This commit is contained in:
Your Name
2026-11-26 15:46:20 +08:00
parent db6d327e91
commit be79e09c83
170 changed files with 21159 additions and 13217 deletions
+9 -1
View File
@@ -16,7 +16,15 @@
"Bash(git *)", "Bash(git *)",
"Bash(tail -c 100000 /Users/long/.claude/projects/-Users-long-Work-zyt/7be9f770-afc3-497d-87a3-2ffa1fbe3fd1.jsonl)", "Bash(tail -c 100000 /Users/long/.claude/projects/-Users-long-Work-zyt/7be9f770-afc3-497d-87a3-2ffa1fbe3fd1.jsonl)",
"Read(//tmp/**)", "Read(//tmp/**)",
"Bash(npx --no-install vue-tsc --noEmit)" "Bash(npx --no-install vue-tsc --noEmit)",
"Bash(python -c \"import paramiko; print\\(paramiko.__version__\\)\")",
"Bash(RH='[IP]' RP='xx12369.36aa!' python rssh.py)",
"Bash(nslookup xt.zhenyangtang.com.cn)",
"Bash(sed -i \"s/c.connect\\(os.environ\\\\['RH'\\\\]/import socket; c.connect\\(socket.gethostbyname\\('xt.zhenyangtang.com.cn'\\)/\" rssh.py)",
"Bash(RP='xx12369.36aa!' python rssh.py)",
"Bash(php -l app/common/service/esign/DoctorEsignIdentityService.php)",
"Bash(php tests/DoctorEsignIdentityTest.php)",
"Bash(php tests/PrescriptionEsignFlowTest.php)"
] ]
} }
} }
+12
View File
@@ -10,6 +10,18 @@ export function systemLogLists(params: any) {
return request.get({ url: '/setting.system.log/lists', params }, { ignoreCancelToken: true }) return request.get({ url: '/setting.system.log/lists', params }, { ignoreCancelToken: true })
} }
export function desktopSessionLists(params: {
date: string
keyword: string
page_no: number
page_size: number
}) {
return request.get(
{ url: '/setting.system.log/desktopSessions', params },
{ ignoreCancelToken: true }
)
}
// 清除系统缓存 // 清除系统缓存
export function systemCacheClear() { export function systemCacheClear() {
return request.post({ url: '/setting.system.cache/clear' }) return request.post({ url: '/setting.system.cache/clear' })
+38 -7
View File
@@ -380,6 +380,15 @@ export interface PrescriptionEsignConfig {
review_enabled?: boolean review_enabled?: boolean
} }
export interface PrescriptionEsignLogEntry {
event: string
label: string
time: number
source: 'tsa' | 'system' | 'local'
actor_name?: string
message?: string
}
export interface PrescriptionEsignStatus extends PrescriptionEsignConfig { export interface PrescriptionEsignStatus extends PrescriptionEsignConfig {
required: boolean required: boolean
status: 'pending' | 'authenticating' | 'signing' | 'signed' | 'failed' | 'uncertain' | 'voided' | 'legacy' status: 'pending' | 'authenticating' | 'signing' | 'signed' | 'failed' | 'uncertain' | 'voided' | 'legacy'
@@ -396,8 +405,17 @@ export interface PrescriptionEsignStatus extends PrescriptionEsignConfig {
issued_at?: number issued_at?: number
signature_time?: number signature_time?: number
signature_time_source?: 'tsa' | 'local' | '' signature_time_source?: 'tsa' | 'local' | ''
doctor_signer_name?: string
review_required?: boolean
review_state?: PrescriptionEsignReviewStatus['state']
review_submitted_at?: number
awaiting_upload?: boolean
can_submit_for_review?: boolean
can_review_prescription?: boolean
review_signer_name?: string review_signer_name?: string
review_signature?: string
review_signature_time?: number review_signature_time?: number
signing_log?: PrescriptionEsignLogEntry[]
signed_at?: number signed_at?: number
auth_url?: string auth_url?: string
} }
@@ -449,6 +467,8 @@ export interface PrescriptionEsignDoctorStatus {
enabled: boolean enabled: boolean
status: 'unbound' | 'needs_mobile' | 'renewal_required' | 'authenticating' | 'binding_required' | 'ready' status: 'unbound' | 'needs_mobile' | 'renewal_required' | 'authenticating' | 'binding_required' | 'ready'
cert_expires_at: number cert_expires_at: number
certificate_state?: 'valid' | 'renewal_required' | 'unconfirmed'
can_edit_signer_name?: boolean
identity_details_required?: boolean identity_details_required?: boolean
quicksign_enabled?: boolean quicksign_enabled?: boolean
quicksign_authorizing?: boolean quicksign_authorizing?: boolean
@@ -463,8 +483,12 @@ export function prescriptionEsignConfig(): Promise<PrescriptionEsignConfig> {
return request.get({ url: '/tcm.prescription/esignConfig' }) return request.get({ url: '/tcm.prescription/esignConfig' })
} }
export function prescriptionEsignStatus(params: { id: number }): Promise<PrescriptionEsignStatus> { export function prescriptionEsignSetConfig(params: { enabled: boolean }): Promise<PrescriptionEsignConfig> {
return request.get({ url: '/tcm.prescription/esignStatus', params }) return request.post({ url: '/tcm.prescription/esignSetConfig', params })
}
export function prescriptionEsignStatus(params: { id: number }, signal?: AbortSignal): Promise<PrescriptionEsignStatus> {
return request.get({ url: '/tcm.prescription/esignStatus', params, signal }, { ignoreCancelToken: true })
} }
/** Read-only identity readiness; this endpoint never submits a signature. */ /** Read-only identity readiness; this endpoint never submits a signature. */
@@ -496,7 +520,7 @@ export function prescriptionEsignDoctorStatus(signal?: AbortSignal): Promise<Pre
) )
} }
export function prescriptionEsignDoctorStart(params: { mobile?: string }): Promise<PrescriptionEsignDoctorStatus> { export function prescriptionEsignDoctorStart(params: { mobile?: string; signer_name?: string }): Promise<PrescriptionEsignDoctorStatus> {
return request.post( return request.post(
{ url: '/tcm.prescription/esignDoctorStart', params, timeout: 180000 }, { url: '/tcm.prescription/esignDoctorStart', params, timeout: 180000 },
{ isOpenRetry: false, retryCount: 0, ignoreCancelToken: true } { isOpenRetry: false, retryCount: 0, ignoreCancelToken: true }
@@ -557,8 +581,8 @@ export function prescriptionDelete(params: { id: number }) {
} }
// 处方详情 // 处方详情
export function prescriptionDetail(params: { id: number }) { export function prescriptionDetail(params: { id: number }, signal?: AbortSignal) {
return request.get({ url: '/tcm.prescription/detail', params }) return request.get({ url: '/tcm.prescription/detail', params, signal }, signal ? { ignoreCancelToken: true } : undefined)
} }
// 根据诊单获取处方列表 // 根据诊单获取处方列表
@@ -572,10 +596,17 @@ export function prescriptionGetByAppointment(params: { appointment_id: number })
} }
// 作废处方 // 作废处方
export function prescriptionVoid(params: { id: number }) { export function prescriptionVoid(params: { id: number; pending_only?: boolean }) {
return request.post({ url: '/tcm.prescription/void', params }) return request.post({ url: '/tcm.prescription/void', params })
} }
export function prescriptionSubmitForReview(params: {
id: number
}): Promise<{ review_submitted_at: number; can_submit_for_review: false }> {
return request.post({ url: '/tcm.prescription/submitForReview', params },
{ isOpenRetry: false, retryCount: 0, ignoreCancelToken: true })
}
/** 处方审核:action approve | reject(驳回同时作废处方) */ /** 处方审核:action approve | reject(驳回同时作废处方) */
export function prescriptionAudit(params: { export function prescriptionAudit(params: {
id: number id: number
@@ -816,7 +847,7 @@ export function prescriptionOrderSetShipMode(params: { id: number; ship_mode: 'g
// ========== 处方库 ========== // ========== 处方库 ==========
export type PrescriptionAiProfile = 'qwen' | 'openai' export type PrescriptionAiProfile = 'qwen' | 'openai' | 'doubao'
export interface PrescriptionLibraryHerb { export interface PrescriptionLibraryHerb {
medicine_id?: number medicine_id?: number
+102 -17
View File
@@ -2,14 +2,19 @@
<el-dialog <el-dialog
:model-value="true" :model-value="true"
:title="reviewer ? '审核签署身份' : '医生电子签署身份'" :title="reviewer ? '审核签署身份' : '医生电子签署身份'"
:width="frameUrl ? 'min(760px, 94vw)' : 'min(520px, 94vw)'" width="min(760px, 94vw)"
top="5vh" top="5vh"
append-to-body append-to-body
:close-on-click-modal="false" :close-on-click-modal="false"
:before-close="dismiss" :before-close="dismiss"
> >
<p class="doctor-esign__message" role="status">{{ guidance }}</p> <p class="doctor-esign__message" role="status">{{ guidance }}</p>
<dl v-if="state?.enabled && state.status === 'ready'" class="doctor-esign__expiry"> <p v-if="statusNotice" class="doctor-esign__message" role="status">{{ statusNotice }}</p>
<dl v-if="state && (certificateLabel || grantActive)" class="doctor-esign__expiry">
<template v-if="certificateLabel">
<dt>签署证书状态</dt>
<dd>{{ certificateLabel }}</dd>
</template>
<template v-if="state.cert_expires_at"> <template v-if="state.cert_expires_at">
<dt>签署证书有效期至</dt> <dt>签署证书有效期至</dt>
<dd>{{ formatExpiry(state.cert_expires_at) }}</dd> <dd>{{ formatExpiry(state.cert_expires_at) }}</dd>
@@ -22,6 +27,17 @@
</template> </template>
</dl> </dl>
<p v-if="error" class="doctor-esign__error" role="alert">{{ error }}</p> <p v-if="error" class="doctor-esign__error" role="alert">{{ error }}</p>
<label v-if="needsSignerName" class="doctor-esign__field">
证件姓名
<el-input
v-model="signerName"
:disabled="!!pending"
autocomplete="off"
:spellcheck="false"
required
placeholder="请输入与本人有效证件一致的姓名"
/>
</label>
<label v-if="needsMobile" class="doctor-esign__field"> <label v-if="needsMobile" class="doctor-esign__field">
本人手机号码 本人手机号码
<el-input <el-input
@@ -67,11 +83,18 @@
{{ state?.quicksign_authorizing ? '确认快捷签授权' : '确认绑定签署身份' }} {{ state?.quicksign_authorizing ? '确认快捷签授权' : '确认绑定签署身份' }}
</el-button> </el-button>
<el-button <el-button
v-if="canResume && !state?.quicksign_authorizing" v-if="canRestartWithSignerName"
:disabled="!!pending"
@click="enterSignerName"
>修改证件姓名</el-button>
<el-button
v-if="canResume && !state?.quicksign_authorizing && !canRestartWithSignerName"
:disabled="!!pending" :disabled="!!pending"
@click="enterMobile" @click="enterMobile"
>重新输入手机号</el-button> >重新输入手机号</el-button>
<el-button :disabled="!!pending" @click="refresh">检查状态</el-button> <el-button :disabled="!!pending" @click="checkStatus">
{{ checkingIdentity ? '检查认证状态' : '重新校验证书' }}
</el-button>
<el-button v-if="frameUrl" link @click="authenticationUnavailable">验证页面不可用</el-button> <el-button v-if="frameUrl" link @click="authenticationUnavailable">验证页面不可用</el-button>
<el-button @click="dismiss">关闭</el-button> <el-button @click="dismiss">关闭</el-button>
</div> </div>
@@ -112,21 +135,42 @@ const state = ref<ReturnType<typeof validateStatus> | null>(null)
const pending = ref<DoctorRequest | null>(null) const pending = ref<DoctorRequest | null>(null)
const frameUrl = ref('') const frameUrl = ref('')
const mobile = ref('') const mobile = ref('')
const signerName = ref('')
const identityNumber = ref('') const identityNumber = ref('')
const editingMobile = ref(false) const editingMobile = ref(false)
const error = ref('') const error = ref('')
const statusNotice = ref('')
const now = ref(Date.now() + props.serverTimeOffsetMs) const now = ref(Date.now() + props.serverTimeOffsetMs)
const authUrl = computed(() => state.value?.auth_url ?? '') const authUrl = computed(() => state.value?.auth_url ?? '')
const authenticating = computed(() => state.value?.enabled === true && state.value.status === 'authenticating') const authenticating = computed(() => state.value?.enabled === true && state.value.status === 'authenticating')
const canResume = computed(() => authenticating.value && !!authUrl.value && !frameUrl.value && !editingMobile.value) const canResume = computed(() => authenticating.value && !!authUrl.value && !frameUrl.value && !editingMobile.value)
const canEditSignerName = computed(() => props.reviewer === true && state.value?.enabled === true
&& state.value.can_edit_signer_name === true && !state.value.quicksign_authorizing)
const canRestartWithSignerName = computed(() => canEditSignerName.value && authenticating.value && !editingMobile.value)
const needsSignerName = computed(() => canEditSignerName.value
&& (state.value?.status === 'unbound' || state.value?.status === 'needs_mobile'
|| (authenticating.value && editingMobile.value)))
const canComplete = computed(() => state.value?.enabled === true && state.value.status === 'binding_required') const canComplete = computed(() => state.value?.enabled === true && state.value.status === 'binding_required')
const checkingIdentity = computed(() => authenticating.value || canComplete.value)
const needsIdentityNumber = computed(() => canComplete.value && !state.value?.quicksign_authorizing const needsIdentityNumber = computed(() => canComplete.value && !state.value?.quicksign_authorizing
&& state.value?.identity_details_required === true) && state.value?.identity_details_required === true)
const needsMobile = computed(() => state.value?.enabled === true const needsMobile = computed(() => state.value?.enabled === true
&& (enrollmentStatuses.includes(state.value.status) || editingMobile.value)) && (enrollmentStatuses.includes(state.value.status) || editingMobile.value))
const certificateState = computed(() => {
const current = state.value
if (!current?.enabled) return ''
if (current.status === 'unbound') return 'unbound'
if (current.certificate_state === 'unconfirmed') return 'unconfirmed'
if (current.status === 'renewal_required' || current.certificate_state === 'renewal_required') return 'renewal_required'
if (current.status !== 'ready' && current.status !== 'needs_mobile') return ''
return current.cert_expires_at * 1000 > now.value ? 'valid' : 'renewal_required'
})
const certificateLabel = computed(() => ({
'': '', unbound: '未绑定', valid: '有效', renewal_required: '需要续期', unconfirmed: '暂无法确认'
})[certificateState.value])
const quickReady = computed(() => state.value?.enabled === true && state.value.status === 'ready' const quickReady = computed(() => state.value?.enabled === true && state.value.status === 'ready'
&& state.value.quicksign_enabled === true) && certificateState.value === 'valid' && state.value.quicksign_enabled === true)
const grantActive = computed(() => quickReady.value && !!state.value && !state.value.quicksign_unavailable_reason const grantActive = computed(() => quickReady.value && !!state.value && !state.value.quicksign_unavailable_reason
&& (state.value.quicksign_remaining_times ?? 0) > 0 && state.value.quicksign_expires_at * 1000 > now.value) && (state.value.quicksign_remaining_times ?? 0) > 0 && state.value.quicksign_expires_at * 1000 > now.value)
const canAuthorizeQuick = computed(() => quickReady.value && !grantActive.value) const canAuthorizeQuick = computed(() => quickReady.value && !grantActive.value)
@@ -137,15 +181,19 @@ const startLabel = computed(() => {
}) })
const guidance = computed(() => { const guidance = computed(() => {
const current = state.value const current = state.value
if (!current) return pending.value === 'status' ? '正在查询医生签署身份…' : '' if (pending.value === 'status' && !checkingIdentity.value) return '正在向 e签宝校验证书…'
if (!current) return ''
if (!current.enabled) return '当前环境未启用医生电子签署身份。' if (!current.enabled) return '当前环境未启用医生电子签署身份。'
if (needsSignerName.value) return '请填写与本人有效证件一致的姓名和本人手机号码,完成人脸认证。'
switch (current.status) { switch (current.status) {
case 'unbound': case 'unbound':
return '首次电子签署前,请验证本人身份并绑定签署证书。' return '首次电子签署前,请验证本人身份并绑定签署证书。'
case 'needs_mobile': case 'needs_mobile':
return '请使用本人手机号码完成签署身份验证。' return '请使用本人手机号码完成签署身份验证。'
case 'renewal_required': case 'renewal_required':
return '签署证书需要续期,请使用本人手机号码完成人脸认证。' return certificateState.value === 'unconfirmed'
? '暂无法确认证书状态,可重新校验,或使用本人手机号码发起续期认证。'
: '签署证书需要续期,请使用本人手机号码完成人脸认证。'
case 'authenticating': case 'authenticating':
if (editingMobile.value) return '请使用本人手机号码完成人脸认证。' if (editingMobile.value) return '请使用本人手机号码完成人脸认证。'
if (current.authUrlUnavailable) return '验证链接不可用,请检查状态后重试。' if (current.authUrlUnavailable) return '验证链接不可用,请检查状态后重试。'
@@ -159,9 +207,11 @@ const guidance = computed(() => {
if (needsIdentityNumber.value) return '人脸认证已通过。首次绑定证书需要补充与本次认证一致的身份证号码。' if (needsIdentityNumber.value) return '人脸认证已通过。首次绑定证书需要补充与本次认证一致的身份证号码。'
return '人脸认证已通过,请确认完成本人的签署身份认证。' return '人脸认证已通过,请确认完成本人的签署身份认证。'
case 'ready': { case 'ready': {
if (certificateState.value !== 'valid') return '请重新校验签署证书后继续。'
if (!quickReady.value) return '医生签署身份已就绪。' if (!quickReady.value) return '医生签署身份已就绪。'
if (grantActive.value) return props.reviewer ? '快捷签授权有效。每张处方由审核人本人确认签名。' if (grantActive.value) return props.reviewer
: '快捷签授权有效。每张处方仍需开方医生本人确认签名。' ? '快捷签授权有效。每张处方由药师本人确认签名。'
: '快捷签授权有效。请回到处方中,由开方医生本人确认签名。'
const reason = current.quicksign_unavailable_reason const reason = current.quicksign_unavailable_reason
if (reason === 'expired' || (current.quicksign_expires_at > 0 && current.quicksign_expires_at * 1000 <= now.value)) { if (reason === 'expired' || (current.quicksign_expires_at > 0 && current.quicksign_expires_at * 1000 <= now.value)) {
return '快捷签授权已过期,请重新授权。' return '快捷签授权已过期,请重新授权。'
@@ -190,11 +240,14 @@ function validTime(value: number) {
function validateStatus(result: PrescriptionEsignDoctorStatus) { function validateStatus(result: PrescriptionEsignDoctorStatus) {
const { const {
enabled, status, cert_expires_at, enabled, status, cert_expires_at, certificate_state,
can_edit_signer_name = false,
identity_details_required = false, quicksign_enabled = false, quicksign_authorizing = false, identity_details_required = false, quicksign_enabled = false, quicksign_authorizing = false,
quicksign_expires_at = 0, quicksign_remaining_times = 0, quicksign_unavailable_reason = '' quicksign_expires_at = 0, quicksign_remaining_times = 0, quicksign_unavailable_reason = ''
} = result } = result
if (!statuses.includes(status) || typeof enabled !== 'boolean' if (!statuses.includes(status) || typeof enabled !== 'boolean'
|| typeof can_edit_signer_name !== 'boolean'
|| (certificate_state !== undefined && !['valid', 'renewal_required', 'unconfirmed'].includes(certificate_state))
|| typeof quicksign_enabled !== 'boolean' || typeof quicksign_authorizing !== 'boolean' || typeof quicksign_enabled !== 'boolean' || typeof quicksign_authorizing !== 'boolean'
|| !validTime(cert_expires_at) || !validTime(quicksign_expires_at) || !validTime(cert_expires_at) || !validTime(quicksign_expires_at)
|| typeof identity_details_required !== 'boolean' || typeof identity_details_required !== 'boolean'
@@ -207,7 +260,7 @@ function validateStatus(result: PrescriptionEsignDoctorStatus) {
const providerUrl = enabled && status === 'authenticating' ? result.auth_url : undefined const providerUrl = enabled && status === 'authenticating' ? result.auth_url : undefined
const auth_url = safeEsignAuthUrl(providerUrl) const auth_url = safeEsignAuthUrl(providerUrl)
return { return {
enabled, status, cert_expires_at, identity_details_required, quicksign_enabled, quicksign_authorizing, enabled, status, cert_expires_at, certificate_state, can_edit_signer_name, identity_details_required, quicksign_enabled, quicksign_authorizing,
quicksign_expires_at, quicksign_remaining_times, quicksign_unavailable_reason, auth_url, quicksign_expires_at, quicksign_remaining_times, quicksign_unavailable_reason, auth_url,
authUrlUnavailable: Boolean(providerUrl && !auth_url) authUrlUnavailable: Boolean(providerUrl && !auth_url)
} }
@@ -215,6 +268,7 @@ function validateStatus(result: PrescriptionEsignDoctorStatus) {
function clearInputs() { function clearInputs() {
mobile.value = '' mobile.value = ''
signerName.value = ''
identityNumber.value = '' identityNumber.value = ''
} }
@@ -239,6 +293,7 @@ function clearStatus() {
state.value = null state.value = null
editingMobile.value = false editingMobile.value = false
error.value = '' error.value = ''
statusNotice.value = ''
} }
function dismiss() { function dismiss() {
@@ -257,8 +312,9 @@ function accept(result: ReturnType<typeof validateStatus>) {
editingMobile.value = false editingMobile.value = false
state.value = result state.value = result
if (!authenticating.value || (frameUrl.value && frameUrl.value !== authUrl.value)) stopAuthentication() if (!authenticating.value || (frameUrl.value && frameUrl.value !== authUrl.value)) stopAuthentication()
if (grantActive.value) { if (certificateState.value === 'valid') {
const expiresIn = result.quicksign_expires_at * 1000 - now.value const expiry = grantActive.value ? Math.min(result.cert_expires_at, result.quicksign_expires_at) : result.cert_expires_at
const expiresIn = expiry * 1000 - now.value
if (expiresIn <= 2147483647) { if (expiresIn <= 2147483647) {
grantExpiryTimer = setTimeout(() => { now.value = Date.now() + props.serverTimeOffsetMs }, expiresIn) grantExpiryTimer = setTimeout(() => { now.value = Date.now() + props.serverTimeOffsetMs }, expiresIn)
} }
@@ -292,6 +348,13 @@ function enterMobile() {
error.value = '' error.value = ''
} }
function enterSignerName() {
if (!canAct() || pending.value || !canRestartWithSignerName.value) return
stopAuthentication()
editingMobile.value = true
error.value = ''
}
async function submit( async function submit(
kind: DoctorRequest, kind: DoctorRequest,
request: () => Promise<PrescriptionEsignDoctorStatus> request: () => Promise<PrescriptionEsignDoctorStatus>
@@ -301,6 +364,7 @@ async function submit(
clearInputs() clearInputs()
clearTimeout(pollTimer) clearTimeout(pollTimer)
error.value = '' error.value = ''
statusNotice.value = ''
pending.value = kind pending.value = kind
try { try {
const result = validateStatus(await request()) const result = validateStatus(await request())
@@ -309,7 +373,7 @@ async function submit(
} catch { } catch {
if (current !== generation || !canAct()) return if (current !== generation || !canAct()) return
clearStatus() clearStatus()
error.value = '医生签署身份状态待确认,请检查状态后继续。' error.value = kind === 'status' ? '签署身份状态待确认,请重新校验证书或检查认证状态。' : '签署身份操作结果待确认,请检查状态后继续。'
return return
} finally { } finally {
if (current === generation) pending.value = null if (current === generation) pending.value = null
@@ -329,18 +393,35 @@ async function refresh() {
} }
} }
async function checkStatus() {
if (!canAct() || pending.value) return
const checkingFlow = checkingIdentity.value
await refresh()
if (!canAct() || !state.value?.enabled || error.value) return
if (checkingFlow) statusNotice.value = '认证状态已更新。'
else if (certificateState.value === 'valid') statusNotice.value = '证书校验通过。'
}
async function start() { async function start() {
if (!canAct() || pending.value) return if (!canAct() || pending.value) return
if (canAuthorizeQuick.value) { if (canAuthorizeQuick.value) {
await submit('start', () => prescriptionEsignDoctorStart({})) await submit('start', () => prescriptionEsignDoctorStart({}))
} else if (needsMobile.value) { } else if (needsMobile.value) {
const number = mobile.value.trim() const number = mobile.value.trim()
clearInputs() const name = needsSignerName.value ? signerName.value.trim() : undefined
if (!/^1[3-9]\d{9}$/.test(number)) { if (!/^1[3-9]\d{9}$/.test(number)) {
if (name === undefined) clearInputs()
error.value = '请输入有效的大陆手机号码。' error.value = '请输入有效的大陆手机号码。'
return return
} }
await submit('start', () => prescriptionEsignDoctorStart({ mobile: number })) if (name !== undefined && !/^[\p{Script=Han}A-Za-z][\p{Script=Han}A-Za-z·()\-]{1,49}$/u.test(name)) {
error.value = '证件姓名须为 2 至 50 个字符,以汉字或英文字母开头,可包含间隔号(·)、半角括号和连字符。'
return
}
await submit('start', () => prescriptionEsignDoctorStart({
mobile: number,
...(name !== undefined ? { signer_name: name } : {})
}))
} }
} }
@@ -361,7 +442,10 @@ async function complete() {
function onVisibilityChange() { function onVisibilityChange() {
if (document.visibilityState === 'visible') void refresh() if (document.visibilityState === 'visible') void refresh()
else clearStatus() else {
clearStatus()
statusNotice.value = '身份验证已暂停,返回此页后会重新检查。'
}
} }
onMounted(() => { onMounted(() => {
@@ -393,6 +477,7 @@ onBeforeUnmount(() => {
.doctor-esign__expiry dt { color: var(--el-text-color-secondary); } .doctor-esign__expiry dt { color: var(--el-text-color-secondary); }
.doctor-esign__expiry dd { margin: 0; } .doctor-esign__expiry dd { margin: 0; }
.doctor-esign__field { display: grid; gap: 6px; max-width: 350px; } .doctor-esign__field { display: grid; gap: 6px; max-width: 350px; }
.doctor-esign__field + .doctor-esign__field { margin-top: 12px; }
.doctor-esign__frame { .doctor-esign__frame {
display: block; display: block;
width: 100%; width: 100%;
+230 -28
View File
@@ -1,17 +1,27 @@
<template> <template>
<section v-show="showControls || signingTime || reviewState?.required" class="esign-panel" aria-label="处方电子签署" v-loading="busy"> <section v-show="showControls || signingTime || showSteps || showSigningLog" class="esign-panel" aria-label="处方电子签署" :aria-busy="busy">
<div class="esign-panel__heading"> <div class="esign-panel__heading">
<strong>医师电子签署</strong> <strong>{{ reviewRequired ? '处方电子签署' : '医师电子签署' }}</strong>
<el-tag v-if="confirmed && state?.environment === 'sandbox' && state.status !== 'legacy'" type="warning" size="small"> <el-tag v-if="state?.environment === 'sandbox' && state.status !== 'legacy'" type="warning" size="small">
沙箱测试 沙箱测试
</el-tag> </el-tag>
</div> </div>
<el-steps v-if="(confirmed || busy) && state?.required && state.status !== 'voided' && (!audit || state.can_sign || state.can_retry_verify)" :active="activeStep" finish-status="success" simple> <div v-if="showSteps" class="esign-panel__progress">
<el-step title="处方草稿已保存" /> <el-steps
<el-step :title="verificationMethod === 'quick' ? '核对快捷签授权' : verificationMethod === 'sms' ? '校验短信验证码' : '验证医生身份'" /> :active="activeStep"
<el-step title="签名并完成" /> :class="{ 'esign-panel__steps--review': reviewRequired }"
</el-steps> finish-status="success"
simple
>
<el-step title="处方草稿已保存" />
<el-step v-if="tracksUpload" title="上传处方" />
<el-step v-else :title="verificationMethod === 'quick' ? '核对快捷签授权' : verificationMethod === 'sms' ? '校验短信验证码' : '验证医生身份'" />
<el-step :title="reviewRequired || tracksUpload ? '医师签署' : '签名并完成'" />
<el-step v-if="reviewRequired" title="药师签署" />
</el-steps>
</div>
<p v-if="message" class="esign-panel__message" aria-live="polite">{{ message }}</p> <p v-if="message" class="esign-panel__message" aria-live="polite">{{ message }}</p>
<p v-if="statusNotice" class="esign-panel__message" role="status">{{ statusNotice }}</p>
<div v-if="signingTime" class="esign-panel__message" aria-live="polite"> <div v-if="signingTime" class="esign-panel__message" aria-live="polite">
<div v-if="signingTime.issuedTime">开具时间:{{ signingTime.issuedTime }}(北京时间)</div> <div v-if="signingTime.issuedTime">开具时间:{{ signingTime.issuedTime }}(北京时间)</div>
<div v-if="signingTime.signatureTime"> <div v-if="signingTime.signatureTime">
@@ -21,11 +31,26 @@
<div>签署时间待核实</div> <div>签署时间待核实</div>
<div v-if="signingTime.verifiedTime">系统验签完成时间:{{ signingTime.verifiedTime }}(北京时间)</div> <div v-if="signingTime.verifiedTime">系统验签完成时间:{{ signingTime.verifiedTime }}(北京时间)</div>
</template> </template>
<div v-if="!audit && state?.review_signature_time">
审核签署时间:{{ formatSigningTime(state.review_signature_time) }}(北京时间 · 可信时间戳)
<span v-if="state.review_signer_name"> · {{ state.review_signer_name }}</span>
</div>
</div> </div>
<p v-if="reviewSigning" class="esign-panel__message esign-panel__review-signature" aria-live="polite">
药师签署时间:<span class="esign-panel__timestamp">{{ reviewSigning.time }}</span>(北京时间 · 可信时间戳)
<span v-if="reviewSigning.name"> · {{ reviewSigning.name }}</span>
</p>
<details v-if="showSigningLog" :key="prescriptionId" class="esign-panel__log">
<summary>签署日志</summary>
<ol v-if="signingLog.length" class="esign-panel__log-list">
<li v-for="(entry, index) in signingLog" :key="`${entry.event}-${entry.time}-${index}`">
<strong>{{ entry.label }}</strong>
<span v-if="entry.actor_name"> · {{ entry.actor_name }}</span>
<div class="esign-panel__log-meta">
<time :datetime="new Date(entry.time * 1000).toISOString()">{{ entry.timeText }}</time>
(北京时间 · {{ entry.sourceLabel }})
</div>
<div v-if="entry.message" class="esign-panel__log-meta">{{ entry.message }}</div>
</li>
</ol>
<p v-else class="esign-panel__message">暂无签署日志。</p>
</details>
<p v-if="error" class="esign-panel__error" role="alert">{{ error }}</p> <p v-if="error" class="esign-panel__error" role="alert">{{ error }}</p>
<label v-if="identityDetailsRequired" class="esign-panel__identity"> <label v-if="identityDetailsRequired" class="esign-panel__identity">
本次验证使用的身份证号 本次验证使用的身份证号
@@ -52,19 +77,31 @@
/> />
</label> </label>
<div v-if="showControls && prescriptionId > 0" class="esign-panel__actions"> <div v-if="showControls && prescriptionId > 0" class="esign-panel__actions">
<el-button type="primary" size="small" :disabled="busy || dialogVisible || (action.run === sendSms && smsSendCoolingDown)" @click="action.run"> <el-button type="primary" size="small" :disabled="busy || dialogVisible || (action.run === sendSms && smsSendCoolingDown)" @click="runAction">
{{ action.label }} {{ action.label }}
</el-button> </el-button>
<el-button v-if="smsCodeEntry" size="small" :disabled="busy || smsSendCoolingDown" @click="sendSms"> <el-button v-if="smsCodeEntry" size="small" :disabled="busy || smsSendCoolingDown" @click="sendSms">
{{ smsSendCoolingDown ? '请稍后重新发送' : '重新发送验证码' }} {{ smsSendCoolingDown ? '请稍后重新发送' : '重新发送验证码' }}
</el-button> </el-button>
<el-button v-if="readiness" size="small" :disabled="busy" @click="closeAuthentication">取消</el-button> <el-button v-if="readiness || smsCodeEntry" size="small" :disabled="busy" @click="closeAuthentication">退出签署</el-button>
<el-button
v-if="canOpenCertificate"
size="small"
:disabled="busy || dialogVisible"
@click="doctorIdentityOpen = true"
>签署身份与证书</el-button>
</div> </div>
<EsignDoctorDialog
v-if="doctorIdentityOpen"
:server-time-offset-ms="userStore.serverTimeOffsetMs"
@close="closeDoctorIdentity"
/>
<EsignReviewPanel <EsignReviewPanel
v-if="audit && confirmed && state" v-if="audit && state"
:prescription-id="prescriptionId" :prescription-id="prescriptionId"
:order-id="reviewOrderId" :order-id="reviewOrderId"
:doctor-signed="state.status === 'signed'" :doctor-signed="state.status === 'signed'"
:doctor-status-confirmed="confirmed"
@change="updateReview" @change="updateReview"
/> />
<el-dialog <el-dialog
@@ -89,7 +126,7 @@
/> />
<template #footer> <template #footer>
<el-button link @click="authenticationUnavailable">验证页面不可用</el-button> <el-button link @click="authenticationUnavailable">验证页面不可用</el-button>
<el-button @click="closeAuthentication">关闭</el-button> <el-button @click="closeAuthentication">退出签署</el-button>
</template> </template>
</el-dialog> </el-dialog>
</section> </section>
@@ -104,6 +141,7 @@ import {
prescriptionEsignStart, prescriptionEsignStart,
prescriptionEsignStatus, prescriptionEsignStatus,
prescriptionEsignVerifyWillingness, prescriptionEsignVerifyWillingness,
prescriptionSubmitForReview,
type PrescriptionEsignIdentityStatus, type PrescriptionEsignIdentityStatus,
type PrescriptionEsignReviewStatus, type PrescriptionEsignReviewStatus,
type PrescriptionEsignStatus type PrescriptionEsignStatus
@@ -119,12 +157,15 @@ import {
validateEsignStatus validateEsignStatus
} from '@/utils/prescription-esign' } from '@/utils/prescription-esign'
import EsignReviewPanel from '@/components/EsignReviewPanel.vue' import EsignReviewPanel from '@/components/EsignReviewPanel.vue'
import EsignDoctorDialog from '@/components/EsignDoctorDialog.vue'
import useUserStore from '@/stores/modules/user'
const props = defineProps<{ prescriptionId: number; initialState?: PrescriptionEsignStatus; audit?: boolean; reviewOrderId?: number }>() const props = defineProps<{ prescriptionId: number; initialState?: PrescriptionEsignStatus; audit?: boolean; reviewOrderId?: number }>()
const emit = defineEmits<{ const emit = defineEmits<{
(e: 'status-change', state: PrescriptionEsignStatus): void (e: 'status-change', state: PrescriptionEsignStatus): void
(e: 'review-change', state: PrescriptionEsignReviewStatus | null): void (e: 'review-change', state: PrescriptionEsignReviewStatus | null): void
}>() }>()
const userStore = useUserStore()
const reviewState = ref<PrescriptionEsignReviewStatus | null>(null) const reviewState = ref<PrescriptionEsignReviewStatus | null>(null)
function updateReview(result: PrescriptionEsignReviewStatus | null) { function updateReview(result: PrescriptionEsignReviewStatus | null) {
@@ -141,12 +182,52 @@ function initialStatus(): PrescriptionEsignStatus | null {
} }
const state = ref<PrescriptionEsignStatus | null>(initialStatus()) const state = ref<PrescriptionEsignStatus | null>(initialStatus())
const work = ref<'status' | 'start' | 'identity' | 'send-sms' | 'verify-sms' | 'sign' | 'verify' | 'download' | null>(null) const work = ref<'status' | 'upload' | 'start' | 'identity' | 'send-sms' | 'verify-sms' | 'sign' | 'verify' | 'download' | null>(null)
const busy = computed(() => work.value !== null) const busy = computed(() => work.value !== null)
const confirmed = ref(false) const confirmed = ref(false)
const awaitingUpload = computed(() => state.value?.awaiting_upload === true)
const tracksUpload = computed(() => awaitingUpload.value || Number(state.value?.review_submitted_at) > 0)
const showControls = computed(() => !props.audit || !confirmed.value || !canApprovePrescriptionEsign(state.value)) const showControls = computed(() => !props.audit || !confirmed.value || !canApprovePrescriptionEsign(state.value))
const signingTime = computed(() => prescriptionEsignTiming(state.value)) const signingTime = computed(() => prescriptionEsignTiming(state.value))
const logSourceLabels = { tsa: '可信时间戳', system: '系统记录', local: '签名记录时间' }
const signingLog = computed(() => {
const entries = state.value?.signing_log
if (!Array.isArray(entries)) return []
return entries.flatMap((entry) => {
if (!entry || typeof entry.event !== 'string' || !entry.event.trim()
|| typeof entry.label !== 'string' || !entry.label.trim()
|| !['tsa', 'system', 'local'].includes(entry.source)) return []
const timeText = formatSigningTime(entry.time)
return timeText ? [{ ...entry, timeText, sourceLabel: logSourceLabels[entry.source] }] : []
}).sort((a, b) => a.time - b.time)
})
const showSigningLog = computed(() => signingLog.value.length > 0
|| (!props.audit && (state.value?.required === true || Boolean(signingTime.value))))
const reviewSigning = computed(() => {
const current = state.value
if (current?.status !== 'signed' && current?.status !== 'voided') return null
const time = formatSigningTime(current.review_signature_time)
if (time) return { time, name: current.review_signer_name }
const review = reviewState.value
if (review?.state !== 'signed') return null
const auditTime = formatSigningTime(review.signature_time)
return auditTime ? { time: auditTime, name: review.signer_name } : null
})
const reviewRequired = computed(() => state.value?.review_required === true || reviewState.value?.required === true
|| Boolean(reviewSigning.value))
const showSteps = computed(() => {
const current = state.value
if (!current) return false
if (reviewRequired.value) return current.status !== 'voided' || Boolean(reviewSigning.value)
return (confirmed.value || busy.value) && current.required && current.status !== 'voided'
&& (!props.audit || current.can_sign || current.can_retry_verify === true)
})
const error = ref('') const error = ref('')
const statusNotice = ref('')
const doctorIdentityOpen = ref(false)
const dialogVisible = ref(false) const dialogVisible = ref(false)
const readiness = ref<'ready' | 'details' | null>(null) const readiness = ref<'ready' | 'details' | null>(null)
const restartRequired = ref(false) const restartRequired = ref(false)
@@ -162,7 +243,7 @@ const verificationMethod = computed(() => state.value?.verification_method)
const accountSetupMessage = computed(() => { const accountSetupMessage = computed(() => {
const current = state.value const current = state.value
if (!current?.can_sign || !verificationMethod.value) return '' if (!current?.can_sign || !verificationMethod.value) return ''
const settings = '请返回页面右上角账号菜单,在「医生电子签署身份」中处理。完成后回到处方查询签署状态。' const settings = '请打开「签署身份与证书」处理后继续。'
if (current.doctor_identity_required && !(verificationMethod.value === 'sms' && smsProfileReady.value)) { if (current.doctor_identity_required && !(verificationMethod.value === 'sms' && smsProfileReady.value)) {
return `${current.message || '请先完成医生签署身份认证。'} ${settings}` return `${current.message || '请先完成医生签署身份认证。'} ${settings}`
} }
@@ -177,21 +258,25 @@ const smsCodeEntry = computed(() => confirmed.value && smsCodeState.value === 'e
const identityResumable = computed(() => !verificationMethod.value && canCheckEsignIdentity(state.value) const identityResumable = computed(() => !verificationMethod.value && canCheckEsignIdentity(state.value)
&& (state.value?.can_resume_identity === true || Boolean(authUrl.value))) && (state.value?.can_resume_identity === true || Boolean(authUrl.value)))
const activeStep = computed(() => { const activeStep = computed(() => {
if (state.value?.status === 'signed') return 3 if (awaitingUpload.value) return 1
if (reviewSigning.value) return 4
if (state.value?.status === 'signed' && state.value.can_download) return 3
if (tracksUpload.value) return 2
if (readiness.value || work.value === 'sign' || work.value === 'verify' if (readiness.value || work.value === 'sign' || work.value === 'verify'
|| state.value?.status === 'signing' || state.value?.status === 'uncertain') return 2 || state.value?.status === 'signing' || state.value?.status === 'uncertain') return 2
return 1 return 1
}) })
const message = computed(() => { const message = computed(() => {
if (props.prescriptionId <= 0) return '缺少关联处方,无法核对签署状态。' if (props.prescriptionId <= 0) return '缺少关联处方,无法核对签署状态。'
if (props.audit && work.value === 'status') return '正在查询签署状态…' if (work.value === 'status') return '正在查询签署状态…'
if (work.value === 'identity' && verificationMethod.value === 'quick') return '正在核对快捷签授权…' if (work.value === 'upload') return '正在上传处方…'
if (work.value === 'identity' && verificationMethod.value === 'sms') return '正在查询短信验证状态…' if (work.value === 'identity' && !readiness.value && verificationMethod.value === 'quick') return '正在核对快捷签授权…'
if (work.value === 'identity' && !readiness.value && verificationMethod.value === 'sms') return '正在查询短信验证状态…'
if (work.value === 'send-sms') return '正在向医生绑定的手机号发送验证码…' if (work.value === 'send-sms') return '正在向医生绑定的手机号发送验证码…'
if (work.value === 'verify-sms') return '正在校验短信验证码…' if (work.value === 'verify-sms') return '正在校验短信验证码…'
if (work.value === 'sign') return '正在签署处方…' if (work.value === 'sign') return '正在签署处方…'
if (work.value === 'verify') return '正在校验已签文件…' if (work.value === 'verify') return '正在校验已签文件…'
if (!confirmed.value || error.value) return '' if (error.value || (!confirmed.value && !state.value)) return ''
if (readiness.value) { if (readiness.value) {
if (verificationMethod.value === 'quick') return '快捷签授权已核对。请核对处方内容后确认签名。' if (verificationMethod.value === 'quick') return '快捷签授权已核对。请核对处方内容后确认签名。'
if (verificationMethod.value === 'sms') return '短信验证码已通过。请核对处方内容后确认签名。' if (verificationMethod.value === 'sms') return '短信验证码已通过。请核对处方内容后确认签名。'
@@ -199,8 +284,18 @@ const message = computed(() => {
} }
const current = state.value const current = state.value
if (!current) return '' if (!current) return ''
if (awaitingUpload.value) {
if (current.can_submit_for_review !== true) return current.message || '请开方医生先上传处方。'
if (current.status === 'signed' && current.can_download) return '医师已签署,请上传处方后进入审核。'
return current.required ? '请先上传处方,再由开方医生本人签署。' : '请上传处方,提交药师审核。'
}
if (current.status === 'legacy' && !current.enabled) return current.message || '此处方使用手写签名。' if (current.status === 'legacy' && !current.enabled) return current.message || '此处方使用手写签名。'
if (current.status === 'signed') return current.can_download ? '处方已签署。' : '处方已签署,原件暂不可用。' if (current.status === 'signed') {
if (reviewRequired.value && !reviewSigning.value) {
return current.can_download ? '医师已签署,等待药师审核签署。' : '医师已签署,原件暂不可用,请查询签署状态。'
}
return current.can_download ? '处方已签署。' : '处方已签署,原件暂不可用。'
}
if (current.required && ['pending', 'authenticating', 'failed'].includes(current.status)) { if (current.required && ['pending', 'authenticating', 'failed'].includes(current.status)) {
if (accountSetupMessage.value) return accountSetupMessage.value if (accountSetupMessage.value) return accountSetupMessage.value
if (canUseMethod(current, 'quick')) { if (canUseMethod(current, 'quick')) {
@@ -224,6 +319,11 @@ const message = computed(() => {
}) })
const action = computed(() => { const action = computed(() => {
if (!confirmed.value) return { label: '查询签署状态', run: refresh } if (!confirmed.value) return { label: '查询签署状态', run: refresh }
if (awaitingUpload.value) {
return !props.audit && state.value?.can_submit_for_review === true
? { label: '上传处方', run: upload }
: { label: '查询签署状态', run: refresh }
}
if (state.value?.can_download && (state.value.status === 'signed' || state.value.status === 'voided')) { if (state.value?.can_download && (state.value.status === 'signed' || state.value.status === 'voided')) {
return { label: '下载已签 PDF', run: download } return { label: '下载已签 PDF', run: download }
} }
@@ -246,6 +346,8 @@ const action = computed(() => {
} }
return { label: '查询签署状态', run: refresh } return { label: '查询签署状态', run: refresh }
}) })
const canOpenCertificate = computed(() => confirmed.value
&& (canUseMethod(state.value, 'quick') || canUseMethod(state.value, 'sms')))
const pollInterval = 5000 const pollInterval = 5000
const authenticationTimeout = 10 * 60 * 1000 const authenticationTimeout = 10 * 60 * 1000
@@ -268,6 +370,7 @@ function isCurrent(current: number, id: number) {
function canUseMethod(result: PrescriptionEsignStatus | null, method: VerificationMethod): boolean { function canUseMethod(result: PrescriptionEsignStatus | null, method: VerificationMethod): boolean {
return result?.verification_method === method && result.enabled && result.required && result.can_sign return result?.verification_method === method && result.enabled && result.required && result.can_sign
&& result.awaiting_upload !== true
&& ['pending', 'authenticating', 'failed'].includes(result.status) && ['pending', 'authenticating', 'failed'].includes(result.status)
} }
@@ -300,7 +403,17 @@ function cancelWork() {
} }
function closeAuthentication() { function closeAuthentication() {
if (dialogVisible.value || readiness.value) cancelWork() if (dialogVisible.value || readiness.value || smsCodeEntry.value) {
cancelWork()
confirmed.value = false
error.value = ''
statusNotice.value = '已退出本次签署,可查询状态后继续。'
}
}
function closeDoctorIdentity() {
doctorIdentityOpen.value = false
void refresh()
} }
function stopVerification(message: string) { function stopVerification(message: string) {
@@ -574,8 +687,9 @@ async function refresh() {
work.value = 'status' work.value = 'status'
confirmed.value = false confirmed.value = false
error.value = '' error.value = ''
statusNotice.value = ''
try { try {
const result = validateEsignStatus(await prescriptionEsignStatus({ id })) const result = validateEsignStatus(await requestIdentity((signal) => prescriptionEsignStatus({ id }, signal)))
if (!isCurrent(current, id)) return if (!isCurrent(current, id)) return
accept(result) accept(result)
// A previous SMS failure can retain the setup flag after the doctor fixes the profile. // A previous SMS failure can retain the setup flag after the doctor fixes the profile.
@@ -602,6 +716,45 @@ async function refresh() {
} }
} }
async function runAction() {
const run = action.value.run
const current = operation
await run()
if (run === refresh && operation === current + 1 && confirmed.value && !error.value && isCurrent(operation, props.prescriptionId)) {
statusNotice.value = '签署状态已更新。'
}
}
async function upload() {
const before = state.value
if (!canAct() || !confirmed.value || props.audit || !awaitingUpload.value || before?.can_submit_for_review !== true) return
const id = props.prescriptionId
const current = ++operation
work.value = 'upload'
error.value = ''
statusNotice.value = ''
try {
const result = await prescriptionSubmitForReview({ id })
if (!isCurrent(current, id)) return
if (!Number.isSafeInteger(result?.review_submitted_at) || result.review_submitted_at <= 0) {
throw new Error('无法核对上传结果')
}
accept({
...before,
review_submitted_at: result.review_submitted_at,
awaiting_upload: false,
can_submit_for_review: false
})
} catch {
if (isCurrent(current, id)) error.value = '暂未确认处方上传,请重试。'
return
} finally {
if (isCurrent(current, id)) work.value = null
}
await refresh()
if (isCurrent(current + 1, id)) statusNotice.value = '处方已上传。'
}
async function download() { async function download() {
if (!canAct() || !confirmed.value || !state.value?.can_download if (!canAct() || !confirmed.value || !state.value?.can_download
|| (state.value.status !== 'signed' && state.value.status !== 'voided')) return || (state.value.status !== 'signed' && state.value.status !== 'voided')) return
@@ -610,7 +763,7 @@ async function download() {
work.value = 'download' work.value = 'download'
error.value = '' error.value = ''
try { try {
const result = validateEsignStatus(await prescriptionEsignStatus({ id })) const result = validateEsignStatus(await requestIdentity((signal) => prescriptionEsignStatus({ id }, signal)))
if (!isCurrent(current, id)) return if (!isCurrent(current, id)) return
accept(result) accept(result)
if (result.can_download && (result.status === 'signed' || result.status === 'voided')) { if (result.can_download && (result.status === 'signed' || result.status === 'voided')) {
@@ -627,7 +780,12 @@ async function download() {
function onVisibilityChange() { function onVisibilityChange() {
if (document.visibilityState === 'visible') return if (document.visibilityState === 'visible') return
if (dialogVisible.value || readiness.value) {
confirmed.value = false
statusNotice.value = '签署验证已暂停,可查询状态后继续。'
}
if (work.value === 'sign') error.value = '签署结果待确认,请查询签署状态。' if (work.value === 'sign') error.value = '签署结果待确认,请查询签署状态。'
if (work.value === 'upload') error.value = '上传结果待确认,请查询处方状态。'
if (work.value === 'verify') error.value = '校验结果待确认,请查询签署状态。' if (work.value === 'verify') error.value = '校验结果待确认,请查询签署状态。'
if (work.value === 'send-sms') error.value = '短信发送状态待确认,请查询签署状态。' if (work.value === 'send-sms') error.value = '短信发送状态待确认,请查询签署状态。'
if (work.value === 'verify-sms') error.value = '短信校验结果待确认,请查询签署状态。' if (work.value === 'verify-sms') error.value = '短信校验结果待确认,请查询签署状态。'
@@ -639,11 +797,16 @@ function resetStatus() {
restartRequired.value = false restartRequired.value = false
confirmed.value = false confirmed.value = false
error.value = '' error.value = ''
statusNotice.value = ''
doctorIdentityOpen.value = false
state.value = initialStatus() state.value = initialStatus()
void refresh() void refresh()
} }
watch(() => props.prescriptionId, resetStatus, { immediate: true }) watch(() => props.prescriptionId, () => {
reviewState.value = null
resetStatus()
}, { immediate: true })
watch(() => props.initialState, (value) => { watch(() => props.initialState, (value) => {
// An emitted state echoed by the parent preserves this interaction. // An emitted state echoed by the parent preserves this interaction.
if (toRaw(value) !== toRaw(state.value)) resetStatus() if (toRaw(value) !== toRaw(state.value)) resetStatus()
@@ -675,11 +838,40 @@ onBeforeUnmount(() => {
} }
.esign-panel :deep(.el-steps) { margin: 10px 0; padding: 10px 12px; } .esign-panel :deep(.el-steps) { margin: 10px 0; padding: 10px 12px; }
.esign-panel :deep(.el-step.is-simple .el-step__title) { font-size: 13px; line-height: 1.4; word-break: normal; } .esign-panel :deep(.el-step.is-simple .el-step__title) { font-size: 13px; line-height: 1.4; word-break: normal; }
.esign-panel__progress { container-type: inline-size; }
.esign-panel__steps--review {
display: grid;
grid-template-columns: 1fr;
gap: 8px 12px;
}
.esign-panel__steps--review :deep(.el-step.is-simple:last-of-type) { max-width: none !important; }
.esign-panel__steps--review :deep(.el-step.is-simple .el-step__title) { max-width: none; white-space: nowrap; }
.esign-panel__steps--review :deep(.el-step.is-simple .el-step__arrow) { display: none; }
.esign-panel__review-signature { overflow-wrap: anywhere; }
.esign-panel__timestamp { white-space: nowrap; }
.esign-panel__actions { margin-top: 10px; } .esign-panel__actions { margin-top: 10px; }
.esign-panel__actions .el-button + .el-button { margin-left: 0; } .esign-panel__actions .el-button + .el-button { margin-left: 0; }
.esign-panel__message, .esign-panel__error { margin: 8px 0; font-size: 13px; } .esign-panel__message, .esign-panel__error { margin: 8px 0; font-size: 13px; }
.esign-panel__message { color: var(--el-text-color-secondary); } .esign-panel__message { color: var(--el-text-color-secondary); }
.esign-panel__error { color: var(--el-color-danger); } .esign-panel__error { color: var(--el-color-danger); }
.esign-panel__log {
margin: 10px 0;
font-size: 13px;
}
.esign-panel__log summary {
width: fit-content;
color: var(--el-color-primary);
cursor: pointer;
font-weight: 500;
}
.esign-panel__log-list {
margin: 8px 0 0;
padding-inline-start: 24px;
list-style: decimal;
overflow-wrap: anywhere;
}
.esign-panel__log-list li + li { margin-top: 8px; }
.esign-panel__log-meta { color: var(--el-text-color-secondary); }
.esign-panel__identity { display: grid; gap: 6px; max-width: 320px; margin: 10px 0; font-size: 13px; } .esign-panel__identity { display: grid; gap: 6px; max-width: 320px; margin: 10px 0; font-size: 13px; }
.esign-panel__frame { .esign-panel__frame {
display: block; display: block;
@@ -690,5 +882,15 @@ onBeforeUnmount(() => {
border-radius: 4px; border-radius: 4px;
background: white; background: white;
} }
@container (min-width: 280px) {
.esign-panel__steps--review { grid-template-columns: repeat(2, minmax(max-content, 1fr)); }
}
@container (min-width: 480px) {
.esign-panel__steps--review { grid-template-columns: repeat(4, minmax(max-content, 1fr)); gap: 0; }
.esign-panel__steps--review :deep(.el-step.is-simple:not(:last-of-type) .el-step__arrow) {
display: flex;
min-width: 18px;
}
}
@media print { .esign-panel { display: none; } } @media print { .esign-panel { display: none; } }
</style> </style>
+24 -34
View File
@@ -1,17 +1,16 @@
<template> <template>
<div v-if="state?.required || error" class="esign-review" v-loading="busy" aria-label="处方审核电子签署"> <div v-if="state?.required || error || busy" class="esign-review" :aria-busy="busy" aria-label="处方审核电子签署">
<strong>审核电子签署</strong> <strong>审核电子签署</strong>
<p v-if="state?.actor_name">当前审核人 {{ state.actor_name }}</p> <p v-if="state?.actor_name">当前审核人 {{ state.actor_name }}</p>
<p v-if="state?.state === 'signed'">
{{ state.signer_name }} · {{ formatSigningTime(state.signature_time) }}(北京时间 · 可信时间戳)
</p>
<p v-if="state?.message" aria-live="polite">{{ state.message }}</p> <p v-if="state?.message" aria-live="polite">{{ state.message }}</p>
<p v-if="busy && !state" role="status">正在查询药师签署状态…</p>
<p v-if="statusNotice" role="status">{{ statusNotice }}</p>
<p v-if="error" class="text-danger" role="alert">{{ error }}</p> <p v-if="error" class="text-danger" role="alert">{{ error }}</p>
<div class="esign-review__actions"> <div class="esign-review__actions">
<el-button v-if="state?.can_confirm" type="primary" size="small" :disabled="busy" @click="confirm(false)"> <el-button v-if="state?.can_confirm" type="primary" size="small" :disabled="busy || !doctorStatusConfirmed" @click="confirm(false)">
确认签名 确认签名
</el-button> </el-button>
<el-button v-if="state?.can_retry_verify" type="primary" size="small" :disabled="busy" @click="confirm(true)"> <el-button v-if="state?.can_retry_verify" type="primary" size="small" :disabled="busy || !doctorStatusConfirmed" @click="confirm(true)">
重试验签 重试验签
</el-button> </el-button>
<el-button v-if="state?.required && doctorSigned" size="small" :disabled="busy" @click="download"> <el-button v-if="state?.required && doctorSigned" size="small" :disabled="busy" @click="download">
@@ -25,10 +24,7 @@
> >
审核签署身份 审核签署身份
</el-button> </el-button>
<el-button v-if="state?.required && !state.can_approve" size="small" :disabled="busy" @click="switchReviewer"> <el-button v-if="error || state?.state !== 'signed'" size="small" :disabled="busy" @click="checkStatus">
切换审核账号
</el-button>
<el-button v-if="error || state?.state !== 'signed'" size="small" :disabled="busy" @click="refresh">
刷新签署状态 刷新签署状态
</el-button> </el-button>
</div> </div>
@@ -43,7 +39,6 @@
<script setup lang="ts"> <script setup lang="ts">
import { onBeforeUnmount, ref, watch } from 'vue' import { onBeforeUnmount, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { import {
prescriptionEsignReviewConfirm, prescriptionEsignReviewConfirm,
@@ -52,18 +47,16 @@ import {
} from '@/api/tcm' } from '@/api/tcm'
import EsignDoctorDialog from '@/components/EsignDoctorDialog.vue' import EsignDoctorDialog from '@/components/EsignDoctorDialog.vue'
import useUserStore from '@/stores/modules/user' import useUserStore from '@/stores/modules/user'
import feedback from '@/utils/feedback' import { downloadOriginalEsignPdf } from '@/utils/prescription-esign'
import { downloadOriginalEsignPdf, formatSigningTime } from '@/utils/prescription-esign'
const props = defineProps<{ prescriptionId: number; orderId?: number; doctorSigned: boolean }>() const props = defineProps<{ prescriptionId: number; orderId?: number; doctorSigned: boolean; doctorStatusConfirmed: boolean }>()
const emit = defineEmits<{ (e: 'change', value: PrescriptionEsignReviewStatus | null): void }>() const emit = defineEmits<{ (e: 'change', value: PrescriptionEsignReviewStatus | null): void }>()
const state = ref<PrescriptionEsignReviewStatus | null>(null) const state = ref<PrescriptionEsignReviewStatus | null>(null)
const identityOpen = ref(false) const identityOpen = ref(false)
const busy = ref(false) const busy = ref(false)
const error = ref('') const error = ref('')
const statusNotice = ref('')
const userStore = useUserStore() const userStore = useUserStore()
const route = useRoute()
const router = useRouter()
let generation = 0 let generation = 0
let statusRequest: AbortController | undefined let statusRequest: AbortController | undefined
@@ -80,7 +73,7 @@ function accept(result: PrescriptionEsignReviewStatus) {
throw new Error('登录账号或审核状态已变化,请刷新页面') throw new Error('登录账号或审核状态已变化,请刷新页面')
} }
state.value = result state.value = result
emit('change', result) emit('change', props.doctorStatusConfirmed ? result : null)
} }
function target() { function target() {
@@ -93,6 +86,7 @@ async function refresh() {
statusRequest = new AbortController() statusRequest = new AbortController()
busy.value = true busy.value = true
error.value = '' error.value = ''
statusNotice.value = ''
emit('change', null) emit('change', null)
try { try {
const result = await prescriptionEsignReviewStatus(target(), statusRequest.signal) const result = await prescriptionEsignReviewStatus(target(), statusRequest.signal)
@@ -106,7 +100,7 @@ async function refresh() {
async function confirm(verifyOnly: boolean) { async function confirm(verifyOnly: boolean) {
const actorId = state.value?.actor_id const actorId = state.value?.actor_id
if (busy.value || !actorId || !(verifyOnly ? state.value?.can_retry_verify : state.value?.can_confirm)) return if (busy.value || !props.doctorStatusConfirmed || !actorId || !(verifyOnly ? state.value?.can_retry_verify : state.value?.can_confirm)) return
const ticket = ++generation const ticket = ++generation
busy.value = true busy.value = true
error.value = '' error.value = ''
@@ -125,19 +119,10 @@ async function confirm(verifyOnly: boolean) {
} }
} }
async function switchReviewer() { async function checkStatus() {
try { const current = generation
await feedback.confirm('当前账号将退出。请所选审核人本人登录。') await refresh()
if (busy.value) return if (generation === current + 1 && state.value && !error.value) statusNotice.value = '药师签署状态已更新。'
busy.value = true
const returnTo = router.resolve({
path: route.path,
query: props.orderId ? { review_order: props.orderId } : { review_prescription: props.prescriptionId }
}).fullPath
await userStore.logout(returnTo)
} catch {
busy.value = false
}
} }
async function download() { async function download() {
@@ -158,11 +143,16 @@ async function download() {
function closeIdentity() { function closeIdentity() {
identityOpen.value = false identityOpen.value = false
void refresh() void checkStatus()
} }
watch(() => [props.prescriptionId, props.orderId, props.doctorSigned, userStore.userInfo.id], watch(() => [props.prescriptionId, props.orderId, userStore.userInfo.id], () => {
() => { if (props.prescriptionId > 0) void refresh() }, { immediate: true }) identityOpen.value = false
state.value = null
if (props.prescriptionId > 0) void refresh()
}, { immediate: true })
watch(() => props.doctorSigned, () => { if (props.prescriptionId > 0) void refresh() })
watch(() => props.doctorStatusConfirmed, (confirmed) => emit('change', confirmed && !busy.value && !error.value ? state.value : null))
onBeforeUnmount(() => { onBeforeUnmount(() => {
generation++ generation++
statusRequest?.abort() statusRequest?.abort()
@@ -0,0 +1,115 @@
<template>
<div v-if="prescriptionId !== null" class="prescription-audit-layout">
<section class="prescription-audit-preview" aria-label="处方单" :aria-busy="loading">
<PrescriptionSlip v-if="detail" :data="detail" compact />
<el-skeleton v-else-if="loading" :rows="8" animated />
<div v-if="error" class="prescription-audit-preview__error" role="status">
<span>{{ error }}</span>
<el-button v-if="prescriptionId > 0" size="small" @click="retry++">重试加载处方</el-button>
</div>
</section>
<section class="prescription-audit-controls" aria-label="签署和审核">
<slot />
</section>
</div>
<slot v-else />
</template>
<script setup lang="ts">
import { ref, watch } from 'vue'
import { prescriptionDetail } from '@/api/tcm'
import PrescriptionSlip from '@/components/prescription-slip/index.vue'
const props = defineProps<{
prescriptionId: number | null
doctorSignedAt?: number
pharmacistSignedAt?: number
}>()
const detail = ref<Record<string, any> | null>(null)
const retry = ref(0)
const loading = ref(false)
const error = ref('')
watch([
() => props.prescriptionId,
() => props.doctorSignedAt,
() => props.pharmacistSignedAt,
retry
], async ([id, doctorAt, pharmacistAt, attempt], previous, onCleanup) => {
if (id !== previous?.[0]) detail.value = null
loading.value = false
error.value = ''
if (id === null) return
if (!Number.isSafeInteger(id) || id <= 0) {
error.value = '当前订单未关联处方'
return
}
const current = detail.value?.esign
if (detail.value && attempt === previous?.[3]
&& (!doctorAt || doctorAt === (current?.signature_time || current?.signed_at))
&& (!pharmacistAt || pharmacistAt === current?.review_signature_time)) return
const controller = new AbortController()
onCleanup(() => controller.abort())
loading.value = true
try {
const response = await prescriptionDetail({ id }, controller.signal)
const result = response?.data ?? response
if (controller.signal.aborted) return
if (Number(result?.id) !== id) throw new Error('处方编号不匹配')
detail.value = result
} catch {
if (!controller.signal.aborted) error.value = '无法加载处方单,请重试。'
} finally {
if (!controller.signal.aborted) loading.value = false
}
}, { immediate: true })
</script>
<style scoped>
.prescription-audit-layout {
display: grid;
grid-template-columns: minmax(0, 1.42fr) minmax(320px, 1fr);
gap: 18px;
align-items: start;
}
.prescription-audit-preview,
.prescription-audit-controls {
min-width: 0;
max-height: min(68vh, 780px);
overflow: auto;
scrollbar-gutter: stable;
}
.prescription-audit-preview {
padding: 10px;
border: 1px solid var(--el-border-color-light);
border-radius: 8px;
background: var(--el-fill-color-light);
}
.prescription-audit-controls { padding-right: 3px; }
.prescription-audit-preview__error {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
padding: 10px;
color: var(--el-text-color-regular);
}
@media (max-width: 840px) {
.prescription-audit-layout {
grid-template-columns: minmax(0, 1fr);
gap: 12px;
max-height: 70vh;
overflow-y: auto;
}
.prescription-audit-preview { max-height: min(50vh, 560px); }
.prescription-audit-controls { max-height: none; overflow: visible; }
}
</style>
+118 -16
View File
@@ -1,5 +1,5 @@
<template> <template>
<div ref="paperRef" class="rx-paper"> <div ref="paperRef" class="rx-paper" :class="{ 'rx-paper--compact': compact }">
<div class="rx-title">{{ isInternal ? '药房联' : slipTitle }}</div> <div class="rx-title">{{ isInternal ? '药房联' : slipTitle }}</div>
<div class="rx-notice"> <div class="rx-notice">
<span class="rx-notice-text"> <span class="rx-notice-text">
@@ -154,21 +154,34 @@
</div> </div>
<div class="rx-bottom"> <div class="rx-bottom">
<div class="rx-bot-row rx-bot-row-1" :class="{ 'rx-bot-row-1--user': !isInternal }"> <div
class="rx-bot-row rx-bot-row-1"
:class="{ 'rx-bot-row-1--user': !isInternal, 'rx-bot-row-1--reviewed': reviewerName }"
>
<div class="rx-bot-cell rx-bot-doctor"> <div class="rx-bot-cell rx-bot-doctor">
<div class="rx-bot-label rx-bot-label--doctor">医师</div> <div class="rx-bot-label rx-bot-label--inline">医师</div>
<div class="rx-bot-doctor-body"> <div class="rx-bot-doctor-body">
<img <img
v-if="data?.doctor_signature" v-if="doctorSignature"
:src="data.doctor_signature" :src="doctorSignature"
alt="医师签名" :alt="doctorName"
class="rx-bot-sign-img" class="rx-bot-sign-img"
@error="onDoctorSignatureError"
/> />
<span v-if="!data?.doctor_signature" class="rx-bot-doctor-name"> <span v-else class="rx-bot-doctor-name">{{ doctorName }}</span>
{{ data?.doctor_name || '—' }}
</span>
</div> </div>
</div> </div>
<div v-if="reviewerName" class="rx-bot-cell rx-bot-reviewer">
<span class="rx-bot-label rx-bot-label--inline">药师审核</span>
<img
v-if="reviewerSignature"
:src="reviewerSignature"
:alt="reviewerName"
class="rx-bot-sign-img"
@error="onReviewerSignatureError"
/>
<span v-else class="rx-bot-reviewer-name">{{ reviewerName }}</span>
</div>
<div v-if="isInternal" class="rx-bot-cell rx-bot-meta"> <div v-if="isInternal" class="rx-bot-cell rx-bot-meta">
<span class="rx-bot-meta-key">类型:</span> <span class="rx-bot-meta-key">类型:</span>
<span class="rx-bot-meta-val">{{ typeText }}</span> <span class="rx-bot-meta-val">{{ typeText }}</span>
@@ -192,6 +205,7 @@
<script lang="ts" setup> <script lang="ts" setup>
import { computed, ref } from 'vue' import { computed, ref } from 'vue'
import type { PrescriptionEsignStatus } from '@/api/tcm'
import { import {
getAuxHerbs, getAuxHerbs,
getMainHerbs, getMainHerbs,
@@ -226,6 +240,7 @@ const props = withDefaults(
auxLibraryName?: string auxLibraryName?: string
/** 抬头(处方联) */ /** 抬头(处方联) */
title?: string title?: string
compact?: boolean
}>(), }>(),
{ {
variant: 'internal', variant: 'internal',
@@ -237,6 +252,45 @@ const props = withDefaults(
const paperRef = ref<HTMLElement | null>(null) const paperRef = ref<HTMLElement | null>(null)
const isInternal = computed(() => props.variant !== 'user') const isInternal = computed(() => props.variant !== 'user')
const slipTitle = computed(() => props.title || '成都双流甄养堂互联网医院 处方笺') const slipTitle = computed(() => props.title || '成都双流甄养堂互联网医院 处方笺')
const verifiedDoctor = computed(() => {
const signing: PrescriptionEsignStatus | undefined = props.data?.esign
if (signing?.status === 'signed' || (signing?.status === 'voided' && signing.can_download)) return signing
return null
})
const doctorName = computed(() => {
const signer = verifiedDoctor.value?.doctor_signer_name
return (typeof signer === 'string' && signer.trim()) || props.data?.doctor_name || '—'
})
const failedDoctorSignature = ref('')
const doctorSignature = computed(() => {
const signature = props.data?.doctor_signature
if (verifiedDoctor.value && !isVerifiedSignaturePng(signature)) return ''
if (!verifiedDoctor.value && props.data?.esign?.required) return ''
return typeof signature === 'string' && signature !== failedDoctorSignature.value ? signature : ''
})
const reviewerName = computed(() => {
const signing = props.data?.esign
if (!signing || !['signed', 'voided'].includes(signing.status)
|| !Number.isInteger(signing.review_signature_time) || signing.review_signature_time <= 0) return ''
return typeof signing.review_signer_name === 'string' ? signing.review_signer_name.trim() : ''
})
const failedReviewerSignature = ref('')
const reviewerSignature = computed(() => {
const signature = props.data?.esign?.review_signature
return reviewerName.value && isVerifiedSignaturePng(signature) && signature !== failedReviewerSignature.value ? signature : ''
})
function isVerifiedSignaturePng(signature: unknown): signature is string {
return typeof signature === 'string' && /^data:image\/png;base64,iVBORw0KGgo[A-Za-z0-9+/]+={0,2}$/.test(signature)
}
function onDoctorSignatureError(event: Event) {
if (event.currentTarget instanceof HTMLImageElement) failedDoctorSignature.value = event.currentTarget.getAttribute('src') ?? ''
}
function onReviewerSignatureError(event: Event) {
if (event.currentTarget instanceof HTMLImageElement) failedReviewerSignature.value = event.currentTarget.src
}
const dateText = computed(() => rxDateText(props.data)) const dateText = computed(() => rxDateText(props.data))
const prescriptionSnText = computed(() => rxPrescriptionSnText(props.data)) const prescriptionSnText = computed(() => rxPrescriptionSnText(props.data))
@@ -612,6 +666,14 @@ defineExpose({
grid-template-columns: 1.6fr 0.6fr; grid-template-columns: 1.6fr 0.6fr;
} }
.rx-bot-row-1--reviewed {
grid-template-columns: minmax(164px, 1.15fr) minmax(188px, 1.3fr) 1.4fr 0.75fr 0.85fr;
}
.rx-bot-row-1--user.rx-bot-row-1--reviewed {
grid-template-columns: minmax(164px, 1.6fr) minmax(188px, 1.6fr) 0.6fr;
}
.rx-hospital-row { .rx-hospital-row {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
@@ -662,7 +724,7 @@ defineExpose({
margin-bottom: 4px; margin-bottom: 4px;
} }
.rx-bot-label--doctor { .rx-bot-label--inline {
flex-shrink: 0; flex-shrink: 0;
margin-bottom: 0; margin-bottom: 0;
margin-right: 6px; margin-right: 6px;
@@ -670,6 +732,14 @@ defineExpose({
align-self: center; align-self: center;
} }
.rx-bot-reviewer-name {
min-width: 0;
font-size: 13px;
font-weight: 500;
line-height: 1.4;
overflow-wrap: anywhere;
}
.rx-bot-doctor { .rx-bot-doctor {
flex-direction: row; flex-direction: row;
align-items: center; align-items: center;
@@ -692,13 +762,13 @@ defineExpose({
line-height: 1.2; line-height: 1.2;
white-space: nowrap; white-space: nowrap;
} }
}
.rx-bot-sign-img { .rx-bot-sign-img {
flex-shrink: 0; flex-shrink: 0;
max-height: 40px; max-height: 24px;
max-width: 110px; max-width: 72px;
object-fit: contain; object-fit: contain;
}
} }
.rx-bot-meta { .rx-bot-meta {
@@ -721,6 +791,38 @@ defineExpose({
line-height: 2.5; line-height: 2.5;
} }
} }
.rx-paper.rx-paper--compact {
width: 100%;
min-height: 0;
padding: clamp(10px, 2.4vw, 24px);
container-type: inline-size;
.rx-title { font-size: 22px; margin: 6px 0 18px; }
.rx-notice { padding: 10px; }
.rx-notice .rx-notice-meta { flex-wrap: wrap; overflow: visible; gap: 2px 14px; }
.rx-notice .rx-notice-meta .rx-meta-item { border: 0; padding: 0; margin: 0; }
.rx-info-cell { padding: 9px; min-width: 0; overflow-wrap: anywhere; }
.rx-herb-name { white-space: normal; overflow-wrap: anywhere; }
.rx-herb-cell { line-height: 1.65; }
.rx-text { overflow-wrap: anywhere; }
.rx-bot-row-1 { display: flex; flex-wrap: wrap; min-height: 0; }
.rx-bot-row-1 > .rx-bot-cell { flex: 1 0 auto; max-width: 100%; border: 0; flex-wrap: wrap; }
.rx-bot-doctor .rx-bot-doctor-name { white-space: normal; overflow-wrap: anywhere; }
}
@container (max-width: 465px) {
.rx-paper--compact .rx-info-row:not(.rx-info-row-full) {
grid-template-columns: repeat(2, minmax(0, 1fr));
.rx-info-cell:nth-child(even) { border-right: none; }
.rx-info-cell:nth-child(n + 3) { border-top: 1px solid #c8c8c8; }
}
.rx-paper--compact .rx-rp-cols-head,
.rx-paper--compact .rx-herbs { grid-template-columns: minmax(0, 1fr); }
.rx-paper--compact .rx-rp-col-head + .rx-rp-col-head { display: none; }
}
</style> </style>
<!-- 全局打印样式:body * 选择器不能放进 scoped --> <!-- 全局打印样式:body * 选择器不能放进 scoped -->
@@ -514,7 +514,7 @@
{{ esignError }} <el-button link type="primary" @click="loadEsignConfig">重试</el-button> {{ esignError }} <el-button link type="primary" @click="loadEsignConfig">重试</el-button>
</el-alert> </el-alert>
<el-alert v-else-if="esignEnabled" type="info" :closable="false" class="mb-3" <el-alert v-else-if="esignEnabled" type="info" :closable="false" class="mb-3"
:title="esignConfig?.environment === 'sandbox' ? '沙箱测试。保存草稿后,由开方医生本人确认签署。' : '保存草稿后,由开方医生本人确认签署。'" /> :title="esignConfig?.environment === 'sandbox' ? '沙箱测试。保存草稿后,先上传处方,再由开方医生本人签署。' : '保存草稿后,先上传处方,再由开方医生本人签署。'" />
<el-form-item v-else-if="esignReady" label="医师签名" prop="doctor_signature" required> <el-form-item v-else-if="esignReady" label="医师签名" prop="doctor_signature" required>
<div class="signature-pad-wrap"> <div class="signature-pad-wrap">
<canvas <canvas
@@ -553,7 +553,7 @@
v-else-if="Number(savedPrescription.audit_status) === 0" v-else-if="Number(savedPrescription.audit_status) === 0"
type="warning" type="warning"
size="small" size="small"
>待审核</el-tag> >{{ pendingPrescriptionReviewLabel(savedPrescription) }}</el-tag>
<el-tag v-else-if="Number(savedPrescription.audit_status) === 2" type="danger" size="small">已驳回</el-tag> <el-tag v-else-if="Number(savedPrescription.audit_status) === 2" type="danger" size="small">已驳回</el-tag>
<div class="flex-1" /> <div class="flex-1" />
</div> </div>
@@ -877,7 +877,7 @@ import { getDictData } from '@/api/app'
import PrescriptionSlip from '@/components/prescription-slip/index.vue' import PrescriptionSlip from '@/components/prescription-slip/index.vue'
import EsignPrescriptionPanel from '@/components/EsignPrescriptionPanel.vue' import EsignPrescriptionPanel from '@/components/EsignPrescriptionPanel.vue'
import { usePrescriptionEsignConfig } from '@/hooks/usePrescriptionEsignConfig' import { usePrescriptionEsignConfig } from '@/hooks/usePrescriptionEsignConfig'
import { downloadPrescriptionPdfIfRequired, requiresOriginalEsignPdf } from '@/utils/prescription-esign' import { downloadPrescriptionPdfIfRequired, pendingPrescriptionReviewLabel, requiresOriginalEsignPdf } from '@/utils/prescription-esign'
import type { PrescriptionEsignStatus } from '@/api/tcm' import type { PrescriptionEsignStatus } from '@/api/tcm'
import html2canvas from 'html2canvas' import html2canvas from 'html2canvas'
import { jsPDF } from 'jspdf' import { jsPDF } from 'jspdf'
@@ -68,7 +68,9 @@ function closeEsign() {
reviewEsignOpen.value = false reviewEsignOpen.value = false
} }
watch([() => userStore.token, () => userInfo.value.id, canManageDoctorEsign, canManageReviewEsign], closeEsign, { flush: 'sync' }) watch([() => userStore.token, () => userInfo.value.id], closeEsign, { flush: 'sync' })
watch(canManageDoctorEsign, (allowed) => { if (!allowed) doctorEsignOpen.value = false }, { flush: 'sync' })
watch(canManageReviewEsign, (allowed) => { if (!allowed) reviewEsignOpen.value = false }, { flush: 'sync' })
onMounted(async () => { onMounted(async () => {
try { try {
const config = await prescriptionEsignConfig() const config = await prescriptionEsignConfig()
+37 -1
View File
@@ -1,4 +1,5 @@
import { import {
prescriptionDetail,
prescriptionEsignDownload, prescriptionEsignDownload,
prescriptionEsignStatus, prescriptionEsignStatus,
type PrescriptionEsignFile, type PrescriptionEsignFile,
@@ -55,7 +56,9 @@ export function validateEsignStatus(value: unknown): PrescriptionEsignStatus {
|| ['enabled', 'required', 'can_sign', 'can_download'].some((key) => typeof (state as any)[key] !== 'boolean') || ['enabled', 'required', 'can_sign', 'can_download'].some((key) => typeof (state as any)[key] !== 'boolean')
|| (state.verification_method !== undefined && !['quick', 'sms'].includes(state.verification_method)) || (state.verification_method !== undefined && !['quick', 'sms'].includes(state.verification_method))
|| [state.can_resume_identity, state.can_retry_verify, state.doctor_identity_required, || [state.can_resume_identity, state.can_retry_verify, state.doctor_identity_required,
state.signing_authorization_required, state.sms_sent].some((flag) => flag !== undefined && typeof flag !== 'boolean')) { state.signing_authorization_required, state.sms_sent, state.awaiting_upload,
state.can_submit_for_review, state.can_review_prescription]
.some((flag) => flag !== undefined && typeof flag !== 'boolean')) {
throw new Error('无法核对处方签署状态,请刷新后重试') throw new Error('无法核对处方签署状态,请刷新后重试')
} }
return state return state
@@ -104,6 +107,39 @@ export function canApprovePrescriptionEsign(status: unknown): boolean {
} }
} }
export function pendingPrescriptionReviewLabel(row: {
review_submitted_at?: number | string
can_review_prescription?: boolean
esign?: PrescriptionEsignStatus
}): string {
const submittedAt = row.esign?.review_submitted_at ?? row.review_submitted_at
if (!(Number(submittedAt) > 0)) return '待上传'
if ((row.esign?.can_review_prescription ?? row.can_review_prescription) === true) return '待审核'
return row.esign?.status === 'signed' ? '签署待核实' : '待医师签署'
}
export async function updatePrescriptionSlipEsign(data: Record<string, unknown> | null, state: PrescriptionEsignStatus): Promise<void> {
if (!data) return
const previous = data.esign as PrescriptionEsignStatus | undefined
data.esign = state
if (state.status !== 'signed' || previous?.status === 'signed') return
// The verified physician seal is stored on the prescription detail after signing.
data.doctor_signature = ''
const id = Number(data.id)
if (!Number.isInteger(id) || id <= 0) return
try {
const response = await prescriptionDetail({ id })
const detail = response?.data ?? response
if (Number(detail?.id) === id && (data.esign as PrescriptionEsignStatus).status === 'signed'
&& typeof detail?.doctor_signature === 'string') {
data.doctor_signature = detail.doctor_signature
}
} catch {
// The slip falls back to the verified name when the seal cannot be loaded.
}
}
/** Verify the received bytes before creating a download; never render or alter the signed PDF. */ /** Verify the received bytes before creating a download; never render or alter the signed PDF. */
export async function verifyEsignPdf(file: PrescriptionEsignFile): Promise<Uint8Array> { export async function verifyEsignPdf(file: PrescriptionEsignFile): Promise<Uint8Array> {
if (!/^[a-f\d]{64}$/i.test(file.sha256 || '')) throw new Error('签署文件缺少有效校验信息') if (!/^[a-f\d]{64}$/i.test(file.sha256 || '')) throw new Error('签署文件缺少有效校验信息')
@@ -402,7 +402,8 @@ const ReportList = defineComponent({
const models: Array<{ profile: PrescriptionAiProfile; label: string; name: string }> = [ const models: Array<{ profile: PrescriptionAiProfile; label: string; name: string }> = [
{ profile: 'qwen', label: '千问', name: 'qwen3.6-35b' }, { profile: 'qwen', label: '千问', name: 'qwen3.6-35b' },
{ profile: 'openai', label: 'OpenAI', name: 'gpt-5.6-sol' } { profile: 'openai', label: 'OpenAI', name: 'gpt-5.6-sol' },
{ profile: 'doubao', label: '豆包', name: 'doubao-seed-2.1-pro' }
] ]
const AI_REPORT_EDIT_PERMISSIONS = [ const AI_REPORT_EDIT_PERMISSIONS = [
@@ -436,7 +437,8 @@ const canRefreshFromBackend = ref(false)
const canEditFromBackend = ref(false) const canEditFromBackend = ref(false)
const states = reactive<Record<PrescriptionAiProfile, ReportState>>({ const states = reactive<Record<PrescriptionAiProfile, ReportState>>({
qwen: createState(), qwen: createState(),
openai: createState() openai: createState(),
doubao: createState()
}) })
const herbSummary = computed(() => { const herbSummary = computed(() => {
@@ -1440,6 +1440,8 @@ function canAddPrescriptionOrderLog() {
/** 与后端 canAuditPrescriptionOrder 同档:超管或 prescription_audit_roles */ /** 与后端 canAuditPrescriptionOrder 同档:超管或 prescription_audit_roles */
const canSetRxAuditOnAddLog = computed(() => { const canSetRxAuditOnAddLog = computed(() => {
if (Number(detailData.value?.prescription_audit_status) === 0
&& detailData.value?.can_review_prescription === false) return false
const u = userStore.userInfo const u = userStore.userInfo
if (!u || Number(u.root) === 1) return true if (!u || Number(u.root) === 1) return true
const ids = Array.isArray(u.role_ids) ? u.role_ids.map((n: unknown) => Number(n)) : [] const ids = Array.isArray(u.role_ids) ? u.role_ids.map((n: unknown) => Number(n)) : []
@@ -0,0 +1,60 @@
import type { PrescriptionEsignStatus } from '@/api/tcm'
const doctorSigningStatus = {
pending: { label: '待医师签署', type: 'warning' },
authenticating: { label: '待医师确认签署', type: 'warning' },
signing: { label: '医师签署中', type: 'primary' },
failed: { label: '医师签署未完成', type: 'danger' },
uncertain: { label: '医师签署待核实', type: 'warning' }
} as const
const pharmacistSigningStatus = {
pending: { label: '待药师签署', type: 'warning' },
signing: { label: '药师签署中', type: 'primary' },
verifying: { label: '药师验签中', type: 'primary' },
failed: { label: '药师签署未完成', type: 'danger' },
uncertain: { label: '药师签署待核实', type: 'warning' },
signed: { label: '已完成双签', type: 'success' }
} as const
const unknownSigningStatus = { label: '签署状态待核实', type: 'warning' } as const
export function prescriptionListSigningStatus(row: {
void_status?: number | string
esign?: PrescriptionEsignStatus | null
}) {
const { esign } = row
if (Number(row.void_status) === 1 || esign?.status === 'voided') {
return { label: '已作废', type: 'danger' } as const
}
if (esign?.required && esign.awaiting_upload === true && esign.status !== 'signed') {
return { label: '上传后签署', type: 'info' } as const
}
switch (esign?.status) {
case 'pending':
case 'authenticating':
case 'signing':
case 'failed':
case 'uncertain':
return doctorSigningStatus[esign.status]
case 'legacy':
return { label: '历史处方', type: 'info' } as const
case 'signed': {
if (esign.can_download !== true) return doctorSigningStatus.uncertain
if (esign.awaiting_upload === true) return { label: '医师已签署', type: 'success' } as const
if (esign.review_state !== undefined) {
return pharmacistSigningStatus[esign.review_state] ?? unknownSigningStatus
}
const pharmacistSignedAt = esign.review_signature_time ?? 0
if (Number.isInteger(pharmacistSignedAt) && pharmacistSignedAt > 0) {
return pharmacistSigningStatus.signed
}
return esign.review_required === true
? pharmacistSigningStatus.pending
: { label: '医师已签署', type: 'success' } as const
}
default:
return unknownSigningStatus
}
}
+452 -105
View File
@@ -24,7 +24,7 @@
<span class="pl-toolbar__sep" aria-hidden="true" /> <span class="pl-toolbar__sep" aria-hidden="true" />
<span <span
class="pl-toolbar__k" class="pl-toolbar__k"
title="「未通过」含待审核与已驳回" title="「未通过」含待上传、待医师签署、待审核与已驳回"
>审核</span> >审核</span>
<el-radio-group <el-radio-group
v-model="formData.audit_filter" v-model="formData.audit_filter"
@@ -103,6 +103,9 @@
<div class="pl-table-head"> <div class="pl-table-head">
<span class="pl-table-head__title">处方列表</span> <span class="pl-table-head__title">处方列表</span>
<div class="flex items-center gap-2"> <div class="flex items-center gap-2">
<el-button v-if="canManageCaSigning" @click="openCaSigningSettings">
CA 签名设置
</el-button>
<el-button <el-button
v-perms="['tcm.prescriptionOrder/lists']" v-perms="['tcm.prescriptionOrder/lists']"
@click="goBusinessOrderList" @click="goBusinessOrderList"
@@ -169,9 +172,6 @@
<el-tag :type="listAuditStatusTagType(row)"> <el-tag :type="listAuditStatusTagType(row)">
{{ listAuditStatusLabel(row) }} {{ listAuditStatusLabel(row) }}
</el-tag> </el-tag>
<el-tag v-if="pendingEsignAudit(row)" type="warning" size="small" effect="plain">
{{ row.esign.status_label }}
</el-tag>
<span <span
v-if="Number(row.business_prescription_audit_rejected) === 1" v-if="Number(row.business_prescription_audit_rejected) === 1"
class="text-xs text-gray-500" class="text-xs text-gray-500"
@@ -192,6 +192,13 @@
</div> </div>
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="签署状态" min-width="140">
<template #default="{ row }">
<el-tag :type="prescriptionListSigningStatus(row).type" size="small" effect="plain">
{{ prescriptionListSigningStatus(row).label }}
</el-tag>
</template>
</el-table-column>
<el-table-column label="作废" min-width="80" align="center"> <el-table-column label="作废" min-width="80" align="center">
<template #default="{ row }"> <template #default="{ row }">
<el-tag v-if="row.void_status === 1" type="danger" size="small">作废</el-tag> <el-tag v-if="row.void_status === 1" type="danger" size="small">作废</el-tag>
@@ -214,7 +221,7 @@
{{ formatListCreateTime(row.create_time) }} {{ formatListCreateTime(row.create_time) }}
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="操作" width="300" fixed="right"> <el-table-column label="操作" width="340" fixed="right">
<template #default="{ row }"> <template #default="{ row }">
<el-button type="primary" link @click="handleView(row)" v-perms="['cf.prescription/read']"> <el-button type="primary" link @click="handleView(row)" v-perms="['cf.prescription/read']">
查看 查看
@@ -238,7 +245,7 @@
创建订单 创建订单
</el-button> </el-button>
<el-button <el-button
v-if="!isApprovedActivePrescription(row)" v-if="!isApprovedActivePrescription(row) && (Number(row.void_status) !== 1 || row.can_restore_rejected === true)"
type="primary" type="primary"
link link
@click="handleEdit(row)" @click="handleEdit(row)"
@@ -247,14 +254,44 @@
编辑 编辑
</el-button> </el-button>
<el-button <el-button
v-if="isPendingPrescriptionAudit(row)" v-if="canReissuePrescription(row)"
type="primary"
link
:loading="reissuingPrescriptionId === Number(row.id)"
:disabled="reissuingPrescriptionId !== 0"
@click="handleReissue(row)"
>
重新开方
</el-button>
<el-button
v-if="row.can_submit_for_review === true"
type="primary"
link
:loading="uploadingPrescriptionId === Number(row.id)"
:disabled="uploadingPrescriptionId !== 0"
@click="submitPrescriptionForReview(row)"
>
上传处方
</el-button>
<el-button
v-if="canOpenPrescriptionAudit(row)"
type="warning" type="warning"
link link
v-perms="['cf.prescription/audit']" v-perms="['cf.prescription/audit']"
@click="openAuditDialog(Number(row.id))" @click="openAuditDialog(row)"
> >
审核 审核
</el-button> </el-button>
<el-button
v-if="canVoidPendingPrescription(row)"
type="danger"
link
:loading="voidingPrescriptionId === Number(row.id)"
:disabled="voidingPrescriptionId !== 0"
@click="voidPendingPrescription(row)"
>
作废
</el-button>
<el-button <el-button
v-if="!isApprovedActivePrescription(row)" v-if="!isApprovedActivePrescription(row)"
type="danger" type="danger"
@@ -274,10 +311,68 @@
</div> </div>
</el-card> </el-card>
<el-dialog
v-if="canManageCaSigning"
v-model="caSigningSettingsVisible"
title="CA 签名设置"
width="min(440px, calc(100vw - 24px))"
:close-on-click-modal="false"
:close-on-press-escape="!caSigningSettingsSaving"
:show-close="!caSigningSettingsSaving"
>
<p v-if="esignLoading" role="status">正在读取 CA 签名设置…</p>
<template v-else-if="esignReady">
<div class="flex items-center justify-between gap-2">
<span>全局 CA 签名</span>
<el-switch
v-model="caSigningSettingsEnabled"
aria-label="全局 CA 签名"
active-text="开启"
inactive-text="关闭"
:disabled="caSigningSettingsSaving"
/>
</div>
<p v-if="esignConfig?.enabled && esignConfig.review_enabled !== true" class="mt-3">
当前仅启用医师 CA 签名。
</p>
<p class="mt-3 leading-relaxed">
保存为开启时,处方上传后依次由医师、药师完成 CA 签名。
保存为关闭时,新开的普通处方使用手写签名,上传后进入原有审核流程。
已进入 CA 流程的处方仍按该流程处理。
</p>
<el-alert
v-if="caSigningSettingsSaveError"
class="mt-3"
type="error"
:closable="false"
:title="caSigningSettingsSaveError"
/>
</template>
<el-alert v-else type="error" :closable="false" title="未能读取 CA 签名设置">
<el-button link type="primary" @click="loadCaSigningSettings">重新加载</el-button>
</el-alert>
<template #footer>
<el-button
:disabled="caSigningSettingsSaving"
@click="caSigningSettingsVisible = false"
>
取消
</el-button>
<el-button
type="primary"
:disabled="!canSaveCaSigningSettings"
:loading="caSigningSettingsSaving"
@click="saveCaSigningSettings"
>
保存
</el-button>
</template>
</el-dialog>
<!-- 新增/编辑/查看抽屉 --> <!-- 新增/编辑/查看抽屉 -->
<el-drawer <el-drawer
v-model="showEdit" v-model="showEdit"
:title="editMode === 'add' ? '新增处方' : editMode === 'edit' ? '编辑处方' : '查看处方'" :title="editMode === 'add' ? (reissueContext ? '重新开方' : '新增处方') : editMode === 'edit' ? '编辑处方' : '查看处方'"
:size="editMode === 'view' ? '920px' : '860px'" :size="editMode === 'view' ? '920px' : '860px'"
class="cf-prescription-drawer" class="cf-prescription-drawer"
:close-on-click-modal="false" :close-on-click-modal="false"
@@ -285,10 +380,15 @@
@close="showEdit = false" @close="showEdit = false"
@closed="onEditDialogClosed" @closed="onEditDialogClosed"
> >
<!-- 查看:A4 处方笺(药房联样式) --> <!-- 查看:A4 处方笺 -->
<div v-if="editMode === 'view'" v-loading="viewDetailLoading" class="rx-wrap"> <div v-if="editMode === 'view'" :aria-busy="viewDetailLoading" class="rx-wrap">
<p v-if="viewDetailLoading" class="rx-status" role="status">正在加载处方详情…</p>
<div v-if="viewDetailError" class="rx-status rx-status-danger" role="alert">
{{ viewDetailError }}
<el-button v-if="slipView?.id" link type="primary" @click="handleView(slipView)">重试加载</el-button>
</div>
<EsignPrescriptionPanel <EsignPrescriptionPanel
v-if="showEdit && slipView?.id && !viewDetailLoading" v-if="showEdit && slipView?.id && !viewDetailLoading && !viewDetailError"
:key="slipView.id" :key="slipView.id"
:prescription-id="Number(slipView.id)" :prescription-id="Number(slipView.id)"
:initial-state="slipView.esign" :initial-state="slipView.esign"
@@ -317,19 +417,27 @@
v-else-if="slipView && Number(slipView.audit_status) === 0" v-else-if="slipView && Number(slipView.audit_status) === 0"
type="warning" type="warning"
size="small" size="small"
>待审核</el-tag> >{{ listAuditStatusLabel(slipView) }}</el-tag>
<el-tag v-else-if="slipView" type="danger" size="small">已驳回</el-tag> <el-tag v-else-if="slipView" type="danger" size="small">已驳回</el-tag>
<el-tag v-if="slipView && pendingEsignAudit(slipView)" type="warning" size="small" effect="plain"> <el-tag v-if="slipView && pendingEsignAudit(slipView)" type="warning" size="small" effect="plain">
{{ slipView.esign.status_label }} {{ slipView.esign.status_label }}
</el-tag> </el-tag>
<div class="flex-1" /> <div class="flex-1" />
<el-button <el-button
v-if="slipView && !viewDetailLoading && isPendingPrescriptionAudit(slipView)" v-if="slipView && !viewDetailLoading && canOpenPrescriptionAudit(slipView)"
v-perms="['cf.prescription/audit']" v-perms="['cf.prescription/audit']"
type="warning" type="warning"
size="small" size="small"
@click="openAuditDialog(Number(slipView.id))" @click="openAuditDialog(slipView)"
>审核</el-button> >审核</el-button>
<el-button
v-if="slipView && !viewDetailLoading && !viewDetailError && canReissuePrescription(slipView)"
type="primary"
size="small"
:loading="reissuingPrescriptionId === Number(slipView.id)"
:disabled="reissuingPrescriptionId !== 0"
@click="handleReissue(slipView)"
>重新开方</el-button>
<el-button v-if="!requiresOriginalEsignPdf(slipView?.esign)" :icon="Printer" size="small" @click="handlePrintSlip">打印</el-button> <el-button v-if="!requiresOriginalEsignPdf(slipView?.esign)" :icon="Printer" size="small" @click="handlePrintSlip">打印</el-button>
<el-button <el-button
type="primary" type="primary"
@@ -364,8 +472,19 @@
<div v-if="slipView.audit_remark" class="mt-1">驳回意见:{{ slipView.audit_remark }}</div> <div v-if="slipView.audit_remark" class="mt-1">驳回意见:{{ slipView.audit_remark }}</div>
</div> </div>
<!-- A4 处方纸:统一组件,与全端药房联一比一 --> <el-tabs
<PrescriptionSlip v-if="slipView" ref="rxSlipRef" :data="slipView" /> v-if="slipView"
v-model="prescriptionTabType"
class="rx-slip-tabs"
:before-leave="() => !downloadingSlip"
>
<el-tab-pane label="药房联" name="internal">
<PrescriptionSlip v-if="prescriptionTabType === 'internal'" ref="rxSlipRef" :data="slipView" />
</el-tab-pane>
<el-tab-pane label="处方联" name="user">
<PrescriptionSlip v-if="prescriptionTabType === 'user'" ref="rxSlipRef" :data="slipView" variant="user" />
</el-tab-pane>
</el-tabs>
<!-- 审核痕迹(不进入打印区) --> <!-- 审核痕迹(不进入打印区) -->
<div <div
@@ -403,7 +522,7 @@
:closable="false" :closable="false"
show-icon show-icon
class="mb-4" class="mb-4"
title="保存修改后,该处方将重新进入「待审核」,需审核人员再次通过后方可生效。" title="保存修改后,请由开方医生重新上传并完成签署,再交药师审核。"
/> />
<el-alert <el-alert
v-if="editMode === 'edit' && Number(editForm.audit_status) === 2" v-if="editMode === 'edit' && Number(editForm.audit_status) === 2"
@@ -414,7 +533,7 @@
> >
<template #title>当前消费者处方为「已驳回」</template> <template #title>当前消费者处方为「已驳回」</template>
<div class="text-sm mt-1"> <div class="text-sm mt-1">
保存修改后将清除驳回并变为「待审核」。{{ 保存修改后将清除驳回并恢复为「待上传」。{{
editForm.audit_remark ? `上次意见:${editForm.audit_remark}` : '' editForm.audit_remark ? `上次意见:${editForm.audit_remark}` : ''
}} }}
</div> </div>
@@ -464,7 +583,7 @@
<el-input <el-input
v-model="editForm.patient_name" v-model="editForm.patient_name"
placeholder="请输入患者姓名" placeholder="请输入患者姓名"
:disabled="editMode === 'edit'" :disabled="editMode === 'edit' || (!!reissueContext && editForm.diagnosis_id > 0)"
/> />
</el-form-item> </el-form-item>
</el-col> </el-col>
@@ -1010,7 +1129,7 @@
{{ esignError }} <el-button link type="primary" @click="loadEsignConfig">重试</el-button> {{ esignError }} <el-button link type="primary" @click="loadEsignConfig">重试</el-button>
</el-alert> </el-alert>
<el-alert v-else-if="esignEnabled" type="info" :closable="false" class="mb-3" <el-alert v-else-if="esignEnabled" type="info" :closable="false" class="mb-3"
:title="esignConfig?.environment === 'sandbox' ? '沙箱测试。保存草稿后,由开方医生本人确认签署。' : '保存草稿后,由开方医生本人确认签署。'" /> :title="esignConfig?.environment === 'sandbox' ? '沙箱测试。保存草稿后,先上传处方,再由开方医生本人签署。' : '保存草稿后,先上传处方,再由开方医生本人签署。'" />
<el-form-item v-else-if="esignReady" label="医师签名" prop="doctor_signature" required> <el-form-item v-else-if="esignReady" label="医师签名" prop="doctor_signature" required>
<div class="signature-pad-wrap"> <div class="signature-pad-wrap">
<canvas <canvas
@@ -1557,31 +1676,35 @@
</template> </template>
</el-dialog> </el-dialog>
<el-dialog v-model="auditDialogVisible" title="处方审核" width="480px" destroy-on-close @closed="auditRemark = ''"> <el-dialog v-model="auditDialogVisible" title="处方审核" width="min(1280px, 96vw)" top="5vh" append-to-body destroy-on-close @closed="auditRemark = ''">
<EsignPrescriptionPanel <PrescriptionAuditLayout
v-if="auditDialogVisible"
:key="auditTargetId"
:prescription-id="auditTargetId" :prescription-id="auditTargetId"
audit :doctor-signed-at="auditEsign?.signature_time || auditEsign?.signed_at"
@review-change="auditReview = $event" :pharmacist-signed-at="auditReview?.signature_time || auditEsign?.review_signature_time"
class="mb-3" >
@status-change="onAuditEsignStatusChange" <EsignPrescriptionPanel
/> v-if="auditDialogVisible"
<p class="text-sm text-gray-600 mb-3"> :key="auditTargetId"
通过:处方保持有效。驳回:将同时作废此处方(与诊间「驳回/作废处方」一致)。 :prescription-id="auditTargetId"
</p> audit
<el-form label-width="80px"> @review-change="onAuditReviewChange"
<el-form-item label="审核意见"> class="mb-3"
<el-input @status-change="onAuditEsignStatusChange"
v-model="auditRemark" />
type="textarea" <p class="text-sm text-gray-600 mb-3">驳回将同时作废处方。通过时审核意见选填。</p>
:rows="3" <el-form label-position="top">
maxlength="500" <el-form-item label="审核意见">
show-word-limit <el-input
placeholder="通过可简要说明;驳回必填" v-model="auditRemark"
/> type="textarea"
</el-form-item> :rows="3"
</el-form> maxlength="500"
show-word-limit
placeholder="驳回时必填"
/>
</el-form-item>
</el-form>
</PrescriptionAuditLayout>
<template #footer> <template #footer>
<el-button @click="auditDialogVisible = false">取消</el-button> <el-button @click="auditDialogVisible = false">取消</el-button>
<el-button type="primary" :loading="auditLoading" :disabled="!canApproveAudit" @click="submitAudit('approve')">审核通过</el-button> <el-button type="primary" :loading="auditLoading" :disabled="!canApproveAudit" @click="submitAudit('approve')">审核通过</el-button>
@@ -1601,7 +1724,10 @@ import {
prescriptionEdit, prescriptionEdit,
prescriptionPatchPatient, prescriptionPatchPatient,
prescriptionDelete, prescriptionDelete,
prescriptionVoid,
prescriptionAudit, prescriptionAudit,
prescriptionEsignSetConfig,
prescriptionSubmitForReview,
prescriptionDetail, prescriptionDetail,
prescriptionOrderCreate, prescriptionOrderCreate,
prescriptionOrderPaidPayOrders, prescriptionOrderPaidPayOrders,
@@ -1620,10 +1746,12 @@ import type { FormInstance, FormRules } from 'element-plus'
import DaterangePicker from '@/components/daterange-picker/index.vue' import DaterangePicker from '@/components/daterange-picker/index.vue'
import MedicineNameSelect from '@/components/medicine-name-select/index.vue' import MedicineNameSelect from '@/components/medicine-name-select/index.vue'
import PrescriptionSlip from '@/components/prescription-slip/index.vue' import PrescriptionSlip from '@/components/prescription-slip/index.vue'
import PrescriptionAuditLayout from '@/components/PrescriptionAuditLayout.vue'
import EsignPrescriptionPanel from '@/components/EsignPrescriptionPanel.vue' import EsignPrescriptionPanel from '@/components/EsignPrescriptionPanel.vue'
import { usePrescriptionEsignConfig } from '@/hooks/usePrescriptionEsignConfig' import { usePrescriptionEsignConfig } from '@/hooks/usePrescriptionEsignConfig'
import { canApprovePrescriptionEsign, downloadPrescriptionPdfIfRequired, requiresOriginalEsignPdf } from '@/utils/prescription-esign' import { canApprovePrescriptionEsign, downloadPrescriptionPdfIfRequired, pendingPrescriptionReviewLabel, requiresOriginalEsignPdf, updatePrescriptionSlipEsign } from '@/utils/prescription-esign'
import type { PrescriptionEsignStatus } from '@/api/tcm' import type { PrescriptionEsignStatus } from '@/api/tcm'
import { prescriptionListSigningStatus } from './components/prescription-list-signing-status'
import { Search, Download, Printer, EditPen } from '@element-plus/icons-vue' import { Search, Download, Printer, EditPen } from '@element-plus/icons-vue'
import { computed, onMounted, onActivated, onDeactivated, reactive, ref, watch, nextTick, defineAsyncComponent } from 'vue' import { computed, onMounted, onActivated, onDeactivated, reactive, ref, watch, nextTick, defineAsyncComponent } from 'vue'
import { useRoute, useRouter } from 'vue-router' import { useRoute, useRouter } from 'vue-router'
@@ -1811,15 +1939,72 @@ const SIGNATURE_CSS_H = 168
const slipView = ref<Record<string, any> | null>(null) const slipView = ref<Record<string, any> | null>(null)
const { config: esignConfig, enabled: esignEnabled, ready: esignReady, loading: esignLoading, error: esignError, load: loadEsignConfig } = usePrescriptionEsignConfig() const { config: esignConfig, enabled: esignEnabled, ready: esignReady, loading: esignLoading, error: esignError, load: loadEsignConfig } = usePrescriptionEsignConfig()
const canManageCaSigning = computed(() => Number(userStore.userInfo?.root) === 1)
const caSigningSettingsVisible = ref(false)
const caSigningSettingsEnabled = ref(false)
const caSigningSettingsSaving = ref(false)
const caSigningSettingsSaveError = ref('')
const canSaveCaSigningSettings = computed(
() => canManageCaSigning.value && esignReady.value && !esignLoading.value && !caSigningSettingsSaving.value
)
async function loadCaSigningSettings() {
if (!canManageCaSigning.value || caSigningSettingsSaving.value) return
caSigningSettingsSaveError.value = ''
if (await loadEsignConfig()) {
caSigningSettingsEnabled.value = esignConfig.value?.enabled === true
}
}
function openCaSigningSettings() {
if (!canManageCaSigning.value) return
caSigningSettingsVisible.value = true
void loadCaSigningSettings()
}
async function saveCaSigningSettings() {
if (!canSaveCaSigningSettings.value) return
caSigningSettingsSaving.value = true
caSigningSettingsSaveError.value = ''
try {
const enabled = caSigningSettingsEnabled.value
const config = await prescriptionEsignSetConfig({ enabled })
if (config?.enabled !== enabled) throw new Error('保存结果与所选设置不一致')
esignConfig.value = config
caSigningSettingsVisible.value = false
feedback.msgSuccess('CA 签名设置已保存')
void getLists({ silent: true }).catch(() => {})
} catch {
caSigningSettingsSaveError.value = '保存未完成,当前选择已保留,请重试。'
} finally {
caSigningSettingsSaving.value = false
}
}
const onEsignStatusChange = (state: PrescriptionEsignStatus) => { const onEsignStatusChange = (state: PrescriptionEsignStatus) => {
if (slipView.value) slipView.value.esign = state const previous = slipView.value?.esign
void getLists() if (slipView.value && state.review_submitted_at !== undefined) {
slipView.value.review_submitted_at = state.review_submitted_at
slipView.value.can_submit_for_review = state.can_submit_for_review === true
slipView.value.can_review_prescription = state.can_review_prescription === true
}
void updatePrescriptionSlipEsign(slipView.value, state)
if (previous?.status !== state.status || previous?.review_signature_time !== state.review_signature_time
|| previous?.review_submitted_at !== state.review_submitted_at
|| previous?.can_review_prescription !== state.can_review_prescription) {
void getLists({ silent: true }).catch(() => {})
}
} }
const viewDetailLoading = ref(false) const viewDetailLoading = ref(false)
const viewDetailError = ref('')
let viewDetailRequest: AbortController | undefined
const roleOptions = ref<Array<{ id: number; name: string }>>([]) const roleOptions = ref<Array<{ id: number; name: string }>>([])
const auditDialogVisible = ref(false) const auditDialogVisible = ref(false)
const uploadingPrescriptionId = ref(0)
const voidingPrescriptionId = ref(0)
const reissuingPrescriptionId = ref(0)
const auditTargetId = ref(0) const auditTargetId = ref(0)
const auditRemark = ref('') const auditRemark = ref('')
const auditLoading = ref(false) const auditLoading = ref(false)
@@ -2415,9 +2600,9 @@ const editReviveHint = computed(() => {
const v = editingWasVoid.value const v = editingWasVoid.value
const r = editingWasRejected.value const r = editingWasRejected.value
if (!v && !r) return '' if (!v && !r) return ''
if (v && r) return '当前处方已作废且已驳回。保存后将取消作废、清除驳回,并重新进入待审核。' if (v && r) return '当前处方已作废且已驳回。保存后将取消作废、清除驳回,请重新上传处方。'
if (v) return '当前为已作废处方。保存后将取消作废,并重新进入待审核。' if (v) return '当前为已作废处方。保存后将取消作废,请重新上传处方。'
return '当前为已驳回处方。保存后将清除驳回,并重新进入待审核。' return '当前为已驳回处方。保存后将清除驳回,请重新上传处方。'
}) })
const slipHerbsList = computed(() => { const slipHerbsList = computed(() => {
@@ -2460,6 +2645,7 @@ const slipDietaryText = computed(() => {
* A4 处方笺(药房联)相关计算 * A4 处方笺(药房联)相关计算
* ============================================================ */ * ============================================================ */
const rxSlipRef = ref<InstanceType<typeof PrescriptionSlip> | null>(null) const rxSlipRef = ref<InstanceType<typeof PrescriptionSlip> | null>(null)
const prescriptionTabType = ref<'internal' | 'user'>('internal')
const downloadingSlip = ref(false) const downloadingSlip = ref(false)
function getRxPaperEl(): HTMLElement | null { function getRxPaperEl(): HTMLElement | null {
@@ -2828,6 +3014,14 @@ const editForm = reactive({
aux_usage: defaultAuxUsage('浓缩水丸') aux_usage: defaultAuxUsage('浓缩水丸')
}) })
const reissueContext = ref<{
appointment_id: number
patient_id: number
phone: string
prescription_name: string
case_record?: unknown
} | null>(null)
/** 编辑页:关联业务订单上的服用天数、医助备注(与处方提示一致) */ /** 编辑页:关联业务订单上的服用天数、医助备注(与处方提示一致) */
const rxLinkedOrderHint = reactive({ const rxLinkedOrderHint = reactive({
loading: false, loading: false,
@@ -2970,7 +3164,8 @@ async function fetchPrescriptionLists(params: Record<string, unknown>) {
const { pager, getLists, resetPage } = usePaging({ const { pager, getLists, resetPage } = usePaging({
fetchFun: fetchPrescriptionLists, fetchFun: fetchPrescriptionLists,
params: formData params: formData,
latestOnly: true
}) })
function pad2(n: number) { function pad2(n: number) {
@@ -3090,8 +3285,16 @@ function auditStatusTagType(v: number | undefined) {
} }
/** 业务订单处方审核驳回时,列表「审核状态」主标签显示为已驳回 */ /** 业务订单处方审核驳回时,列表「审核状态」主标签显示为已驳回 */
function listAuditStatusLabel(row: { audit_status?: number; business_prescription_audit_rejected?: number }) { function listAuditStatusLabel(row: {
audit_status?: number
void_status?: number
review_submitted_at?: number
can_review_prescription?: boolean
esign?: PrescriptionEsignStatus
business_prescription_audit_rejected?: number
}) {
if (Number(row.business_prescription_audit_rejected) === 1) return '已驳回' if (Number(row.business_prescription_audit_rejected) === 1) return '已驳回'
if (isPendingPrescriptionAudit(row)) return pendingPrescriptionReviewLabel(row)
return auditStatusLabel(row.audit_status) return auditStatusLabel(row.audit_status)
} }
@@ -3127,8 +3330,44 @@ function isPendingPrescriptionAudit(row: { audit_status?: number | string; void_
return (row.audit_status === 0 || row.audit_status === '0') && Number(row.void_status) !== 1 return (row.audit_status === 0 || row.audit_status === '0') && Number(row.void_status) !== 1
} }
type VoidablePrescriptionRow = Parameters<typeof isPendingPrescriptionAudit>[0] & {
id?: number | string
can_void?: boolean
can_submit_for_review?: boolean
can_review_prescription?: boolean
}
function canVoidPendingPrescription(row: VoidablePrescriptionRow) {
return isPendingPrescriptionAudit(row) && row.can_void === true
}
async function voidPendingPrescription(row: VoidablePrescriptionRow) {
const id = Number(row.id)
if (!Number.isSafeInteger(id) || id <= 0 || voidingPrescriptionId.value || !canVoidPendingPrescription(row)) return
voidingPrescriptionId.value = id
try {
await feedback.confirm('确定作废这张处方吗?作废后可重新开方。')
await prescriptionVoid({ id, pending_only: true })
row.void_status = 1
row.can_void = false
row.can_submit_for_review = false
row.can_review_prescription = false
feedback.msgSuccess('处方已作废')
await getLists({ silent: true })
} catch {
// The request interceptor reports failures. Canceling leaves the row untouched.
} finally {
voidingPrescriptionId.value = 0
}
}
function canOpenPrescriptionAudit(row: { audit_status?: number | string; void_status?: number | string; can_review_prescription?: boolean }) {
return isPendingPrescriptionAudit(row) && row.can_review_prescription === true
}
function pendingEsignAudit(row: { audit_status?: number | string; void_status?: number | string; esign?: PrescriptionEsignStatus }) { function pendingEsignAudit(row: { audit_status?: number | string; void_status?: number | string; esign?: PrescriptionEsignStatus }) {
return isPendingPrescriptionAudit(row) && row.esign?.required === true && !canApprovePrescriptionEsign(row.esign) return isPendingPrescriptionAudit(row) && row.esign?.required === true && row.esign.awaiting_upload !== true
&& !canApprovePrescriptionEsign(row.esign)
} }
function formatAuditTime(ts: number | null | undefined) { function formatAuditTime(ts: number | null | undefined) {
@@ -3199,6 +3438,10 @@ function rowToSlipView(row: any) {
} }
function onEditDialogClosed() { function onEditDialogClosed() {
viewDetailRequest?.abort()
viewDetailRequest = undefined
viewDetailLoading.value = false
viewDetailError.value = ''
slipView.value = null slipView.value = null
signatureActivePointerId.value = null signatureActivePointerId.value = null
} }
@@ -3305,6 +3548,7 @@ function scheduleEditSignatureInit() {
if (sig && String(sig).trim().startsWith('data:image') && signatureCanvasRef.value) { if (sig && String(sig).trim().startsWith('data:image') && signatureCanvasRef.value) {
const img = new Image() const img = new Image()
img.onload = () => { img.onload = () => {
if (editForm.doctor_signature !== sig) return
const canvas = signatureCanvasRef.value const canvas = signatureCanvasRef.value
const ctx = canvas?.getContext('2d') const ctx = canvas?.getContext('2d')
if (!canvas || !ctx) return if (!canvas || !ctx) return
@@ -3312,7 +3556,7 @@ function scheduleEditSignatureInit() {
commitSignatureImage() commitSignatureImage()
} }
img.onerror = () => { img.onerror = () => {
commitSignatureImage() if (editForm.doctor_signature === sig) commitSignatureImage()
} }
img.src = sig img.src = sig
} }
@@ -3339,9 +3583,38 @@ function normalizeVisibleRoleIds(row: any): number[] {
return [] return []
} }
function openAuditDialog(id: number) { async function submitPrescriptionForReview(row: Record<string, any>) {
if (auditLoading.value) return if (uploadingPrescriptionId.value || row.can_submit_for_review !== true) return
auditTargetId.value = id const id = Number(row.id)
if (!Number.isSafeInteger(id) || id <= 0) return
uploadingPrescriptionId.value = id
try {
const result = await prescriptionSubmitForReview({ id })
const submittedAt = Number(result?.review_submitted_at)
if (!Number.isSafeInteger(submittedAt) || submittedAt <= 0) {
feedback.msgError('无法确认上传结果,请刷新处方状态后重试')
return
}
for (const target of [row, pager.lists.find((item: any) => Number(item.id) === id), slipView.value]) {
if (!target || Number(target.id) !== id) continue
target.review_submitted_at = submittedAt
target.can_submit_for_review = false
if (target.esign) target.esign = { ...target.esign, ...result, awaiting_upload: false }
}
const needsDoctorSignature = row.esign?.required === true && row.esign.status !== 'signed'
feedback.msgSuccess(needsDoctorSignature ? '处方已上传,请完成医师签署' : '处方已上传')
if (needsDoctorSignature) await handleView(row)
await getLists({ silent: true })
} catch {
// 请求失败时由拦截器显示提示,可重新上传。
} finally {
uploadingPrescriptionId.value = 0
}
}
function openAuditDialog(row: Record<string, any>) {
if (auditLoading.value || !canOpenPrescriptionAudit(row)) return
auditTargetId.value = Number(row.id)
auditEsign.value = null auditEsign.value = null
auditReview.value = null auditReview.value = null
auditRemark.value = '' auditRemark.value = ''
@@ -3358,6 +3631,16 @@ function onAuditEsignStatusChange(state: PrescriptionEsignStatus) {
} }
} }
function onAuditReviewChange(state: import('@/api/tcm').PrescriptionEsignReviewStatus | null) {
auditReview.value = state
if (!state?.required) return
const row = pager.lists.find((row: any) => Number(row.id) === auditTargetId.value)
if (row?.esign && state.state !== row.esign.review_state) {
row.esign.review_state = state.state
void getLists()
}
}
async function submitAudit(action: 'approve' | 'reject') { async function submitAudit(action: 'approve' | 'reject') {
if (auditLoading.value || (action === 'approve' && !canApproveAudit.value)) return if (auditLoading.value || (action === 'approve' && !canApproveAudit.value)) return
if (action === 'reject' && !auditRemark.value.trim()) { if (action === 'reject' && !auditRemark.value.trim()) {
@@ -3723,6 +4006,7 @@ const removeHerb = (index: number) => {
// 重置表单 // 重置表单
const resetForm = () => { const resetForm = () => {
reissueContext.value = null
editForm.id = 0 editForm.id = 0
editForm.prescription_type = '浓缩水丸' editForm.prescription_type = '浓缩水丸'
editForm.dosage_amount = 1 editForm.dosage_amount = 1
@@ -3734,7 +4018,7 @@ const resetForm = () => {
editForm.gender = 1 editForm.gender = 1
editForm.age = 0 editForm.age = 0
editForm.visit_no = '' editForm.visit_no = ''
editForm.prescription_date = new Date().toISOString().split('T')[0] editForm.prescription_date = dayRangeStrings(new Date()).start.slice(0, 10)
editForm.tongue = '' editForm.tongue = ''
editForm.tongue_image = '' editForm.tongue_image = ''
editForm.pulse = '' editForm.pulse = ''
@@ -3768,42 +4052,89 @@ const resetForm = () => {
} }
// 新增处方 // 新增处方
const handleAdd = () => { const handleAdd = () => openNewPrescription()
function openNewPrescription(source?: Record<string, any>) {
void loadEsignConfig() void loadEsignConfig()
isLoadingData.value = !!source
resetForm() resetForm()
if (source) {
fillPrescriptionContents(source)
editForm.diagnosis_id = Number(source.diagnosis_id) || 0
editForm.visit_no = source.visit_no === source.sn ? '' : String(source.visit_no || '')
reissueContext.value = {
appointment_id: Number(source.appointment_id) || 0,
patient_id: Number(source.patient_id) || 0,
phone: String(source.phone || ''),
prescription_name: String(source.prescription_name || ''),
case_record: editForm.diagnosis_id > 0 ? undefined : source.case_record
}
}
editForm.doctor_name = String(userStore.userInfo?.name || '') editForm.doctor_name = String(userStore.userInfo?.name || '')
editingWasVoid.value = false editingWasVoid.value = false
editingWasRejected.value = false editingWasRejected.value = false
editMode.value = 'add' editMode.value = 'add'
// 新建时允许watch自动设置默认值
isLoadingData.value = false
showEdit.value = true showEdit.value = true
nextTick(() => { nextTick(() => {
isLoadingData.value = false
formRef.value?.clearValidate() formRef.value?.clearValidate()
scheduleEditSignatureInit() scheduleEditSignatureInit()
}) })
} }
function canReissuePrescription(row: { creator_id?: number | string; void_status?: number | string }) {
const doctorId = Number(userStore.userInfo?.id)
return Number(row.void_status) === 1 && doctorId > 0 && Number(row.creator_id) === doctorId
&& hasPermission(['cf.prescription/add'])
}
async function handleReissue(row: { id?: number | string; creator_id?: number | string; void_status?: number | string }) {
const id = Number(row.id)
if (!Number.isSafeInteger(id) || id <= 0 || reissuingPrescriptionId.value || !canReissuePrescription(row)) return
const fromDetail = showEdit.value
reissuingPrescriptionId.value = id
try {
const detail = await prescriptionDetail({ id })
if (fromDetail ? !showEdit.value || editMode.value !== 'view' || Number(slipView.value?.id) !== id : showEdit.value) return
if (Number(detail?.id) !== id || !canReissuePrescription(detail)) {
feedback.msgWarning('这张处方当前无法重新开方,请刷新后查看')
return
}
openNewPrescription(detail)
} catch {
feedback.msgError('无法加载作废处方,请重试')
} finally {
reissuingPrescriptionId.value = 0
}
}
// 查看处方(处方笺样式,详情接口补全电话、签名等) // 查看处方(处方笺样式,详情接口补全电话、签名等)
const handleView = async (row: any) => { const handleView = async (row: any) => {
const id = Number(row.id)
if (!Number.isSafeInteger(id) || id <= 0) return
viewDetailRequest?.abort()
const request = new AbortController()
viewDetailRequest = request
editingWasVoid.value = false editingWasVoid.value = false
editingWasRejected.value = false editingWasRejected.value = false
editMode.value = 'view' editMode.value = 'view'
prescriptionTabType.value = 'internal'
slipView.value = rowToSlipView(row) slipView.value = rowToSlipView(row)
showEdit.value = true showEdit.value = true
viewDetailLoading.value = true viewDetailLoading.value = true
viewDetailError.value = ''
try { try {
const d = await prescriptionDetail({ id: row.id }) const d = await prescriptionDetail({ id }, request.signal)
if (d && typeof d === 'object') { if (request.signal.aborted) return
slipView.value = { if (Number(d?.id) !== id) throw new Error('处方详情与当前处方不一致')
...d, slipView.value = rowToSlipView(d)
herbs: normalizeSlipHerbs((d as any).herbs) } catch {
} if (!request.signal.aborted) viewDetailError.value = '无法加载处方详情,请重试。'
}
} catch (e: any) {
feedback.msgError(e?.msg || '加载处方详情失败')
} finally { } finally {
viewDetailLoading.value = false if (viewDetailRequest === request) {
viewDetailRequest = undefined
viewDetailLoading.value = false
}
} }
} }
@@ -3829,8 +4160,34 @@ const handleEdit = async (row: any) => {
} }
} }
// 深拷贝数据到表单
editForm.id = src.id editForm.id = src.id
fillPrescriptionContents(src)
editForm.visit_no = src.visit_no || ''
editForm.prescription_date = src.prescription_date || ''
editForm.doctor_name = src.doctor_name || ''
editForm.doctor_signature = String(src.doctor_signature || '')
editForm.is_shared = src.is_shared ?? 0
editForm.visible_role_ids = normalizeVisibleRoleIds(src)
editForm.audit_status = src.audit_status ?? 1
editForm.audit_time = src.audit_time ?? null
editForm.audit_by_name = src.audit_by_name || ''
editForm.audit_remark = src.audit_remark || ''
editForm.diagnosis_id = src.diagnosis_id ?? 0
editForm.creator_id = Number(src.creator_id) > 0 ? Number(src.creator_id) : 0
editForm.is_system_auto = Number(src.is_system_auto) === 1 ? 1 : 0
editForm.business_prescription_audit_rejected = Number(src.business_prescription_audit_rejected) === 1 ? 1 : 0
editForm.business_prescription_audit_remark = String(src.business_prescription_audit_remark || '')
nextTick(() => {
isLoadingData.value = false
formRef.value?.clearValidate()
scheduleEditSignatureInit()
})
showEdit.value = true
void loadRxLinkedOrderHintForEdit(Number(editForm.id))
}
function fillPrescriptionContents(src: Record<string, any>) {
editForm.prescription_type = src.prescription_type || '浓缩水丸' editForm.prescription_type = src.prescription_type || '浓缩水丸'
// 确保 dosage_amount 是数字类型,以匹配下拉框的 :value // 确保 dosage_amount 是数字类型,以匹配下拉框的 :value
@@ -3857,14 +4214,12 @@ const handleEdit = async (row: any) => {
editForm.patient_name = src.patient_name || '' editForm.patient_name = src.patient_name || ''
editForm.gender = src.gender ?? 1 editForm.gender = src.gender ?? 1
editForm.age = src.age ?? 0 editForm.age = src.age ?? 0
editForm.visit_no = src.visit_no || ''
editForm.prescription_date = src.prescription_date || ''
editForm.tongue = src.tongue || '' editForm.tongue = src.tongue || ''
editForm.tongue_image = src.tongue_image || '' editForm.tongue_image = src.tongue_image || ''
editForm.pulse = src.pulse || '' editForm.pulse = src.pulse || ''
editForm.pulse_condition = src.pulse_condition || '' editForm.pulse_condition = src.pulse_condition || ''
editForm.clinical_diagnosis = src.clinical_diagnosis || '' editForm.clinical_diagnosis = src.clinical_diagnosis || ''
editForm.herbs = src.herbs ? (src.herbs as any[]).map((h) => normalizeHerbRow(h)) : [] editForm.herbs = normalizeSlipHerbs(src.herbs)
editForm.dose_count = src.dose_count ?? 7 editForm.dose_count = src.dose_count ?? 7
editForm.dose_unit = src.dose_unit || '剂' editForm.dose_unit = src.dose_unit || '剂'
editForm.usage_days = src.usage_days ?? 7 editForm.usage_days = src.usage_days ?? 7
@@ -3873,39 +4228,13 @@ const handleEdit = async (row: any) => {
editForm.usage_time = src.usage_time || '饭后' editForm.usage_time = src.usage_time || '饭后'
editForm.usage_way = src.usage_way || '温水送服' editForm.usage_way = src.usage_way || '温水送服'
editForm.dietary_taboo = src.dietary_taboo editForm.dietary_taboo = src.dietary_taboo
? (Array.isArray(src.dietary_taboo) ? src.dietary_taboo : String(src.dietary_taboo).split(',').filter((v: string) => v)) ? (Array.isArray(src.dietary_taboo) ? [...src.dietary_taboo] : String(src.dietary_taboo).split(',').filter((v: string) => v))
: [] : []
editForm.usage_notes = src.usage_notes || '' editForm.usage_notes = src.usage_notes || ''
editForm.doctor_name = src.doctor_name || ''
editForm.doctor_signature = String(src.doctor_signature || '')
editForm.is_shared = src.is_shared ?? 0
editForm.visible_role_ids = normalizeVisibleRoleIds(src)
editForm.audit_status = src.audit_status ?? 1
editForm.audit_time = src.audit_time ?? null
editForm.audit_by_name = src.audit_by_name || ''
editForm.audit_remark = src.audit_remark || ''
editForm.diagnosis_id = src.diagnosis_id ?? 0
editForm.creator_id = Number(src.creator_id) > 0 ? Number(src.creator_id) : 0
editForm.is_system_auto = Number(src.is_system_auto) === 1 ? 1 : 0
editForm.business_prescription_audit_rejected = Number(src.business_prescription_audit_rejected) === 1 ? 1 : 0
editForm.business_prescription_audit_remark = String(src.business_prescription_audit_remark || '')
Object.assign( Object.assign(
editForm.aux_usage, editForm.aux_usage,
normalizeAuxUsageForm(src.aux_usage, editForm.prescription_type) normalizeAuxUsageForm(src.aux_usage, editForm.prescription_type)
) )
// 数据加载完成,重新启用watch
// 使用 setTimeout 确保所有数据都已经渲染完成
setTimeout(() => {
isLoadingData.value = false
}, 0)
showEdit.value = true
void loadRxLinkedOrderHintForEdit(Number(editForm.id))
nextTick(() => {
formRef.value?.clearValidate()
scheduleEditSignatureInit()
})
} }
// 提交表单 // 提交表单
@@ -3949,6 +4278,10 @@ const handleSubmit = async () => {
let result: any let result: any
if (editMode.value === 'add') { if (editMode.value === 'add') {
params.audit_status = 0 params.audit_status = 0
if (reissueContext.value) {
Object.assign(params, reissueContext.value)
if (!editForm.visit_no.trim()) delete params.visit_no
}
result = await prescriptionAdd(params) result = await prescriptionAdd(params)
} else { } else {
result = await prescriptionEdit(params) result = await prescriptionEdit(params)
@@ -3958,7 +4291,7 @@ const handleSubmit = async () => {
feedback.msgSuccess(result?.esign?.required ? '处方草稿已保存' : '处方已保存,请核对电子签署状态') feedback.msgSuccess(result?.esign?.required ? '处方草稿已保存' : '处方已保存,请核对电子签署状态')
await handleView({ ...editForm, id, audit_status: 0, esign: result?.esign }) await handleView({ ...editForm, id, audit_status: 0, esign: result?.esign })
} else { } else {
feedback.msgSuccess('保存成功,处方已进入待审核') feedback.msgSuccess('处方已保存,请在「已开处方」上传')
showEdit.value = false showEdit.value = false
} }
getLists() getLists()
@@ -4008,7 +4341,17 @@ onMounted(async () => {
} }
getLists() getLists()
const reviewId = Number(route.query.review_prescription) const reviewId = Number(route.query.review_prescription)
if (Number.isSafeInteger(reviewId) && reviewId > 0) openAuditDialog(reviewId) if (Number.isSafeInteger(reviewId) && reviewId > 0 && hasPermission(['cf.prescription/audit'])) {
try {
const detail = await prescriptionDetail({ id: reviewId })
if (canOpenPrescriptionAudit(detail)) openAuditDialog(detail)
else if (isPendingPrescriptionAudit(detail)) feedback.msgWarning(
Number(detail.review_submitted_at) > 0 ? '请等开方医生签署并通过验签后再审核' : '请开方医生先上传处方'
)
} catch {
// 请求失败时由拦截器显示提示。
}
}
}) })
</script> </script>
@@ -4177,6 +4520,10 @@ onMounted(async () => {
margin: -20px; margin: -20px;
} }
.rx-slip-tabs :deep(.el-tabs__content) {
overflow: visible;
}
.rx-toolbar { .rx-toolbar {
display: flex; display: flex;
align-items: center; align-items: center;
@@ -1273,7 +1273,8 @@
<el-dialog <el-dialog
v-model="auditVisible" v-model="auditVisible"
:title="auditTitle" :title="auditTitle"
width="480px" :width="auditKind === 'prescription' ? 'min(1280px, 96vw)' : '480px'"
:top="auditKind === 'prescription' ? '5vh' : undefined"
destroy-on-close destroy-on-close
@closed="auditRemark = ''" @closed="auditRemark = ''"
> >
@@ -1297,18 +1298,24 @@
</div> </div>
</template> </template>
</el-alert> </el-alert>
<EsignPrescriptionPanel <PrescriptionAuditLayout
v-if="auditVisible && auditKind === 'prescription'" :prescription-id="auditKind === 'prescription' ? Number(auditRowData?.prescription_id) || 0 : null"
:key="auditTargetId" :doctor-signed-at="auditEsign?.signature_time || auditEsign?.signed_at"
:prescription-id="Number(auditRowData?.prescription_id) || 0" :pharmacist-signed-at="auditReview?.signature_time || auditEsign?.review_signature_time"
audit >
:review-order-id="Number(auditTargetId)" <EsignPrescriptionPanel
@review-change="auditReview = $event" v-if="auditVisible && auditKind === 'prescription'"
class="mb-3" :key="auditTargetId"
@status-change="auditEsign = $event" :prescription-id="Number(auditRowData?.prescription_id) || 0"
/> audit
<p class="text-[13px] text-gray-500 mb-3 bg-gray-50/80 border border-gray-100 p-2 rounded">驳回时必须填写意见;通过时意见选填。</p> :review-order-id="Number(auditTargetId)"
<el-input v-model="auditRemark" type="textarea" :rows="4" maxlength="500" show-word-limit placeholder="在此输入审核意见..." /> @review-change="auditReview = $event"
class="mb-3"
@status-change="auditEsign = $event"
/>
<p class="text-[13px] text-gray-500 mb-3 bg-gray-50/80 border border-gray-100 p-2 rounded">驳回时必须填写意见;通过时意见选填。</p>
<el-input v-model="auditRemark" type="textarea" :rows="4" maxlength="500" show-word-limit placeholder="在此输入审核意见..." />
</PrescriptionAuditLayout>
<template #footer> <template #footer>
<el-button @click="auditVisible = false">取消</el-button> <el-button @click="auditVisible = false">取消</el-button>
<el-button type="primary" :loading="auditSubmitting" :disabled="!canApproveAudit" @click="submitAudit('approve')">同意通过</el-button> <el-button type="primary" :loading="auditSubmitting" :disabled="!canApproveAudit" @click="submitAudit('approve')">同意通过</el-button>
@@ -1820,6 +1827,7 @@
v-model="prescriptionTabType" v-model="prescriptionTabType"
class="mx-4 mt-2" class="mx-4 mt-2"
style="margin-bottom: 0; z-index: 1; position: relative" style="margin-bottom: 0; z-index: 1; position: relative"
:before-leave="() => !prescriptionSlipExporting"
> >
<el-tab-pane label="药房联" name="internal" /> <el-tab-pane label="药房联" name="internal" />
<el-tab-pane label="处方联" name="user" /> <el-tab-pane label="处方联" name="user" />
@@ -1878,7 +1886,7 @@
:key="prescriptionViewData.id" :key="prescriptionViewData.id"
:prescription-id="Number(prescriptionViewData.id)" :prescription-id="Number(prescriptionViewData.id)"
:initial-state="prescriptionViewData.esign" :initial-state="prescriptionViewData.esign"
@status-change="prescriptionViewData.esign = $event" @status-change="updatePrescriptionSlipEsign(prescriptionViewData, $event)"
/> />
<PrescriptionSlip <PrescriptionSlip
v-if="prescriptionViewData" v-if="prescriptionViewData"
@@ -2149,8 +2157,9 @@ import {
} from '@/api/tcm' } from '@/api/tcm'
import PrescriptionSlip from '@/components/prescription-slip/index.vue' import PrescriptionSlip from '@/components/prescription-slip/index.vue'
import EsignPrescriptionPanel from '@/components/EsignPrescriptionPanel.vue' import EsignPrescriptionPanel from '@/components/EsignPrescriptionPanel.vue'
import PrescriptionAuditLayout from '@/components/PrescriptionAuditLayout.vue'
import type { PrescriptionEsignStatus } from '@/api/tcm' import type { PrescriptionEsignStatus } from '@/api/tcm'
import { canApprovePrescriptionEsign, downloadPrescriptionPdfIfRequired, requiresOriginalEsignPdf } from '@/utils/prescription-esign' import { canApprovePrescriptionEsign, downloadPrescriptionPdfIfRequired, requiresOriginalEsignPdf, updatePrescriptionSlipEsign } from '@/utils/prescription-esign'
import html2canvas from 'html2canvas' import html2canvas from 'html2canvas'
import { jsPDF } from 'jspdf' import { jsPDF } from 'jspdf'
import { getDictData } from '@/api/app' import { getDictData } from '@/api/app'
@@ -2966,10 +2975,10 @@ function canEditRow(row: {
return fs === 1 || fs === 2 return fs === 1 || fs === 2
} }
function canRxAudit(row: { prescription_audit_status?: number; fulfillment_status?: number }) { function canRxAudit(row: { prescription_audit_status?: number; fulfillment_status?: number; can_review_prescription?: boolean }) {
const fs = Number(row.fulfillment_status) const fs = Number(row.fulfillment_status)
if (fs === 3 || fs === 4 || fs === 6) return false if (fs === 3 || fs === 4 || fs === 6) return false
return Number(row.prescription_audit_status) === 0 return Number(row.prescription_audit_status) === 0 && row.can_review_prescription === true
} }
function canPayAudit(row: { function canPayAudit(row: {
@@ -3729,6 +3738,7 @@ const auditTitle = computed(() =>
function openAudit(row: Record<string, any>, kind: 'prescription' | 'payment') { function openAudit(row: Record<string, any>, kind: 'prescription' | 'payment') {
if (auditSubmitting.value) return if (auditSubmitting.value) return
if (kind === 'prescription' && !canRxAudit(row)) return
auditKind.value = kind auditKind.value = kind
auditTargetId.value = Number(row.id) auditTargetId.value = Number(row.id)
auditRowData.value = row auditRowData.value = row
@@ -1840,7 +1840,8 @@
<el-dialog <el-dialog
v-model="auditVisible" v-model="auditVisible"
:title="auditTitle" :title="auditTitle"
width="92%" :width="auditKind === 'prescription' ? 'min(1280px, 96vw)' : '92%'"
:top="auditKind === 'prescription' ? '5vh' : undefined"
destroy-on-close destroy-on-close
class="po-h5-dialog" class="po-h5-dialog"
@closed="auditRemark = ''" @closed="auditRemark = ''"
@@ -1865,18 +1866,24 @@
</div> </div>
</template> </template>
</el-alert> </el-alert>
<EsignPrescriptionPanel <PrescriptionAuditLayout
v-if="auditVisible && auditKind === 'prescription'" :prescription-id="auditKind === 'prescription' ? Number(auditRowData?.prescription_id) || 0 : null"
:key="auditTargetId" :doctor-signed-at="auditEsign?.signature_time || auditEsign?.signed_at"
:prescription-id="Number(auditRowData?.prescription_id) || 0" :pharmacist-signed-at="auditReview?.signature_time || auditEsign?.review_signature_time"
audit >
:review-order-id="Number(auditTargetId)" <EsignPrescriptionPanel
@review-change="auditReview = $event" v-if="auditVisible && auditKind === 'prescription'"
class="mb-3" :key="auditTargetId"
@status-change="auditEsign = $event" :prescription-id="Number(auditRowData?.prescription_id) || 0"
/> audit
<p class="text-[13px] text-gray-500 mb-3 bg-gray-50/80 border border-gray-100 p-2 rounded">驳回时必须填写意见;通过时意见选填。</p> :review-order-id="Number(auditTargetId)"
<el-input v-model="auditRemark" type="textarea" :rows="4" maxlength="500" show-word-limit placeholder="在此输入审核意见..." /> @review-change="auditReview = $event"
class="mb-3"
@status-change="auditEsign = $event"
/>
<p class="text-[13px] text-gray-500 mb-3 bg-gray-50/80 border border-gray-100 p-2 rounded">驳回时必须填写意见;通过时意见选填。</p>
<el-input v-model="auditRemark" type="textarea" :rows="4" maxlength="500" show-word-limit placeholder="在此输入审核意见..." />
</PrescriptionAuditLayout>
<template #footer> <template #footer>
<el-button @click="auditVisible = false">取消</el-button> <el-button @click="auditVisible = false">取消</el-button>
<el-button type="primary" :loading="auditSubmitting" :disabled="!canApproveAudit" @click="submitAudit('approve')">同意通过</el-button> <el-button type="primary" :loading="auditSubmitting" :disabled="!canApproveAudit" @click="submitAudit('approve')">同意通过</el-button>
@@ -2420,6 +2427,7 @@
v-model="prescriptionTabType" v-model="prescriptionTabType"
class="mx-4 mt-2" class="mx-4 mt-2"
style="margin-bottom: 0; z-index: 1; position: relative" style="margin-bottom: 0; z-index: 1; position: relative"
:before-leave="() => !prescriptionSlipExporting"
> >
<el-tab-pane label="药房联" name="internal" /> <el-tab-pane label="药房联" name="internal" />
<el-tab-pane label="处方联" name="user" /> <el-tab-pane label="处方联" name="user" />
@@ -2478,7 +2486,7 @@
:key="prescriptionViewData.id" :key="prescriptionViewData.id"
:prescription-id="Number(prescriptionViewData.id)" :prescription-id="Number(prescriptionViewData.id)"
:initial-state="prescriptionViewData.esign" :initial-state="prescriptionViewData.esign"
@status-change="prescriptionViewData.esign = $event" @status-change="updatePrescriptionSlipEsign(prescriptionViewData, $event)"
/> />
<PrescriptionSlip <PrescriptionSlip
v-if="prescriptionViewData" v-if="prescriptionViewData"
@@ -2713,8 +2721,9 @@ import {
} from './components/prescription-order-utils' } from './components/prescription-order-utils'
import PrescriptionSlip from '@/components/prescription-slip/index.vue' import PrescriptionSlip from '@/components/prescription-slip/index.vue'
import EsignPrescriptionPanel from '@/components/EsignPrescriptionPanel.vue' import EsignPrescriptionPanel from '@/components/EsignPrescriptionPanel.vue'
import PrescriptionAuditLayout from '@/components/PrescriptionAuditLayout.vue'
import type { PrescriptionEsignStatus } from '@/api/tcm' import type { PrescriptionEsignStatus } from '@/api/tcm'
import { canApprovePrescriptionEsign, downloadPrescriptionPdfIfRequired, requiresOriginalEsignPdf } from '@/utils/prescription-esign' import { canApprovePrescriptionEsign, downloadPrescriptionPdfIfRequired, requiresOriginalEsignPdf, updatePrescriptionSlipEsign } from '@/utils/prescription-esign'
import html2canvas from 'html2canvas' import html2canvas from 'html2canvas'
import { jsPDF } from 'jspdf' import { jsPDF } from 'jspdf'
import { getDictData } from '@/api/app' import { getDictData } from '@/api/app'
@@ -3445,10 +3454,10 @@ function canEditRow(row: {
return fs === 1 || fs === 2 return fs === 1 || fs === 2
} }
function canRxAudit(row: { prescription_audit_status?: number; fulfillment_status?: number }) { function canRxAudit(row: { prescription_audit_status?: number; fulfillment_status?: number; can_review_prescription?: boolean }) {
const fs = Number(row.fulfillment_status) const fs = Number(row.fulfillment_status)
if (fs === 3 || fs === 4 || fs === 6) return false if (fs === 3 || fs === 4 || fs === 6) return false
return Number(row.prescription_audit_status) === 0 return Number(row.prescription_audit_status) === 0 && row.can_review_prescription === true
} }
function canPayAudit(row: { function canPayAudit(row: {
@@ -4696,6 +4705,7 @@ const auditTitle = computed(() =>
function openAudit(row: Record<string, any>, kind: 'prescription' | 'payment') { function openAudit(row: Record<string, any>, kind: 'prescription' | 'payment') {
if (auditSubmitting.value) return if (auditSubmitting.value) return
if (kind === 'prescription' && !canRxAudit(row)) return
auditKind.value = kind auditKind.value = kind
auditTargetId.value = Number(row.id) auditTargetId.value = Number(row.id)
auditRowData.value = row auditRowData.value = row
@@ -31,32 +31,45 @@
</template> </template>
</prescription-order-detail-drawer> </prescription-order-detail-drawer>
<el-dialog v-model="auditVisible" :title="auditTitle" width="480px" append-to-body destroy-on-close> <el-dialog
<EsignPrescriptionPanel v-model="auditVisible"
v-if="auditVisible && auditKind === 'prescription'" :title="auditTitle"
:key="actionRow.id" :width="auditKind === 'prescription' ? 'min(1280px, 96vw)' : '480px'"
:prescription-id="Number(actionRow.prescription_id) || 0" :top="auditKind === 'prescription' ? '5vh' : undefined"
audit append-to-body
:review-order-id="Number(actionRow.id)" destroy-on-close
@review-change="auditReview = $event" >
class="mb-3" <PrescriptionAuditLayout
@status-change="auditEsign = $event" :prescription-id="auditKind === 'prescription' ? Number(actionRow.prescription_id) || 0 : null"
/> :doctor-signed-at="auditEsign?.signature_time || auditEsign?.signed_at"
<el-alert :pharmacist-signed-at="auditReview?.signature_time || auditEsign?.review_signature_time"
title="通过时审核意见可不填;驳回时必须填写明确原因。" >
type="warning" <EsignPrescriptionPanel
:closable="false" v-if="auditVisible && auditKind === 'prescription'"
show-icon :key="actionRow.id"
class="mb-4" :prescription-id="Number(actionRow.prescription_id) || 0"
/> audit
<el-input :review-order-id="Number(actionRow.id)"
v-model="auditRemark" @review-change="auditReview = $event"
type="textarea" class="mb-3"
:rows="4" @status-change="auditEsign = $event"
maxlength="500" />
show-word-limit <el-alert
placeholder="请输入审核意见" title="通过时审核意见可不填;驳回时必须填写明确原因。"
/> type="warning"
:closable="false"
show-icon
class="mb-4"
/>
<el-input
v-model="auditRemark"
type="textarea"
:rows="4"
maxlength="500"
show-word-limit
placeholder="请输入审核意见"
/>
</PrescriptionAuditLayout>
<template #footer> <template #footer>
<el-button @click="auditVisible = false">取消</el-button> <el-button @click="auditVisible = false">取消</el-button>
<el-button type="primary" :loading="submitting" :disabled="!canApproveAudit" @click="submitAudit('approve')">同意通过</el-button> <el-button type="primary" :loading="submitting" :disabled="!canApproveAudit" @click="submitAudit('approve')">同意通过</el-button>
@@ -254,6 +267,7 @@ import { ArrowDown } from '@element-plus/icons-vue'
import { ElMessageBox } from 'element-plus' import { ElMessageBox } from 'element-plus'
import feedback from '@/utils/feedback' import feedback from '@/utils/feedback'
import EsignPrescriptionPanel from '@/components/EsignPrescriptionPanel.vue' import EsignPrescriptionPanel from '@/components/EsignPrescriptionPanel.vue'
import PrescriptionAuditLayout from '@/components/PrescriptionAuditLayout.vue'
import type { PrescriptionEsignStatus } from '@/api/tcm' import type { PrescriptionEsignStatus } from '@/api/tcm'
import { canApprovePrescriptionEsign } from '@/utils/prescription-esign' import { canApprovePrescriptionEsign } from '@/utils/prescription-esign'
import PrescriptionOrderDetailDrawer from '@/views/consumer/prescription/components/PrescriptionOrderDetailDrawer.vue' import PrescriptionOrderDetailDrawer from '@/views/consumer/prescription/components/PrescriptionOrderDetailDrawer.vue'
@@ -406,6 +420,7 @@ async function openEdit(row: Record<string, any>) {
function openAction(row: Record<string, any>, action: MyPatientOrderAction) { function openAction(row: Record<string, any>, action: MyPatientOrderAction) {
if (submitting.value && (action === 'audit_prescription' || action === 'audit_payment')) return if (submitting.value && (action === 'audit_prescription' || action === 'audit_payment')) return
if (action === 'audit_prescription' && row.can_review_prescription !== true) return
actionRow.value = row actionRow.value = row
switch (action) { switch (action) {
case 'edit': case 'edit':
@@ -50,6 +50,7 @@ export function myPatientOrderActions(row: Record<string, any>): MyPatientOrderA
} }
if ( if (
permitted('tcm.prescriptionOrder/auditPrescription') permitted('tcm.prescriptionOrder/auditPrescription')
&& row.can_review_prescription === true
&& prescriptionAudit === 0 && prescriptionAudit === 0
&& ![3, 4, 6].includes(fulfillment) && ![3, 4, 6].includes(fulfillment)
) { ) {
@@ -0,0 +1,110 @@
<template>
<div>
<el-card class="!border-none" shadow="never">
<el-form :model="filters" inline @submit.prevent="resetPage">
<el-form-item label="统计日期">
<el-date-picker
v-model="filters.date"
type="date"
value-format="YYYY-MM-DD"
:clearable="false"
/>
</el-form-item>
<el-form-item label="用户">
<el-input v-model.trim="filters.keyword" placeholder="账号或姓名" clearable />
</el-form-item>
<el-form-item>
<el-button native-type="submit" type="primary">查询</el-button>
<el-button @click="resetFilters">重置</el-button>
</el-form-item>
</el-form>
</el-card>
<el-card v-loading="pager.loading" class="!border-none mt-4" shadow="never">
<div class="flex flex-wrap items-baseline gap-x-4 gap-y-1 mb-4">
<h2 class="text-lg font-medium">桌面登录记录</h2>
<span v-if="pager.extend?.total_day_seconds != null">
当日会话累计 {{ durationText(pager.extend.total_day_seconds) }}
</span>
<span class="text-tx-secondary text-sm">按北京时间自然日统计</span>
</div>
<el-table :data="pager.lists" row-key="id" empty-text="当日没有匹配的桌面登录记录">
<el-table-column
label="账号"
prop="account"
min-width="120"
show-overflow-tooltip
/>
<el-table-column label="姓名" prop="name" min-width="100" show-overflow-tooltip />
<el-table-column label="登录时间" prop="login_time" width="176" />
<el-table-column label="退出时间" width="176">
<template #default="{ row }">{{ row.logout_time || '—' }}</template>
</el-table-column>
<el-table-column label="本次登录时长" min-width="130">
<template #default="{ row }">{{ durationText(row.duration_seconds) }}</template>
</el-table-column>
<el-table-column label="计入当日" min-width="130">
<template #default="{ row }">{{ durationText(row.day_seconds) }}</template>
</el-table-column>
<el-table-column label="状态" min-width="100">
<template #default="{ row }">
<el-tooltip
v-if="row.status === 'timeout'"
content="连续 3 分钟未收到心跳,退出时间按最后一次确认在线的时间记录"
placement="top"
>
<el-tag type="warning" effect="plain">{{ row.status_label }}</el-tag>
</el-tooltip>
<el-tag
v-else
:type="row.status === 'online' ? 'success' : 'info'"
effect="plain"
>
{{ row.status_label }}
</el-tag>
</template>
</el-table-column>
</el-table>
<div class="flex mt-4 justify-end">
<pagination v-model="pager" @change="getLists" />
</div>
</el-card>
</div>
</template>
<script lang="ts" setup name="desktopSessions">
import { desktopSessionLists } from '@/api/setting/system'
import { usePaging } from '@/hooks/usePaging'
const beijingDate = () =>
new Intl.DateTimeFormat('sv-SE', {
timeZone: 'Asia/Shanghai',
year: 'numeric',
month: '2-digit',
day: '2-digit'
}).format(new Date())
const filters = reactive({ date: beijingDate(), keyword: '' })
const { pager, getLists, resetPage } = usePaging({
fetchFun: desktopSessionLists,
params: filters,
latestOnly: true,
firstLoading: true
})
function resetFilters() {
filters.date = beijingDate()
filters.keyword = ''
resetPage()
}
function durationText(seconds: number) {
const hours = Math.floor(seconds / 3600)
const minutes = Math.floor((seconds % 3600) / 60)
if (hours) return `${hours}小时${minutes}分${seconds % 60}秒`
if (minutes) return `${minutes}分${seconds % 60}秒`
return `${seconds % 60}秒`
}
onMounted(() => getLists())
</script>
+28
View File
@@ -178,6 +178,34 @@ test('opening a pending enrollment performs a GET and requires an explicit resum
settings.unmount() settings.unmount()
}) })
test('certificate recheck reads a fresh result without leaving the dialog or writing enrollment', async () => {
let result = grant({ certificate_state: 'valid' })
const settings = createDialog({ read: () => result })
await flush()
assert.equal(settings.certificateLabel.value, '有效')
assert.match(dialogScript.template, /重新校验证书/)
assert.doesNotMatch(dialogScript.template, /切换签署账号/)
result = status({ status: 'renewal_required', certificate_state: 'unconfirmed' })
await settings.checkStatus()
assert.equal(settings.certificateLabel.value, '暂无法确认')
assert.match(settings.guidance.value, /重新校验/)
assert.equal(settings.statusNotice.value, '')
assert.deepEqual(settings.writeCalls(), [])
result = status({ status: 'renewal_required', certificate_state: 'renewal_required' })
await settings.checkStatus()
assert.equal(settings.certificateLabel.value, '需要续期')
assert.equal(settings.startLabel.value, '开始续期认证')
result = grant({ certificate_state: 'valid', quicksign_unavailable_reason: 'expired', quicksign_expires_at: 0 })
await settings.checkStatus()
assert.equal(settings.statusNotice.value, '证书校验通过。')
assert.equal(settings.certificateLabel.value, '有效')
assert.match(settings.guidance.value, /快捷签授权已过期/)
assert.deepEqual(settings.calls.map(([method]) => method), ['read', 'read', 'read', 'read'])
})
test('certificate renewal uses the explicitly entered mobile and clears it after starting', async () => { test('certificate renewal uses the explicitly entered mobile and clears it after starting', async () => {
const settings = createDialog({ read: () => status({ status: 'renewal_required' }) }) const settings = createDialog({ read: () => status({ status: 'renewal_required' }) })
await flush() await flush()
+448 -12
View File
@@ -51,6 +51,19 @@ test('signing mutations allow 180 seconds and explicitly disable transport repla
} }
}) })
test('the detail and audit status requests use independent cancellation signals', async () => {
const calls = []
const api = loadModule('api/tcm.ts', {
'@/utils/request': { default: { get: async (config, options) => { calls.push({ config, options }); return status() } } }
})
const detail = new AbortController()
const audit = new AbortController()
await Promise.all([api.prescriptionEsignStatus({ id: 17 }, detail.signal), api.prescriptionEsignStatus({ id: 17 }, audit.signal)])
assert.equal(calls[0].config.signal, detail.signal)
assert.equal(calls[1].config.signal, audit.signal)
assert.ok(calls.every((call) => call.options.ignoreCancelToken === true))
})
test('authentication links accept only absolute HTTPS URLs without credentials', () => { test('authentication links accept only absolute HTTPS URLs without credentials', () => {
const utils = loadModule('utils/prescription-esign.ts', { '@/api/tcm': {} }) const utils = loadModule('utils/prescription-esign.ts', { '@/api/tcm': {} })
for (const value of ['javascript:alert(1)', 'http://example.test', '//example.test', 'https://user:secret@example.test', '', null]) { for (const value of ['javascript:alert(1)', 'http://example.test', '//example.test', 'https://user:secret@example.test', '', null]) {
@@ -217,9 +230,11 @@ function panel(initial = status(), api = {}) {
clearTimeout: (id) => timers.delete(id), clearTimeout: (id) => timers.delete(id),
Date: { now: () => now }, document, Date: { now: () => now }, document,
props, emit: (_, value) => events.push(value), props, emit: (_, value) => events.push(value),
useUserStore: () => ({ serverTimeOffsetMs: 0 }),
safeEsignAuthUrl: utils.safeEsignAuthUrl, safeEsignAuthUrl: utils.safeEsignAuthUrl,
canApprovePrescriptionEsign: utils.canApprovePrescriptionEsign, canApprovePrescriptionEsign: utils.canApprovePrescriptionEsign,
canCheckEsignIdentity: utils.canCheckEsignIdentity, canCheckEsignIdentity: utils.canCheckEsignIdentity,
formatSigningTime: utils.formatSigningTime,
prescriptionEsignTiming: utils.prescriptionEsignTiming, prescriptionEsignTiming: utils.prescriptionEsignTiming,
validateEsignStatus: utils.validateEsignStatus, validateEsignStatus: utils.validateEsignStatus,
validateEsignIdentityStatus: utils.validateEsignIdentityStatus, validateEsignIdentityStatus: utils.validateEsignIdentityStatus,
@@ -227,13 +242,14 @@ function panel(initial = status(), api = {}) {
calls.push(['download', { id }]); return api.download?.(isCurrent) calls.push(['download', { id }]); return api.download?.(isCurrent)
}, },
prescriptionEsignStatus: async (p) => { calls.push(['status', p]); return api.refresh ? api.refresh() : initial }, prescriptionEsignStatus: async (p) => { calls.push(['status', p]); return api.refresh ? api.refresh() : initial },
prescriptionSubmitForReview: async (p) => { calls.push(['upload', p]); return api.upload(p) },
prescriptionEsignDoctorStatus: async (signal) => { calls.push(['profile']); return api.profile(signal) }, prescriptionEsignDoctorStatus: async (signal) => { calls.push(['profile']); return api.profile(signal) },
prescriptionEsignStart: async (p) => { calls.push(['start', p]); return api.start ? api.start(p) : identity() }, prescriptionEsignStart: async (p) => { calls.push(['start', p]); return api.start ? api.start(p) : identity() },
prescriptionEsignIdentityStatus: async (p, signal) => { calls.push(['identity', p]); return api.identity ? api.identity(signal) : identity() }, prescriptionEsignIdentityStatus: async (p, signal) => { calls.push(['identity', p]); return api.identity ? api.identity(signal) : identity() },
prescriptionEsignVerifyWillingness: async (p) => { calls.push(['verify-sms', p]); return api.verifySms(p) }, prescriptionEsignVerifyWillingness: async (p) => { calls.push(['verify-sms', p]); return api.verifySms(p) },
prescriptionEsignComplete: async (p) => { calls.push(['complete', p]); return api.complete ? api.complete(p) : status({ status: 'signed', can_sign: false, can_download: true }) } prescriptionEsignComplete: async (p) => { calls.push(['complete', p]); return api.complete ? api.complete(p) : status({ status: 'signed', can_sign: false, can_download: true }) }
} }
const value = new Function(...Object.keys(globals), `${compiledPanel}\nreturn { state, busy, work, confirmed, showControls, signingTime, error, authUrl, start, refresh, dialogVisible, readiness, action, message, activeStep, identityNumber, identityDetailsRequired, confirmSign, closeAuthentication, authenticationUnavailable, onVisibilityChange, smsCode, smsCodeEntry, smsSendCoolingDown, sendSms, verifySms }`)(...Object.values(globals)) const value = new Function(...Object.keys(globals), `${compiledPanel}\nreturn { state, busy, work, confirmed, showControls, signingTime, signingLog, showSigningLog, error, authUrl, start, refresh, dialogVisible, readiness, action, message, activeStep, identityNumber, identityDetailsRequired, confirmSign, closeAuthentication, authenticationUnavailable, onVisibilityChange, smsCode, smsCodeEntry, smsSendCoolingDown, sendSms, verifySms, showSteps, reviewRequired, reviewSigning, updateReview, runAction, statusNotice }`)(...Object.values(globals))
value.confirmed.value = true // The existing-state tests begin after a successful initial query. value.confirmed.value = true // The existing-state tests begin after a successful initial query.
async function advance(ms) { async function advance(ms) {
now += ms now += ms
@@ -260,6 +276,43 @@ function accountBasedIdentity(method, changes = {}) {
}) })
} }
test('a saved draft must upload before quick-sign preparation, with retry and explicit confirmation', async () => {
const draft = status({
review_required: true, awaiting_upload: true, review_submitted_at: 0,
can_submit_for_review: true, can_review_prescription: false, can_sign: false
})
const submitted = accountBasedStatus('quick', {
review_required: true, awaiting_upload: false, review_submitted_at: 1760000000,
can_submit_for_review: false, can_review_prescription: false
})
let attempts = 0
const p = panel(draft, {
refresh: async () => attempts === 2 ? submitted : draft,
upload: async () => {
if (++attempts === 1) throw new Error('temporary network error')
return { review_submitted_at: 1760000000, can_submit_for_review: false }
},
start: async () => ({ ...submitted, status: 'authenticating', can_resume_identity: true }),
identity: async () => accountBasedIdentity('quick', {
...submitted, status: 'authenticating', can_resume_identity: true
})
})
p.watchers[0]()
await flush()
assert.equal(p.action.value.label, '上传处方')
assert.equal(p.activeStep.value, 1)
assert.deepEqual(p.calls.map(([name]) => name), ['status'])
await p.runAction()
assert.match(p.error.value, /重试/)
assert.equal(p.action.value.label, '上传处方')
await p.runAction()
assert.deepEqual(p.calls.map(([name]) => name), ['status', 'upload', 'upload', 'status', 'start', 'identity'])
assert.equal(p.action.value.label, '确认签名')
assert.equal(p.activeStep.value, 2)
await p.runAction()
assert.equal(p.calls.at(-1)[0], 'complete')
})
test('quick signing prepares once on open and waits for the prescriber to confirm', async () => { test('quick signing prepares once on open and waits for the prescriber to confirm', async () => {
const prepared = accountBasedStatus('quick', { status: 'authenticating', can_resume_identity: true }) const prepared = accountBasedStatus('quick', { status: 'authenticating', can_resume_identity: true })
const p = panel(accountBasedStatus('quick'), { const p = panel(accountBasedStatus('quick'), {
@@ -307,7 +360,7 @@ test('quick signing routes missing identity and unusable grants to account setti
await blocked.refresh() await blocked.refresh()
await blocked.confirmSign() await blocked.confirmSign()
assert.deepEqual(blocked.calls.map(([method]) => method), ['status']) assert.deepEqual(blocked.calls.map(([method]) => method), ['status'])
assert.match(blocked.message.value, /身份认证.*医生电子签署身份/) assert.match(blocked.message.value, /身份认证.*签署身份与证书/)
for (const [reason, copy] of [['missing', /待完成/], ['expired', /已到期/], ['exhausted', /次数已用完/], ['invalid', /已失效/]]) { for (const [reason, copy] of [['missing', /待完成/], ['expired', /已到期/], ['exhausted', /次数已用完/], ['invalid', /已失效/]]) {
let authorized = false let authorized = false
@@ -322,7 +375,7 @@ test('quick signing routes missing identity and unusable grants to account setti
assert.deepEqual(p.calls.map(([method]) => method), ['status', 'start']) assert.deepEqual(p.calls.map(([method]) => method), ['status', 'start'])
assert.equal(p.action.value.label, '查询签署状态') assert.equal(p.action.value.label, '查询签署状态')
assert.match(p.message.value, copy) assert.match(p.message.value, copy)
assert.match(p.message.value, /医生电子签署身份.*查询签署状态/) assert.match(p.message.value, /签署身份与证书/)
authorized = true authorized = true
await p.action.value.run() await p.action.value.run()
assert.equal(p.action.value.label, '确认签名') assert.equal(p.action.value.label, '确认签名')
@@ -451,7 +504,7 @@ test('SMS checks the repaired account profile before allowing another manual sen
identity: async () => accountBasedIdentity('sms', { identity_status: 'ING', can_complete: false }) identity: async () => accountBasedIdentity('sms', { identity_status: 'ING', can_complete: false })
}) })
await p.refresh() await p.refresh()
assert.match(p.message.value, /医生电子签署身份/) assert.match(p.message.value, /签署身份与证书/)
await p.sendSms() await p.sendSms()
assert.deepEqual(p.calls.map(([method]) => method), ['status', 'profile']) assert.deepEqual(p.calls.map(([method]) => method), ['status', 'profile'])
@@ -512,6 +565,53 @@ test('audit panel retains signing evidence when signing actions are hidden', asy
assert.equal(p.signingTime.value.signatureTime, '2026/11/18 00:03:04') assert.equal(p.signingTime.value.signatureTime, '2026/11/18 00:03:04')
}) })
test('audit progress waits for a verified pharmacist signature and shows its trusted time', async () => {
const doctor = status({ status: 'signed', can_sign: false, can_download: true, review_required: true })
const p = panel(doctor)
p.props.audit = true
await p.refresh()
assert.equal(p.showControls.value, false)
assert.equal(p.showSteps.value, true)
assert.equal(p.activeStep.value, 3)
assert.match(p.message.value, /等待药师审核签署/)
const time = Date.parse('2026-11-17T16:03:04Z') / 1000
p.updateReview({ required: true, state: 'verifying', signature_time: time, signer_name: '测试药师' })
assert.equal(p.reviewSigning.value, null)
assert.equal(p.activeStep.value, 3)
p.updateReview({ required: true, state: 'signed', signature_time: 0, signer_name: '测试药师' })
assert.equal(p.activeStep.value, 3)
p.updateReview({ required: true, state: 'signed', signature_time: time, signer_name: '测试药师' })
assert.equal(p.activeStep.value, 4)
assert.deepEqual(p.reviewSigning.value, { time: '2026/11/18 00:03:04', name: '测试药师' })
})
test('single-signed records retain three steps and archived pharmacist timestamps show a completed fourth step', async () => {
const signed = status({ status: 'signed', can_sign: false, can_download: true })
const single = panel(signed)
assert.equal(single.showSteps.value, true)
assert.equal(single.reviewRequired.value, false)
assert.equal(single.activeStep.value, 3)
const audit = panel(signed)
audit.props.audit = true
await audit.refresh()
assert.equal(audit.showSteps.value, false)
audit.updateReview({ required: true, state: 'pending' })
assert.equal(audit.showSteps.value, true)
assert.equal(audit.activeStep.value, 3)
const time = Date.parse('2026-11-17T16:03:04Z') / 1000
for (const status of ['signed', 'voided']) {
const response = { ...signed, status, review_signature_time: time, review_signer_name: '测试药师' }
const dual = panel(signed, { refresh: async () => response })
await dual.refresh()
assert.equal(dual.showSteps.value, true)
assert.equal(dual.reviewRequired.value, true)
assert.equal(dual.activeStep.value, 4)
assert.deepEqual(dual.reviewSigning.value, { time: '2026/11/18 00:03:04', name: '测试药师' })
}
})
test('audit signing panel directs unsigned work to the prescriber', async () => { test('audit signing panel directs unsigned work to the prescriber', async () => {
let response = status() let response = status()
const p = panel(status(), { refresh: async () => response }) const p = panel(status(), { refresh: async () => response })
@@ -1045,12 +1145,28 @@ test('supplementary identity is a masked input with explicit action and no persi
const { descriptor } = parse(source) const { descriptor } = parse(source)
assert.match(descriptor.template.content, /v-model="identityNumber"\s+type="password"/) assert.match(descriptor.template.content, /v-model="identityNumber"\s+type="password"/)
assert.match(descriptor.template.content, /autocomplete="off"/) assert.match(descriptor.template.content, /autocomplete="off"/)
assert.match(descriptor.template.content, /@click="action.run"/) assert.match(descriptor.template.content, /@click="runAction"/)
assert.match(source, /const run = action\.value\.run\s+const current = operation\s+await run\(\)/)
assert.match(source, /label: '确认签名', run: confirmSign/) assert.match(source, /label: '确认签名', run: confirmSign/)
assert.match(descriptor.template.content, /v-if="authUrl && dialogVisible/) assert.match(descriptor.template.content, /v-if="authUrl && dialogVisible/)
assert.doesNotMatch(source, /show-password|localStorage|sessionStorage|console\.|window\.open|window\.location/) assert.doesNotMatch(source, /show-password|localStorage|sessionStorage|console\.|window\.open|window\.location/)
}) })
test('status checks and exiting authentication retain a visible notice without submitting a signature', async () => {
const p = panel(status())
p.confirmed.value = false
await p.runAction()
assert.match(p.statusNotice.value, /签署状态已更新/)
p.dialogVisible.value = true
p.identityNumber.value = 'private-input'
p.closeAuthentication()
assert.equal(p.dialogVisible.value, false)
assert.equal(p.identityNumber.value, '')
assert.match(p.statusNotice.value, /已退出本次签署/)
assert.equal(p.action.value.label, '查询签署状态')
assert.deepEqual(p.calls.map(([method]) => method), ['status'])
})
function pageDeclarations(filename, selected, globals) { function pageDeclarations(filename, selected, globals) {
const fullPath = path.join(__dirname, '../src', filename) const fullPath = path.join(__dirname, '../src', filename)
const source = parse(fs.readFileSync(fullPath, 'utf8'), { filename: fullPath }).descriptor.scriptSetup.content const source = parse(fs.readFileSync(fullPath, 'utf8'), { filename: fullPath }).descriptor.scriptSetup.content
@@ -1069,6 +1185,146 @@ function pageDeclarations(filename, selected, globals) {
return new Function(...Object.keys(globals), `${compiled}\nreturn { ${selected.join(', ')} }`)(...Object.values(globals)) return new Function(...Object.keys(globals), `${compiled}\nreturn { ${selected.join(', ')} }`)(...Object.values(globals))
} }
test('audit preview loads only its current prescription and refreshes after a signing change', async () => {
const filename = 'PrescriptionAuditLayout.vue'
const source = fs.readFileSync(path.join(__dirname, '../src/components', filename), 'utf8')
const { descriptor } = parse(source, { filename })
const script = compileScript(descriptor, { id: 'audit-preview-test' }).content
const js = ts.transpileModule(script, {
compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS }
}).outputText
const calls = []
const imports = {
vue,
'@/api/tcm': { prescriptionDetail: ({ id }, signal) => new Promise((resolve) => calls.push({ id, signal, resolve })) },
'@/components/prescription-slip/index.vue': { default: {} }
}
const exports = {}
new Function('require', 'exports', js)((id) => imports[id], exports)
const props = vue.reactive({ prescriptionId: null })
const scope = vue.effectScope()
const preview = scope.run(() => exports.default.setup(props, { expose() {} }))
try {
assert.equal(calls.length, 0)
props.prescriptionId = 51
await vue.nextTick()
props.prescriptionId = 52
await vue.nextTick()
assert.equal(calls[0].signal.aborted, true)
assert.deepEqual(calls.map((call) => call.id), [51, 52])
calls[0].resolve({ id: 51 })
calls[1].resolve({ id: 51 })
await Promise.resolve()
assert.equal(preview.detail.value, null)
assert.match(preview.error.value, /重试/)
preview.retry.value++
await vue.nextTick()
calls[2].resolve({ id: 52, esign: { signature_time: 10 } })
await Promise.resolve()
assert.equal(preview.detail.value.id, 52)
assert.equal(preview.error.value, '')
props.doctorSignedAt = 10
await vue.nextTick()
assert.equal(calls.length, 3)
props.pharmacistSignedAt = 15
await vue.nextTick()
assert.equal(calls[3].id, 52)
calls[3].resolve({ id: 52, esign: { signature_time: 10, review_signature_time: 15 } })
await Promise.resolve()
assert.equal(preview.detail.value.esign.review_signature_time, 15)
} finally {
scope.stop()
}
})
test('signing log orders actual events and preserves the time source and empty states', () => {
const time = Date.parse('2026-11-17T16:03:04Z') / 1000
const entries = [
{ event: 'archived', label: '系统归档完成', time: time + 3, source: 'system' },
{ event: 'signed', label: '医师签署', time, source: 'tsa', actor_name: '测试医师', message: '签署完成' },
{ event: 'draft', label: '草稿已保存', time: time - 2, source: 'local' },
{ event: 'invalid', label: '无效时间', time: 0, source: 'tsa' },
{ event: 'unknown', label: '未知来源', time, source: 'unknown' }
]
const withEvents = panel(status({ signing_log: entries }))
assert.deepEqual(withEvents.signingLog.value.map((entry) => [entry.event, entry.sourceLabel]), [
['draft', '签名记录时间'], ['signed', '可信时间戳'], ['archived', '系统记录']
])
assert.equal(withEvents.signingLog.value[1].actor_name, '测试医师')
assert.equal(withEvents.signingLog.value[1].message, '签署完成')
assert.equal(withEvents.signingLog.value[1].timeText, '2026/11/18 00:03:04')
assert.equal(entries[0].event, 'archived')
assert.equal(withEvents.showSigningLog.value, true)
const pending = panel(status())
assert.deepEqual(pending.signingLog.value, [])
assert.equal(pending.showSigningLog.value, true)
const audit = panel(status())
audit.props.audit = true
assert.equal(audit.showSigningLog.value, false)
assert.equal(panel(status({ required: false, status: 'legacy' })).showSigningLog.value, false)
})
test('both slips use verified physician and pharmacist PNGs and fall back to the signer names', () => {
const png = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jN9sAAAAASUVORK5CYII='
const props = vue.reactive({ variant: 'internal', data: { doctor_name: '开方人', doctor_signature: png, esign: status({
status: 'signed', doctor_signer_name: ' 测试医生 ',
review_signature_time: 1794931384, review_signer_name: ' 测试药师 ', review_signature: png
}) } })
const component = 'components/prescription-slip/index.vue'
const { doctorName, doctorSignature, failedDoctorSignature, reviewerName, reviewerSignature, failedReviewerSignature } = pageDeclarations(component,
['verifiedDoctor', 'doctorName', 'failedDoctorSignature', 'doctorSignature',
'reviewerName', 'failedReviewerSignature', 'reviewerSignature', 'isVerifiedSignaturePng'],
{ computed: vue.computed, ref: vue.ref, props })
for (const variant of ['internal', 'user']) {
props.variant = variant
assert.equal(doctorName.value, '测试医生')
assert.equal(doctorSignature.value, png)
assert.equal(reviewerName.value, '测试药师')
assert.equal(reviewerSignature.value, png)
failedDoctorSignature.value = png
failedReviewerSignature.value = png
assert.equal(doctorSignature.value, '')
assert.equal(reviewerSignature.value, '')
assert.equal(doctorName.value, '测试医生')
assert.equal(reviewerName.value, '测试药师')
failedDoctorSignature.value = ''
failedReviewerSignature.value = ''
}
props.data.esign.status = 'pending'
assert.equal(doctorSignature.value, '')
assert.equal(doctorName.value, '开方人')
assert.equal(reviewerName.value, '')
assert.equal(reviewerSignature.value, '')
props.data.esign.status = 'signed'
props.data.esign.review_signature = 'data:image/svg+xml;base64,PHN2Zz4='
assert.equal(reviewerSignature.value, '')
assert.equal(reviewerName.value, '测试药师')
})
test('the slip reloads a newly verified physician seal once from prescription detail', async () => {
const requests = []
const { updatePrescriptionSlipEsign } = loadModule('utils/prescription-esign.ts', { '@/api/tcm': {
prescriptionDetail: async ({ id }) => {
requests.push(id)
return { id, doctor_signature: 'verified seal' }
}
} })
const signed = status({ status: 'signed', can_sign: false, can_download: true })
const slip = { id: 17, esign: status(), doctor_signature: 'old signature' }
const refreshed = updatePrescriptionSlipEsign(slip, signed)
assert.equal(slip.esign, signed)
assert.equal(slip.doctor_signature, '')
await refreshed
assert.equal(slip.doctor_signature, 'verified seal')
await updatePrescriptionSlipEsign(slip, signed)
assert.deepEqual(requests, [17])
})
test('shared editor permits an unsigned save only in enabled mode and retains the saved id after detail failure', async () => { test('shared editor permits an unsigned save only in enabled mode and retains the saved id after detail failure', async () => {
for (const enabled of [false, true]) { for (const enabled of [false, true]) {
const requests = [] const requests = []
@@ -1105,7 +1361,7 @@ test('consumer editor keeps the saved prescription open for signing instead of r
formRef: vue.ref({ validate: async () => {} }), submitLoading: vue.ref(false), formRef: vue.ref({ validate: async () => {} }), submitLoading: vue.ref(false),
esignReady: vue.ref(true), esignEnabled: vue.ref(true), loadEsignConfig: async () => true, esignReady: vue.ref(true), esignEnabled: vue.ref(true), loadEsignConfig: async () => true,
editForm: { herbs: [{ name: 'test herb', dosage: 1 }], doctor_signature: '' }, editForm: { herbs: [{ name: 'test herb', dosage: 1 }], doctor_signature: '' },
editMode: vue.ref('add'), showEdit: vue.ref(true), herbValidationLabel: () => 'test herb', editMode: vue.ref('add'), showEdit: vue.ref(true), reissueContext: vue.ref(null), herbValidationLabel: () => 'test herb',
prescriptionAdd: async () => ({ id: 17, esign: status() }), prescriptionAdd: async () => ({ id: 17, esign: status() }),
prescriptionEdit: async () => { throw new Error('wrong API') }, prescriptionEdit: async () => { throw new Error('wrong API') },
handleView: async (row) => viewed.push(row), getLists: () => {}, handleView: async (row) => viewed.push(row), getLists: () => {},
@@ -1119,7 +1375,177 @@ test('consumer editor keeps the saved prescription open for signing instead of r
assert.match(messages[0], /处方草稿已保存/) assert.match(messages[0], /处方草稿已保存/)
}) })
test('opening a consumer audit clears previous evidence and allows rejection while signing is pending', async () => { test('list upload can retry and opens signing without exposing audit to the pharmacist', async () => {
const requests = []
const messages = []
const opened = []
const row = {
id: 17, audit_status: 0, review_submitted_at: 0, can_submit_for_review: true, can_review_prescription: false,
esign: status({ awaiting_upload: true, can_sign: false })
}
const drawer = { ...row }
const { pendingPrescriptionReviewLabel } = loadModule('utils/prescription-esign.ts', { '@/api/tcm': {} })
const globals = {
pager: { lists: [row] }, slipView: vue.ref(drawer), uploadingPrescriptionId: vue.ref(0),
getLists: async () => {},
handleView: async (rx) => { opened.push(rx.id) },
prescriptionSubmitForReview: async (params) => {
requests.push(params)
if (requests.length === 1) throw new Error('temporary network error')
return { review_submitted_at: 1760000000, can_submit_for_review: false }
},
feedback: { msgSuccess: (message) => messages.push(message) }
}
const { submitPrescriptionForReview, canOpenPrescriptionAudit } = pageDeclarations(
'views/consumer/prescription/index.vue',
['isPendingPrescriptionAudit', 'canOpenPrescriptionAudit', 'submitPrescriptionForReview'], globals
)
assert.equal(canOpenPrescriptionAudit(row), false)
assert.equal(pendingPrescriptionReviewLabel(row), '待上传')
await submitPrescriptionForReview({ ...row, can_submit_for_review: false })
assert.equal(requests.length, 0)
await submitPrescriptionForReview(row)
assert.equal(canOpenPrescriptionAudit(row), false)
assert.equal(globals.uploadingPrescriptionId.value, 0)
await submitPrescriptionForReview(row)
assert.deepEqual(requests, [{ id: 17 }, { id: 17 }])
assert.equal(canOpenPrescriptionAudit(row), false)
assert.equal(canOpenPrescriptionAudit(globals.slipView.value), false)
assert.equal(pendingPrescriptionReviewLabel(row), '待医师签署')
const verified = {
...row, can_review_prescription: true,
esign: { ...row.esign, status: 'signed', can_review_prescription: true }
}
assert.equal(canOpenPrescriptionAudit(verified), true)
assert.equal(pendingPrescriptionReviewLabel(verified), '待审核')
assert.equal(canOpenPrescriptionAudit({ ...verified, void_status: 1 }), false)
assert.equal(row.can_submit_for_review, false)
assert.equal(globals.slipView.value.esign.review_submitted_at, 1760000000)
assert.deepEqual(opened, [17])
assert.match(messages[0], /请完成医师签署/)
})
test('issued prescriptions can void pending drafts with permission and keep the record', async () => {
const calls = []
const messages = []
let cancel = true
let refreshes = 0
const row = { id: 17, audit_status: '0', can_void: true, can_submit_for_review: true }
const globals = {
voidingPrescriptionId: vue.ref(0),
prescriptionVoid: async (params) => {
calls.push(params)
if (calls.length === 1) throw new Error('temporary failure')
},
getLists: async () => { refreshes++ },
feedback: {
confirm: async () => { if (cancel) throw new Error('cancel') },
msgSuccess: (message) => messages.push(message)
}
}
const { canVoidPendingPrescription, voidPendingPrescription } = pageDeclarations(
'views/consumer/prescription/index.vue',
['isPendingPrescriptionAudit', 'canVoidPendingPrescription', 'voidPendingPrescription'], globals
)
assert.equal(canVoidPendingPrescription(row), true)
for (const other of [{ audit_status: 1 }, { audit_status: 2 }, { void_status: 1 }, { can_void: false }]) {
await voidPendingPrescription({ ...row, ...other })
}
await voidPendingPrescription(row)
assert.deepEqual(calls, [])
cancel = false
await voidPendingPrescription(row)
assert.equal(canVoidPendingPrescription(row), true)
await Promise.all([voidPendingPrescription(row), voidPendingPrescription(row)])
assert.deepEqual(calls, [{ id: 17, pending_only: true }, { id: 17, pending_only: true }])
assert.equal(row.void_status, 1)
assert.equal(row.can_submit_for_review, false)
assert.equal(canVoidPendingPrescription(row), false)
assert.equal(refreshes, 1)
assert.deepEqual(messages, ['处方已作废'])
})
test('issued prescriptions reopen a voided record as a new prescription with fresh signature and review', async () => {
const source = {
id: 17, sn: 'RX0017', visit_no: 'RX0017', void_status: '1', creator_id: '8',
prescription_date: '2025-01-01', prescription_type: '饮片', dosage_amount: '120',
diagnosis_id: 18, appointment_id: 19, patient_id: 20, phone: 'test', patient_name: '虚构测试',
clinical_diagnosis: '虚构诊断', herbs: [{ name: '测试药材', dosage: 1, formula_type: '辅方' }],
dietary_taboo: ['测试项目'], prescription_name: '测试处方', case_record: { archive: true },
audit_status: 2, doctor_signature: 'data:image/png;base64,old', esign: status({ status: 'voided' }),
prescription_order_id: 21, is_shared: 1, visible_role_ids: [22]
}
const newEsign = status({ status: 'pending', awaiting_upload: true })
const view = []
const saves = []
const reads = []
const warnings = []
const form = { aux_usage: {} }
let permitted = true
let detail = { ...source, void_status: 0 }
const globals = {
userStore: { userInfo: { id: 8, name: '虚构医师' } }, hasPermission: () => permitted,
showEdit: vue.ref(false), editMode: vue.ref('view'), slipView: vue.ref(null), editForm: form,
reissueContext: vue.ref(null), reissuingPrescriptionId: vue.ref(0), isLoadingData: vue.ref(false),
editingWasVoid: vue.ref(true), editingWasRejected: vue.ref(true),
nextTick: vue.nextTick, formRef: vue.ref({ clearValidate() {}, validate: async () => true }),
loadEsignConfig: async () => true, scheduleEditSignatureInit() {}, clearRxLinkedOrderHint() {},
dayRangeStrings: () => ({ start: '2026-11-23 00:00:00' }), defaultAuxUsage: () => ({}),
normalizeAuxUsageForm: () => ({}), normalizeSlipHerbs: (herbs) => herbs.map((herb) => ({ ...herb })),
submitLoading: vue.ref(false), esignReady: vue.ref(true), esignEnabled: vue.ref(true),
herbValidationLabel: () => '药材', prescriptionDetail: async (params) => { reads.push(params); return detail },
prescriptionAdd: async (params) => { saves.push(params); return { id: 23, esign: newEsign } },
prescriptionEdit: async () => assert.fail('reissue edited original prescription'),
handleView: async (row) => view.push(row), getLists() {},
feedback: { msgSuccess() {}, msgWarning: (message) => warnings.push(message), msgError: assert.fail }
}
const { canReissuePrescription, handleReissue, handleSubmit, handleAdd } = pageDeclarations(
'views/consumer/prescription/index.vue',
['resetForm', 'fillPrescriptionContents', 'openNewPrescription', 'handleAdd', 'canReissuePrescription', 'handleReissue', 'handleSubmit'], globals
)
assert.equal(canReissuePrescription(source), true)
await handleReissue({ ...source, void_status: 0 })
await handleReissue({ ...source, creator_id: 9 })
permitted = false
await handleReissue(source)
assert.deepEqual(reads, [])
permitted = true
await handleReissue(source)
assert.equal(globals.showEdit.value, false)
assert.equal(warnings.length, 1)
detail = source
await Promise.all([handleReissue(source), handleReissue(source)])
assert.deepEqual(reads, [{ id: 17 }, { id: 17 }])
assert.equal(globals.showEdit.value, true)
assert.equal(globals.editMode.value, 'add')
assert.equal(form.id, 0)
assert.equal(form.doctor_signature, '')
assert.equal(form.prescription_date, '2026-11-23')
assert.equal(form.dosage_amount, 120)
assert.deepEqual(form.herbs, source.herbs)
form.dietary_taboo.push('本次新增')
assert.deepEqual(source.dietary_taboo, ['测试项目'])
await handleSubmit()
const [saved] = saves
assert.equal(saved.audit_status, 0)
assert.equal(saved.diagnosis_id, 18)
assert.equal(saved.appointment_id, 19)
assert.equal(saved.patient_id, 20)
assert.equal(saved.phone, 'test')
assert.equal(saved.prescription_name, '测试处方')
assert.equal(saved.case_record, undefined)
assert.equal(saved.doctor_signature, '')
assert.deepEqual(saved.visible_role_ids, [])
for (const field of ['sn', 'visit_no', 'void_status', 'esign', 'prescription_order_id']) {
assert.equal(Object.hasOwn(saved, field), false)
}
assert.equal(view[0].id, 23)
assert.deepEqual(view[0].esign, newEsign)
handleAdd()
assert.equal(globals.reissueContext.value, null)
})
test('opening a submitted consumer audit clears previous evidence and still needs pharmacist signature for approval', async () => {
const requests = [] const requests = []
const { canApprovePrescriptionEsign } = loadModule('utils/prescription-esign.ts', { '@/api/tcm': {} }) const { canApprovePrescriptionEsign } = loadModule('utils/prescription-esign.ts', { '@/api/tcm': {} })
const signed = status({ status: 'signed', can_download: true, can_sign: false }) const signed = status({ status: 'signed', can_download: true, can_sign: false })
@@ -1133,10 +1559,14 @@ test('opening a consumer audit clears previous evidence and allows rejection whi
} }
const { openAuditDialog, onAuditEsignStatusChange, submitAudit } = pageDeclarations( const { openAuditDialog, onAuditEsignStatusChange, submitAudit } = pageDeclarations(
'views/consumer/prescription/index.vue', 'views/consumer/prescription/index.vue',
['canApproveAudit', 'openAuditDialog', 'onAuditEsignStatusChange', 'submitAudit'], globals ['canApproveAudit', 'isPendingPrescriptionAudit', 'canOpenPrescriptionAudit', 'openAuditDialog', 'onAuditEsignStatusChange', 'submitAudit'], globals
) )
openAuditDialog(17) openAuditDialog({ id: 17, audit_status: 0, review_submitted_at: 0 })
assert.equal(globals.auditDialogVisible.value, false)
openAuditDialog({ id: 17, audit_status: 0, review_submitted_at: 1760000000, can_review_prescription: false })
assert.equal(globals.auditDialogVisible.value, false)
openAuditDialog({ id: 17, audit_status: 0, review_submitted_at: 1760000000, can_review_prescription: true })
assert.equal(globals.auditEsign.value, null) assert.equal(globals.auditEsign.value, null)
assert.equal(globals.auditReview.value, null) assert.equal(globals.auditReview.value, null)
await submitAudit('approve') await submitAudit('approve')
@@ -1146,7 +1576,7 @@ test('opening a consumer audit clears previous evidence and allows rejection whi
globals.auditRemark.value = '处方需修正' globals.auditRemark.value = '处方需修正'
await submitAudit('reject') await submitAudit('reject')
openAuditDialog(18) openAuditDialog({ id: 18, audit_status: 0, review_submitted_at: 1760000000, can_review_prescription: true })
onAuditEsignStatusChange(signed) onAuditEsignStatusChange(signed)
await submitAudit('approve') await submitAudit('approve')
assert.equal(requests.length, 1, 'a single verified doctor signature cannot approve') assert.equal(requests.length, 1, 'a single verified doctor signature cannot approve')
@@ -1181,8 +1611,13 @@ for (const filename of [
} }
const isFirstVisit = filename.includes('OrderActionHost') const isFirstVisit = filename.includes('OrderActionHost')
const open = isFirstVisit ? 'openAction' : 'openAudit' const open = isFirstVisit ? 'openAction' : 'openAudit'
const handlers = pageDeclarations(filename, ['canApproveAudit', open, 'submitAudit'], globals) const helpers = isFirstVisit ? [] : ['canRxAudit']
handlers[open]({ id: 17, prescription_id: 51 }, isFirstVisit ? 'audit_prescription' : 'prescription') const handlers = pageDeclarations(filename, ['canApproveAudit', ...helpers, open, 'submitAudit'], globals)
const row = { id: 17, prescription_id: 51, prescription_audit_status: 0, fulfillment_status: 1 }
const prescriptionAction = isFirstVisit ? 'audit_prescription' : 'prescription'
handlers[open]({ ...row, can_review_prescription: false }, prescriptionAction)
assert.equal(globals.auditVisible.value, false)
handlers[open]({ ...row, can_review_prescription: true }, prescriptionAction)
await handlers.submitAudit('approve') await handlers.submitAudit('approve')
assert.deepEqual(requests, []) assert.deepEqual(requests, [])
@@ -1204,6 +1639,7 @@ for (const filename of [
for (const filename of [ for (const filename of [
'components/EsignPrescriptionPanel.vue', 'components/EsignPrescriptionPanel.vue',
'components/EsignReviewPanel.vue', 'components/EsignReviewPanel.vue',
'components/prescription-slip/index.vue',
'components/tcm-prescription/index.vue', 'components/tcm-prescription/index.vue',
'views/consumer/prescription/index.vue', 'views/consumer/prescription/index.vue',
'views/consumer/prescription/order_list.vue', 'views/consumer/prescription/order_list.vue',
@@ -0,0 +1,60 @@
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 { parse, compileScript, compileTemplate } = require('@vue/compiler-sfc')
const viewDir = path.join(__dirname, '../src/views/consumer/prescription')
const source = fs.readFileSync(path.join(viewDir, 'components/prescription-list-signing-status.ts'), 'utf8')
const { outputText } = ts.transpileModule(source, {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 }
})
const moduleExports = {}
new Function('exports', outputText)(moduleExports)
const { prescriptionListSigningStatus } = moduleExports
test('list separates prescriber and pharmacist signing from audit outcome', () => {
const cases = [
[{ status: 'pending', required: true, awaiting_upload: true }, '上传后签署', 'info'],
[{ status: 'pending' }, '待医师签署', 'warning'],
[{ status: 'authenticating' }, '待医师确认签署', 'warning'],
[{ status: 'signing' }, '医师签署中', 'primary'],
[{ status: 'failed' }, '医师签署未完成', 'danger'],
[{ status: 'uncertain' }, '医师签署待核实', 'warning'],
[{ status: 'signed', can_download: false }, '医师签署待核实', 'warning'],
[{ status: 'signed', can_download: true }, '医师已签署', 'success'],
[{ status: 'signed', can_download: true, awaiting_upload: true, review_required: true }, '医师已签署', 'success'],
[{ status: 'signed', can_download: true, review_required: true }, '待药师签署', 'warning'],
[{ status: 'signed', can_download: true, review_required: true, review_state: 'pending' }, '待药师签署', 'warning'],
[{ status: 'signed', can_download: true, review_required: true, review_state: 'signing' }, '药师签署中', 'primary'],
[{ status: 'signed', can_download: true, review_required: true, review_state: 'verifying' }, '药师验签中', 'primary'],
[{ status: 'signed', can_download: true, review_required: true, review_state: 'failed' }, '药师签署未完成', 'danger'],
[{ status: 'signed', can_download: true, review_required: true, review_state: 'uncertain' }, '药师签署待核实', 'warning'],
[{ status: 'signed', can_download: true, review_required: true, review_state: 'signed' }, '已完成双签', 'success'],
[{ status: 'signed', can_download: true, review_signature_time: 1712345678 }, '已完成双签', 'success'],
[{ status: 'legacy' }, '历史处方', 'info'],
[{ status: 'voided' }, '已作废', 'danger'],
[{ status: 'unavailable' }, '签署状态待核实', 'warning'],
[undefined, '签署状态待核实', 'warning']
]
for (const [esign, label, type] of cases) {
for (const audit_status of [0, 1, 2]) {
assert.deepEqual(prescriptionListSigningStatus({ esign, audit_status }), { label, type })
}
}
assert.deepEqual(prescriptionListSigningStatus({ esign: { status: 'legacy' }, void_status: '1' }),
{ label: '已作废', type: 'danger' })
})
test('issued prescription template renders signing in a dedicated table column', () => {
const filename = path.join(viewDir, 'index.vue')
const { descriptor, errors } = parse(fs.readFileSync(filename, 'utf8'), { filename })
assert.deepEqual(errors, [])
const template = descriptor.template.content
assert.match(template, /label="审核状态"[\s\S]+?listAuditStatusLabel\(row\)[\s\S]+?<\/el-table-column>/)
assert.match(template, /label="签署状态"[\s\S]+?prescriptionListSigningStatus\(row\)\.label[\s\S]+?<\/el-table-column>/)
const script = compileScript(descriptor, { id: 'prescription-list' })
const compiled = compileTemplate({ filename, source: template, id: 'prescription-list', compilerOptions: { bindingMetadata: script.bindings } })
assert.deepEqual(compiled.errors, [])
})
File diff suppressed because one or more lines are too long
+3 -1
View File
@@ -81,7 +81,9 @@ DOCTOR_VERIFY_SSL=true
程序会自动在地址末尾追加 `/adminapi`。它与现有管理端保持相同约定: 程序会自动在地址末尾追加 `/adminapi`。它与现有管理端保持相同约定:
- 登录:`POST /login/account`,请求包含 `account`、`password`、`terminal=1`。 - 工作站使用 `POST /login/account` 登录,请求包含 `account`、`password` 和独立的 `terminal=21`。升级前保存的登录凭据需要重新登录一次。
- 工作站每 60 秒调用 `POST /login/desktopHeartbeat`。每次登录的有效期截至下一个北京时间 05:00,登录和心跳响应中的 `desktop_expires_at` 为 Unix 秒。退出账号或关闭应用时通过 `POST /login/logout` 结束会话。
- Web 后台的「桌面登录记录」支持按日期、账号或姓名调阅。跨北京时间零点的会话按实际重叠时段计入各日。断线超过心跳宽限时,退出时间按服务器最后确认在线的时间记录。
- 鉴权请求头:`token: <登录 token>`,`version: 1.9.4`。 - 鉴权请求头:`token: <登录 token>`,`version: 1.9.4`。
- 响应 envelope:`code=1` 成功、`0` 业务失败、`-1` 登录失效、`10` 需绑定企业微信。 - 响应 envelope:`code=1` 成功、`0` 业务失败、`-1` 登录失效、`10` 需绑定企业微信。
- 权限与数据范围:完全以后端 `/auth.admin/mySelf` 返回为准。 - 权限与数据范围:完全以后端 `/auth.admin/mySelf` 返回为准。
+82 -8
View File
@@ -3,6 +3,7 @@
from __future__ import annotations from __future__ import annotations
import logging import logging
import math
import os import os
import sys import sys
import time import time
@@ -10,7 +11,7 @@ from collections.abc import Mapping, Sequence
from contextlib import suppress from contextlib import suppress
from typing import Any from typing import Any
from PySide6.QtCore import QLibraryInfo, QLocale, QObject, Qt, QTimer, QTranslator from PySide6.QtCore import QLibraryInfo, QLocale, QObject, Qt, QThreadPool, QTimer, QTranslator
from PySide6.QtGui import QGuiApplication, QIcon from PySide6.QtGui import QGuiApplication, QIcon
from PySide6.QtWidgets import ( from PySide6.QtWidgets import (
QApplication, QApplication,
@@ -423,9 +424,18 @@ class ApplicationController(QObject):
self._restore_worker: Any = None self._restore_worker: Any = None
self._shutting_down = False self._shutting_down = False
self._authentication_expiry_in_progress = False self._authentication_expiry_in_progress = False
self._desktop_session: Session | None = None
self._heartbeat_pending = False
self._next_heartbeat_at = 0.0
self._session_workers = QThreadPool(self)
self._session_workers.setMaxThreadCount(2)
self._desktop_timer = QTimer(self)
self._desktop_timer.setSingleShot(True)
self._desktop_timer.setTimerType(Qt.TimerType.PreciseTimer)
self._desktop_timer.timeout.connect(self._check_desktop_session)
application.applicationStateChanged.connect(self._check_desktop_session)
self._rebuild_remote_repository() self._rebuild_remote_repository()
self.app_updater = AppUpdateSession(self) self.app_updater = AppUpdateSession(self)
set_authentication_expired_handler(self._on_authentication_expired)
application.aboutToQuit.connect(self.shutdown) application.aboutToQuit.connect(self.shutdown)
def start(self) -> None: def start(self) -> None:
@@ -529,7 +539,7 @@ class ApplicationController(QObject):
self.remote_repository = repository self.remote_repository = repository
if old is not None and old is not self.current_repository: if old is not None and old is not self.current_repository:
with suppress(Exception): with suppress(Exception):
old.client.close() old.close()
def _begin_session_restore(self) -> None: def _begin_session_restore(self) -> None:
"""Validate a scoped persisted token without racing manual login.""" """Validate a scoped persisted token without racing manual login."""
@@ -655,6 +665,8 @@ class ApplicationController(QObject):
self.login_window.set_session_restore_pending(False) self.login_window.set_session_restore_pending(False)
def _on_login_succeeded(self, payload: dict[str, Any]) -> None: def _on_login_succeeded(self, payload: dict[str, Any]) -> None:
if self._shutting_down:
return
self._cancel_session_restore() self._cancel_session_restore()
session = payload.get("session") session = payload.get("session")
repository = payload.get("repository") repository = payload.get("repository")
@@ -683,13 +695,22 @@ class ApplicationController(QObject):
self.current_repository = repository self.current_repository = repository
self._authentication_expiry_in_progress = False self._authentication_expiry_in_progress = False
self.current_demo_mode = demo_mode self.current_demo_mode = demo_mode
set_authentication_expired_handler(self._on_authentication_expired)
self.shell_window = ShellWindow(repository, payload, session.permissions) self.shell_window = ShellWindow(repository, payload, session.permissions)
self.shell_window.logout_requested.connect(self._logout) self.shell_window.logout_requested.connect(self._logout)
self.shell_window.close_requested.connect(self.request_quit)
self.shell_window.video_requested.connect(self._request_video) self.shell_window.video_requested.connect(self._request_video)
self.shell_window.update_check_requested.connect( self.shell_window.update_check_requested.connect(
lambda: self.app_updater.check(interactive=True) lambda: self.app_updater.check(interactive=True)
) )
self._apply_window_icon(self.shell_window) self._apply_window_icon(self.shell_window)
if isinstance(repository, RemoteDoctorRepository):
self._desktop_session = session
self._heartbeat_pending = False
self._next_heartbeat_at = time.time() + 60
self._check_desktop_session()
if self.shell_window is None:
return
if self.login_window is not None: if self.login_window is not None:
self.login_window.hide() self.login_window.hide()
self.shell_window.show() self.shell_window.show()
@@ -697,6 +718,45 @@ class ApplicationController(QObject):
self.shell_window.activateWindow() self.shell_window.activateWindow()
self.app_updater.schedule(delay_ms=400) self.app_updater.schedule(delay_ms=400)
def _check_desktop_session(self, *_args: Any) -> None:
"""Check wall time even when idle, minimized or returning from sleep."""
session = self._desktop_session
repository = self.current_repository
if session is None or repository is None or self._shutting_down:
return
now = time.time()
remaining = session.desktop_expires_at - now
if remaining <= 0:
self._logout(message="已到北京时间 05:00,请重新登录医生工作站。")
return
# A repeating wall-clock check also catches clock changes and resume on
# platforms where a long monotonic timer pauses during system sleep.
self._desktop_timer.start(max(1, min(1000, math.ceil(remaining * 1000))))
if self._heartbeat_pending or now < self._next_heartbeat_at:
return
self._heartbeat_pending = True
self._next_heartbeat_at = now + 60
def received(deadline: int) -> None:
if self._desktop_session is session:
self._heartbeat_pending = False
session.desktop_expires_at = min(session.desktop_expires_at, deadline)
self._check_desktop_session()
def failed(_error: Exception) -> None:
if self._desktop_session is session:
self._heartbeat_pending = False
self._next_heartbeat_at = time.time() + 15
run_async(
repository.desktop_heartbeat,
session.token,
on_success=received,
on_error=failed,
pool=self._session_workers,
)
def _login_guard_error(self, message: str) -> None: def _login_guard_error(self, message: str) -> None:
if self.login_window is not None: if self.login_window is not None:
self.login_window.error_banner.show_message(message, "warning") self.login_window.error_banner.show_message(message, "warning")
@@ -720,6 +780,9 @@ class ApplicationController(QObject):
def _logout(self, *, message: str = "") -> None: def _logout(self, *, message: str = "") -> None:
"""Clear authenticated resources and return to the login window.""" """Clear authenticated resources and return to the login window."""
self._desktop_session = None
self._desktop_timer.stop()
set_authentication_expired_handler(None)
self._restore_video_preview(activate=False) self._restore_video_preview(activate=False)
calls = tuple(self.video_calls.values()) calls = tuple(self.video_calls.values())
for call in calls: for call in calls:
@@ -729,18 +792,27 @@ class ApplicationController(QObject):
self.video_calls.clear() self.video_calls.clear()
self.video_pending.clear() self.video_pending.clear()
self._pending_im_request = None self._pending_im_request = None
for dialog in self.demo_video_dialogs.values(): for dialog in tuple(self.demo_video_dialogs.values()):
dialog.close() dialog.close()
self.demo_video_dialogs.clear() self.demo_video_dialogs.clear()
if self.current_repository is not None: repository = self.current_repository
if isinstance(repository, RemoteDoctorRepository):
# Stale queued requests retain their old client. Detach locally
# before enabling login and release the remote session off-thread.
token = repository.detach_session()
self.remote_repository = None
self._rebuild_remote_repository()
run_async(repository.close, token, pool=self._session_workers)
elif repository is not None:
with suppress(Exception): with suppress(Exception):
self.current_repository.logout() repository.logout()
self.current_repository = None self.current_repository = None
self._show_login()
if self.shell_window is not None: if self.shell_window is not None:
self.shell_window.close_requested.disconnect(self.request_quit)
self.shell_window.close() self.shell_window.close()
self.shell_window.deleteLater() self.shell_window.deleteLater()
self.shell_window = None self.shell_window = None
self._show_login()
if message and self.login_window is not None: if message and self.login_window is not None:
self.login_window.error_banner.show_message(message, "warning") self.login_window.error_banner.show_message(message, "warning")
@@ -1130,6 +1202,8 @@ class ApplicationController(QObject):
if self._shutting_down: if self._shutting_down:
return return
self._shutting_down = True self._shutting_down = True
self._desktop_session = None
self._desktop_timer.stop()
self._cancel_session_restore() self._cancel_session_restore()
self.app_updater.shutdown() self.app_updater.shutdown()
set_authentication_expired_handler(None) set_authentication_expired_handler(None)
@@ -1141,7 +1215,7 @@ class ApplicationController(QObject):
self._wait_for_video_lifecycle(calls, timeout=1.25) self._wait_for_video_lifecycle(calls, timeout=1.25)
if self.remote_repository is not None: if self.remote_repository is not None:
with suppress(Exception): with suppress(Exception):
self.remote_repository.client.close() self.remote_repository.close()
def _prefer_native_tls_backend() -> None: def _prefer_native_tls_backend() -> None:
+4 -1
View File
@@ -48,7 +48,10 @@ def esign_status(value: Any) -> dict[str, Any]:
or any(not isinstance(result.get(key), bool) for key in ("required", "can_sign", "can_download")) or any(not isinstance(result.get(key), bool) for key in ("required", "can_sign", "can_download"))
or any(not isinstance(result.get(key, False), bool) for key in ( or any(not isinstance(result.get(key, False), bool) for key in (
"can_resume_identity", "can_retry_verify", "doctor_identity_required", "sms_sent", "can_resume_identity", "can_retry_verify", "doctor_identity_required", "sms_sent",
"signing_authorization_required", "signing_authorization_required", "awaiting_upload", "can_submit_for_review", "can_review_prescription",
))
or ("review_submitted_at" in result and (
type(result["review_submitted_at"]) is not int or result["review_submitted_at"] < 0
)) ))
or ("signing_authorization_reason" in result or ("signing_authorization_reason" in result
and result["signing_authorization_reason"] not in _QUICKSIGN_UNAVAILABLE_REASONS) and result["signing_authorization_reason"] not in _QUICKSIGN_UNAVAILABLE_REASONS)
@@ -624,6 +624,8 @@ class Prescription:
audit_time: str = "" audit_time: str = ""
audit_by_name: str = "" audit_by_name: str = ""
audit_remark: str = "" audit_remark: str = ""
review_submitted_at: int | None = None
can_submit_for_review: bool = False
business_prescription_audit_status: int | None = None business_prescription_audit_status: int | None = None
business_prescription_audit_rejected: bool = False business_prescription_audit_rejected: bool = False
business_prescription_audit_remark: str = "" business_prescription_audit_remark: str = ""
@@ -698,6 +700,8 @@ class Prescription:
audit_time=_text(source.get("audit_time")), audit_time=_text(source.get("audit_time")),
audit_by_name=_text(source.get("audit_by_name")), audit_by_name=_text(source.get("audit_by_name")),
audit_remark=_text(source.get("audit_remark")), audit_remark=_text(source.get("audit_remark")),
review_submitted_at=_integer(source.get("review_submitted_at"), None),
can_submit_for_review=source.get("can_submit_for_review") is True,
business_prescription_audit_status=_integer( business_prescription_audit_status=_integer(
source.get("business_prescription_audit_status"), None source.get("business_prescription_audit_status"), None
), ),
@@ -20,6 +20,7 @@ class Session:
is_paw: int = 1 is_paw: int = 1
need_bind_work_wechat: bool = False need_bind_work_wechat: bool = False
metadata: dict[str, Any] = field(default_factory=dict, repr=False) metadata: dict[str, Any] = field(default_factory=dict, repr=False)
desktop_expires_at: int = 0
@property @property
def authenticated(self) -> bool: def authenticated(self) -> bool:
@@ -241,15 +241,18 @@ class ApiClient:
payload: Mapping[str, Any], payload: Mapping[str, Any],
*, *,
timeout: float = 10.0, timeout: float = 10.0,
headers: Mapping[str, str] | None = None,
) -> Any: ) -> Any:
"""Send a short control request without waiting for the ordinary pool.""" """Send a short control request without waiting for the ordinary pool."""
if not self._owns_client:
return self.post(endpoint, payload, timeout=timeout, headers=headers)
try: try:
with httpx.Client(transport=self._stream_transport, verify=self._verify) as client: with httpx.Client(transport=self._stream_transport, verify=self._verify) as client:
response = client.post( response = client.post(
self._endpoint_url(endpoint), self._endpoint_url(endpoint),
json=dict(payload), json=dict(payload),
headers=self._headers(None), headers=self._headers(headers),
timeout=timeout, timeout=timeout,
) )
return self._unwrap(response) return self._unwrap(response)
@@ -128,6 +128,7 @@ DEMO_PERMISSIONS: tuple[str, ...] = (
"doctor.medicine/lists", "doctor.medicine/lists",
) )
_DEMO_MODEL_LABELS = {"qwen": "千问", "openai": "OpenAI", "doubao": "豆包"}
PATIENT_AI_MEDICAL_DISCLAIMER = ( PATIENT_AI_MEDICAL_DISCLAIMER = (
"仅供临床辅助参考,不可替代医生诊断,不得直接用于开方、用药调整或其他医疗决策。" "仅供临床辅助参考,不可替代医生诊断,不得直接用于开方、用药调整或其他医疗决策。"
"系统未对舌像、报告附件或视频画面进行视觉诊断;仅分析已录入、归档或转写的文字及附件元数据。" "系统未对舌像、报告附件或视频画面进行视觉诊断;仅分析已录入、归档或转写的文字及附件元数据。"
@@ -1080,7 +1081,7 @@ class DemoDoctorRepository:
"请由医生结合四诊与最新检验结果复核。" "请由医生结合四诊与最新检验结果复核。"
), ),
"model_key": model_key, "model_key": model_key,
"model_label": "千问" if model_key == "qwen" else "OpenAI", "model_label": _DEMO_MODEL_LABELS.get(model_key, model_key),
"task": task, "task": task,
} }
@@ -1134,15 +1135,15 @@ class DemoDoctorRepository:
self, self,
diagnosis_id: int, diagnosis_id: int,
*, *,
model: Literal["qwen", "openai"] = "qwen", model: Literal["qwen", "openai", "doubao"] = "qwen",
) -> dict[str, Any]: ) -> dict[str, Any]:
"""Return one model's structured offline analysis for the demo case.""" """Return one model's structured offline analysis for the demo case."""
if diagnosis_id <= 0: if diagnosis_id <= 0:
raise ValueError("diagnosis_id must be positive") raise ValueError("diagnosis_id must be positive")
clean_model = str(model).strip().lower() clean_model = str(model).strip().lower()
if clean_model not in {"qwen", "openai"}: if clean_model not in {"qwen", "openai", "doubao"}:
raise ValueError("model must be qwen or openai") raise ValueError("model must be qwen, openai or doubao")
with self._lock: with self._lock:
consultation = self._find_consultation(diagnosis_id) consultation = self._find_consultation(diagnosis_id)
raw = consultation.raw if isinstance(consultation.raw, Mapping) else {} raw = consultation.raw if isinstance(consultation.raw, Mapping) else {}
@@ -1176,9 +1177,9 @@ class DemoDoctorRepository:
"risk_assessment": risk_assessment, "risk_assessment": risk_assessment,
"treatment_advice": treatment, "treatment_advice": treatment,
"model_key": clean_model, "model_key": clean_model,
"model_label": "千问" if clean_model == "qwen" else "OpenAI", "model_label": _DEMO_MODEL_LABELS[clean_model],
"model_name": ( "model_name": (
"qwen3.6-35b-demo" if clean_model == "qwen" else "openai-demo" {"qwen": "qwen3.6-35b-demo", "openai": "openai-demo", "doubao": "doubao-demo"}[clean_model]
), ),
"generated_at": datetime.now().replace(microsecond=0).isoformat(sep=" "), "generated_at": datetime.now().replace(microsecond=0).isoformat(sep=" "),
} }
@@ -1196,15 +1197,15 @@ class DemoDoctorRepository:
self, self,
patient_id: int, patient_id: int,
*, *,
model: Literal["qwen", "openai"], model: Literal["qwen", "openai", "doubao"],
) -> dict[str, Any]: ) -> dict[str, Any]:
"""Append one deterministic demo snapshot while retaining every version.""" """Append one deterministic demo snapshot while retaining every version."""
if patient_id <= 0: if patient_id <= 0:
raise ValueError("patient_id must be positive") raise ValueError("patient_id must be positive")
clean_model = str(model).strip().lower() clean_model = str(model).strip().lower()
if clean_model not in {"qwen", "openai"}: if clean_model not in {"qwen", "openai", "doubao"}:
raise ValueError("model must be qwen or openai") raise ValueError("model must be qwen, openai or doubao")
with self._lock: with self._lock:
consultation = self._find_patient_consultation(patient_id) consultation = self._find_patient_consultation(patient_id)
current = self._patient_ai_reports.setdefault(patient_id, []) current = self._patient_ai_reports.setdefault(patient_id, [])
@@ -4311,6 +4312,7 @@ class DemoDoctorRepository:
latest_by_model: dict[str, dict[str, Any] | None] = { latest_by_model: dict[str, dict[str, Any] | None] = {
"qwen": None, "qwen": None,
"openai": None, "openai": None,
"doubao": None,
} }
for row in reports: for row in reports:
model = str(row.get("model_key") or "").strip().lower() model = str(row.get("model_key") or "").strip().lower()
@@ -4399,8 +4401,8 @@ class DemoDoctorRepository:
"patient_id": patient_id, "patient_id": patient_id,
"diagnosis_id": consultation.id, "diagnosis_id": consultation.id,
"model_key": model, "model_key": model,
"model_name": "gpt-5.6-sol-demo" if is_openai else "qwen3.6-35b-demo", "model_name": {"qwen": "qwen3.6-35b-demo", "openai": "gpt-5.6-sol-demo", "doubao": "doubao-demo"}.get(model, model),
"model_label": "OpenAI" if is_openai else "千问", "model_label": _DEMO_MODEL_LABELS.get(model, model),
"version": version, "version": version,
"report": structured, "report": structured,
"content": json.dumps(structured, ensure_ascii=False), "content": json.dumps(structured, ensure_ascii=False),
+130 -28
View File
@@ -2,6 +2,7 @@
from __future__ import annotations from __future__ import annotations
import logging
import mimetypes import mimetypes
import re import re
import time import time
@@ -12,6 +13,7 @@ from inspect import Parameter, signature
from io import BytesIO from io import BytesIO
from os import PathLike from os import PathLike
from pathlib import Path from pathlib import Path
from threading import RLock
from typing import Any, Final, Literal, Protocol from typing import Any, Final, Literal, Protocol
from uuid import uuid4 from uuid import uuid4
@@ -41,6 +43,7 @@ from .cos_upload import upload_video_to_cos
from .token_store import TokenStore from .token_store import TokenStore
AuditAction = Literal["approve", "reject"] AuditAction = Literal["approve", "reject"]
DESKTOP_TERMINAL = 21
PRESCRIPTION_LIBRARY_PERMISSIONS: Final[dict[str, str]] = { PRESCRIPTION_LIBRARY_PERMISSIONS: Final[dict[str, str]] = {
"create": "wcf.prescription/add", "create": "wcf.prescription/add",
@@ -210,6 +213,7 @@ class DoctorRepository(Protocol):
task: str = "custom", task: str = "custom",
request_id: str | None = None, request_id: str | None = None,
cancelled: Callable[[], bool] | None = None, cancelled: Callable[[], bool] | None = None,
model: str | None = None,
) -> Iterator[dict[str, Any]]: ) -> Iterator[dict[str, Any]]:
"""Yield normalized assistant content and preparation progress events.""" """Yield normalized assistant content and preparation progress events."""
@@ -233,7 +237,7 @@ class DoctorRepository(Protocol):
self, self,
diagnosis_id: int, diagnosis_id: int,
*, *,
model: Literal["qwen", "openai"] = "qwen", model: Literal["qwen", "openai", "doubao"] = "qwen",
) -> dict[str, Any]: ) -> dict[str, Any]:
"""Generate one model's structured reception analysis for a diagnosis.""" """Generate one model's structured reception analysis for a diagnosis."""
@@ -244,7 +248,7 @@ class DoctorRepository(Protocol):
self, self,
patient_id: int, patient_id: int,
*, *,
model: Literal["qwen", "openai"], model: Literal["qwen", "openai", "doubao"],
) -> dict[str, Any]: ) -> dict[str, Any]:
"""Append one model-specific AI diagnosis snapshot for one patient.""" """Append one model-specific AI diagnosis snapshot for one patient."""
@@ -345,6 +349,9 @@ class DoctorRepository(Protocol):
) -> Any: ) -> Any:
"""Approve or reject an issued prescription.""" """Approve or reject an issued prescription."""
def submit_prescription_for_review(self, prescription_id: int) -> dict[str, Any]:
"""Submit the issued prescription for pharmacist review."""
def list_medicines( def list_medicines(
self, self,
*, *,
@@ -870,6 +877,8 @@ class RemoteDoctorRepository:
self.token_store = token_store self.token_store = token_store
self._login_metadata: dict[str, Any] = {} self._login_metadata: dict[str, Any] = {}
self._session: Session | None = None self._session: Session | None = None
self._auth_lock = RLock()
self._closed = False
def login( def login(
self, self,
@@ -885,14 +894,23 @@ class RemoteDoctorRepository:
previously persisted token, so a partial login cannot survive restart. previously persisted token, so a partial login cannot survive restart.
""" """
with self._auth_lock:
if self._closed:
raise RuntimeError("工作站已关闭")
return self._login(account, password, remember_account)
def _login(self, account: str, password: str, remember_account: bool) -> Session:
clean_account = account.strip() clean_account = account.strip()
if not clean_account or not password: if not clean_account or not password:
raise ValueError("account and password are required") raise ValueError("account and password are required")
previous_token = (
self.token_store.load_token(scope=self.client.base_url) if self.token_store else None
)
try: try:
result = _require_mapping( result = _require_mapping(
self.client.post( self.client.post(
"login/account", "login/account",
{"account": clean_account, "password": password, "terminal": 1}, {"account": clean_account, "password": password, "terminal": DESKTOP_TERMINAL},
), ),
"login/account", "login/account",
) )
@@ -902,6 +920,7 @@ class RemoteDoctorRepository:
"login/account returned no token", "login/account returned no token",
data=dict(result), data=dict(result),
) )
self._desktop_deadline(result)
self.client.set_token(token) self.client.set_token(token)
self._login_metadata = dict(result) self._login_metadata = dict(result)
session = self.get_session() session = self.get_session()
@@ -915,46 +934,85 @@ class RemoteDoctorRepository:
token, token,
account=clean_account if remember_account else "", account=clean_account if remember_account else "",
scope=self.client.base_url, scope=self.client.base_url,
desktop_expires_at=session.desktop_expires_at,
) )
except Exception: except Exception:
self._clear_authentication(clear_persisted=True) if self._login_metadata.get("desktop_expires_at"):
self._notify_logout(self.client.token)
self._clear_authentication(previous_token, self.client.token)
raise raise
self._session = session self._session = session
return session return session
def restore_session(self, token: str | None = None) -> Session | None: def restore_session(self, token: str | None = None) -> Session | None:
"""Restore a persisted token and validate it by loading ``mySelf``.""" """Require a live desktop heartbeat before restoring the profile."""
with self._auth_lock:
if self._closed:
return None
return self._restore_session(token)
def _restore_session(self, token: str | None) -> Session | None:
candidate = token candidate = token
persisted_candidate = candidate is None persisted_candidate = candidate is None
if candidate is None and self.token_store is not None: if candidate is None and self.token_store is not None:
candidate = self.token_store.load_token(scope=self.client.base_url) candidate = self.token_store.load_token(scope=self.client.base_url)
if not candidate or not candidate.strip(): if not candidate or not candidate.strip():
self._clear_authentication(clear_persisted=False) self._clear_authentication()
return None return None
clean_token = candidate.strip() clean_token = candidate.strip()
self.client.set_token(clean_token)
self._login_metadata.clear() self._login_metadata.clear()
try: try:
deadline = 0
if persisted_candidate and self.token_store is not None:
deadline = self.token_store.desktop_expiry(clean_token)
# Older releases saved the Web terminal's token here.
if not deadline or time.time() >= deadline:
raise AuthenticationExpiredError("请重新登录医生工作站", code=-1)
confirmed = self.desktop_heartbeat(clean_token)
self._login_metadata["desktop_expires_at"] = min(deadline or confirmed, confirmed)
self.client.set_token(clean_token)
session = self.get_session() session = self.get_session()
if not isinstance(session, Session) or not session.authenticated: if not isinstance(session, Session) or not session.authenticated:
raise ApiProtocolError("persisted token returned an incomplete session") raise ApiProtocolError("persisted token returned an incomplete session")
except AuthenticationExpiredError: except AuthenticationExpiredError:
self._clear_authentication(clear_persisted=persisted_candidate) self._clear_authentication(clean_token if persisted_candidate else None)
raise raise
except ApiTransportError: except ApiTransportError:
# A transient transport failure must not destroy an otherwise valid # A transient transport failure must not destroy an otherwise valid
# persisted credential; it remains available on the next startup. # persisted credential; it remains available on the next startup.
self._clear_authentication(clear_persisted=False) self._clear_authentication()
raise raise
except Exception: except Exception:
# Protocol and business/control-flow failures are deterministic for # Protocol and business/control-flow failures are deterministic for
# this token and must not be replayed on every application launch. # this token and must not be replayed on every application launch.
self._clear_authentication(clear_persisted=persisted_candidate) if self._login_metadata.get("desktop_expires_at"):
self._notify_logout(clean_token)
self._clear_authentication(clean_token if persisted_candidate else None)
raise raise
self._session = session self._session = session
return session return session
@staticmethod
def _desktop_deadline(data: Mapping[str, Any]) -> int:
deadline = _to_int(data.get("desktop_expires_at"))
if deadline <= 0:
raise ApiProtocolError("服务器未返回工作站登录有效期,请联系管理员更新服务。")
if time.time() >= deadline:
raise AuthenticationExpiredError("工作站登录已到期,请重新登录。", code=-1)
return deadline
def desktop_heartbeat(self, token: str) -> int:
"""Refresh presence for the captured token and return its fixed cutoff."""
data = self._desktop_post("login/desktopHeartbeat", token, timeout=8.0)
return self._desktop_deadline(_require_mapping(data, "login/desktopHeartbeat"))
def _desktop_post(self, endpoint: str, token: str, *, timeout: float) -> Any:
# Control requests must still run while business requests occupy the HTTP pool.
post = getattr(self.client, "post_independent", self.client.post)
return post(endpoint, {}, headers={"token": token}, timeout=timeout)
def get_session(self) -> Session: def get_session(self) -> Session:
"""Load the current user, permissions and dynamic menu from ``mySelf``.""" """Load the current user, permissions and dynamic menu from ``mySelf``."""
@@ -976,6 +1034,7 @@ class RemoteDoctorRepository:
menu=menu, menu=menu,
is_paw=is_paw, is_paw=is_paw,
need_bind_work_wechat=need_bind, need_bind_work_wechat=need_bind,
desktop_expires_at=_to_int(self._login_metadata.get("desktop_expires_at")),
metadata={ metadata={
key: value key: value
for key, value in self._login_metadata.items() for key, value in self._login_metadata.items()
@@ -991,26 +1050,53 @@ class RemoteDoctorRepository:
return self._session.user if self._session is not None else self.get_session().user return self._session.user if self._session is not None else self.get_session().user
def logout(self, *, forget_account: bool = False) -> None: def logout(self, *, forget_account: bool = False) -> None:
"""Clear local authentication without implicitly retrying a remote write.""" """Clear the local session and notify the server once."""
self.client.clear_token() self._notify_logout(self.detach_session(forget_account=forget_account))
self._login_metadata.clear()
self._session = None def detach_session(self, *, forget_account: bool = False) -> str:
if self.token_store is not None: """Remove credentials immediately and capture the verified desktop token."""
if forget_account:
with self._auth_lock:
token = self.client.token
verified_token = token if self._login_metadata.get("desktop_expires_at") else ""
self._clear_authentication(token)
if forget_account and self.token_store is not None:
self.token_store.clear() self.token_store.clear()
else: return verified_token
self.token_store.clear_token()
def _clear_authentication(self, *, clear_persisted: bool) -> None: def _notify_logout(self, token: str) -> None:
if token:
try:
self._desktop_post("login/logout", token, timeout=3.0)
except Exception as error:
# Lost connectivity is covered by the server's heartbeat grace.
logging.getLogger(__name__).info(
"desktop logout response unavailable (%s)", type(error).__name__
)
def close(self, detached_token: str = "") -> None:
"""Finish an in-flight sign-in, revoke its token and close the transport."""
with self._auth_lock:
self._closed = True
token = detached_token or self.detach_session()
try:
self._notify_logout(token)
finally:
self.client.close()
def _clear_authentication(self, *owned_tokens: str | None) -> None:
"""Reset partial authentication state without masking its root error.""" """Reset partial authentication state without masking its root error."""
self.client.clear_token() self.client.clear_token()
self._login_metadata.clear() self._login_metadata.clear()
self._session = None self._session = None
if clear_persisted and self.token_store is not None: if any(owned_tokens) and self.token_store is not None:
with suppress(Exception): with suppress(Exception):
self.token_store.clear_token() saved_token = self.token_store.load_token(scope=self.client.base_url)
if saved_token and saved_token in owned_tokens:
self.token_store.clear_token()
def list_appointments( def list_appointments(
self, *, page_no: int = 1, page_size: int = 20, **filters: Any self, *, page_no: int = 1, page_size: int = 20, **filters: Any
@@ -1468,6 +1554,7 @@ class RemoteDoctorRepository:
task: str = "custom", task: str = "custom",
request_id: str | None = None, request_id: str | None = None,
cancelled: Callable[[], bool] | None = None, cancelled: Callable[[], bool] | None = None,
model: str | None = None,
) -> Iterator[dict[str, Any]]: ) -> Iterator[dict[str, Any]]:
"""Stream a diagnosis answer; use the legacy route only when streaming is absent.""" """Stream a diagnosis answer; use the legacy route only when streaming is absent."""
@@ -1476,6 +1563,11 @@ class RemoteDoctorRepository:
"id": diagnosis_id, "prompt": clean_prompt, "task": clean_task, "id": diagnosis_id, "prompt": clean_prompt, "task": clean_task,
"request_id": request_id or str(uuid4()), "request_id": request_id or str(uuid4()),
} }
if model is not None:
# 省略时由服务端按任务默认模型(千问)回答。
if model not in {"qwen", "openai", "doubao"}:
raise ValueError("model must be qwen, openai or doubao")
body["model"] = model
received_event = False received_event = False
received_done = False received_done = False
try: try:
@@ -1562,7 +1654,7 @@ class RemoteDoctorRepository:
def analyze_tongue_screenshot(self, diagnosis_id: int, content: bytes, *, request_id: str, model: str = "qwen") -> dict[str, Any]: def analyze_tongue_screenshot(self, diagnosis_id: int, content: bytes, *, request_id: str, model: str = "qwen") -> dict[str, Any]:
"""Analyze a temporary video image without adding it to the clinical record.""" """Analyze a temporary video image without adding it to the clinical record."""
if (not isinstance(model, str) or model not in {"qwen", "openai"} if (not isinstance(model, str) or model not in {"qwen", "openai", "doubao"}
or isinstance(diagnosis_id, bool) or not isinstance(diagnosis_id, int) or diagnosis_id <= 0 or isinstance(diagnosis_id, bool) or not isinstance(diagnosis_id, int) or diagnosis_id <= 0
or not isinstance(content, bytes) or not 4 <= len(content) <= 10 * 1024 * 1024 or not isinstance(content, bytes) or not 4 <= len(content) <= 10 * 1024 * 1024
or not content.startswith(b"\xff\xd8") or not content.startswith(b"\xff\xd8")
@@ -1601,15 +1693,15 @@ class RemoteDoctorRepository:
self, self,
diagnosis_id: int, diagnosis_id: int,
*, *,
model: Literal["qwen", "openai"] = "qwen", model: Literal["qwen", "openai", "doubao"] = "qwen",
) -> dict[str, Any]: ) -> dict[str, Any]:
"""Generate one model's structured analysis via the first-party API.""" """Generate one model's structured analysis via the first-party API."""
if diagnosis_id <= 0: if diagnosis_id <= 0:
raise ValueError("diagnosis_id must be positive") raise ValueError("diagnosis_id must be positive")
clean_model = str(model).strip().lower() clean_model = str(model).strip().lower()
if clean_model not in {"qwen", "openai"}: if clean_model not in {"qwen", "openai", "doubao"}:
raise ValueError("model must be qwen or openai") raise ValueError("model must be qwen, openai or doubao")
payload = _client_request( payload = _client_request(
self.client, self.client,
"post", "post",
@@ -1637,15 +1729,15 @@ class RemoteDoctorRepository:
self, self,
patient_id: int, patient_id: int,
*, *,
model: Literal["qwen", "openai"], model: Literal["qwen", "openai", "doubao"],
) -> dict[str, Any]: ) -> dict[str, Any]:
"""Append one patient snapshot; the desktop never sends provider secrets.""" """Append one patient snapshot; the desktop never sends provider secrets."""
if patient_id <= 0: if patient_id <= 0:
raise ValueError("patient_id must be positive") raise ValueError("patient_id must be positive")
clean_model = str(model).strip().lower() clean_model = str(model).strip().lower()
if clean_model not in {"qwen", "openai"}: if clean_model not in {"qwen", "openai", "doubao"}:
raise ValueError("model must be qwen or openai") raise ValueError("model must be qwen, openai or doubao")
payload = _client_request( payload = _client_request(
self.client, self.client,
"post", "post",
@@ -1952,6 +2044,16 @@ class RemoteDoctorRepository:
{"id": prescription_id, "action": action, "remark": remark.strip()}, {"id": prescription_id, "action": action, "remark": remark.strip()},
) )
def submit_prescription_for_review(self, prescription_id: int) -> dict[str, Any]:
if prescription_id <= 0:
raise ValueError("prescription id is required")
endpoint = "tcm.prescription/submitForReview"
result = _require_mapping(self.client.post(endpoint, {"id": prescription_id}), endpoint)
submitted_at = result.get("review_submitted_at")
if type(submitted_at) is not int or submitted_at <= 0 or result.get("can_submit_for_review") is not False:
raise ApiProtocolError("处方上传结果格式不正确")
return dict(result)
def void_prescription(self, prescription_id: int) -> Any: def void_prescription(self, prescription_id: int) -> Any:
"""Void a diagnosis-context prescription when no business order blocks it.""" """Void a diagnosis-context prescription when no business order blocks it."""
@@ -103,6 +103,7 @@ class TokenStore:
*, *,
account: str | None = None, account: str | None = None,
scope: str | None = None, scope: str | None = None,
desktop_expires_at: int = 0,
) -> None: ) -> None:
"""Persist a token plus optional account and API-scope metadata. """Persist a token plus optional account and API-scope metadata.
@@ -117,6 +118,12 @@ class TokenStore:
self.save_account(account) self.save_account(account)
return return
data = self._read_file() data = self._read_file()
data.pop("desktop_session", None)
if desktop_expires_at > 0:
data["desktop_session"] = {
"token_sha256": hashlib.sha256(cleaned.encode()).hexdigest(),
"expires_at": desktop_expires_at,
}
if account is not None: if account is not None:
account_value = account.strip() account_value = account.strip()
previous_account = str(data.get("account") or "").strip() previous_account = str(data.get("account") or "").strip()
@@ -151,6 +158,18 @@ class TokenStore:
data["token"] = cleaned data["token"] = cleaned
self._write_file(data) self._write_file(data)
def desktop_expiry(self, token: str) -> int:
"""Read the deadline only for the matching workstation-issued token."""
marker = self._read_file().get("desktop_session")
if not isinstance(marker, dict):
return 0
fingerprint = hashlib.sha256(token.encode()).hexdigest()
expiry = marker.get("expires_at")
if marker.get("token_sha256") == fingerprint and type(expiry) is int and expiry > 0:
return expiry
return 0
def clear_token(self) -> None: def clear_token(self) -> None:
"""Delete the token while retaining remembered login credentials.""" """Delete the token while retaining remembered login credentials."""
@@ -161,6 +180,7 @@ class TokenStore:
self._uses_keyring = False self._uses_keyring = False
data = self._read_file() data = self._read_file()
data.pop("token", None) data.pop("token", None)
data.pop("desktop_session", None)
if not data.get("account"): if not data.get("account"):
data.pop("scope", None) data.pop("scope", None)
self._write_file(data) self._write_file(data)
@@ -457,14 +477,14 @@ class TokenStore:
# Explicit allow-list guarantees accidental password-like fields are ignored. # Explicit allow-list guarantees accidental password-like fields are ignored.
return { return {
key: value[key] key: value[key]
for key in ("token", "account", "scope", "credential") for key in ("token", "account", "scope", "credential", "desktop_session")
if key in value if key in value
} }
def _write_file(self, data: dict[str, Any]) -> None: def _write_file(self, data: dict[str, Any]) -> None:
safe = { safe = {
key: data[key] key: data[key]
for key in ("token", "account", "scope", "credential") for key in ("token", "account", "scope", "credential", "desktop_session")
if data.get(key) if data.get(key)
} }
if not safe: if not safe:
@@ -116,6 +116,7 @@ from .prescription_ai import (
can_use_diagnosis_ai_assistant, can_use_diagnosis_ai_assistant,
diagnosis_ai_task, diagnosis_ai_task,
) )
from .prescription_esign import resume_saved_prescription, saved_prescription_message
AI_CONSULT_QSS = clinical_stylesheet(""" AI_CONSULT_QSS = clinical_stylesheet("""
QDialog#AiConsultDialog { QDialog#AiConsultDialog {
@@ -1222,7 +1223,7 @@ def _unwrap_analysis(payload: Any) -> dict[str, Any]:
current: Mapping[str, Any] = payload current: Mapping[str, Any] = payload
latest = current.get("latest_by_model") latest = current.get("latest_by_model")
if isinstance(latest, Mapping): if isinstance(latest, Mapping):
for key in ("qwen", "openai"): for key in ("qwen", "openai", "doubao"):
row = latest.get(key) row = latest.get(key)
if isinstance(row, Mapping): if isinstance(row, Mapping):
current = row current = row
@@ -7085,7 +7086,7 @@ class AiConsultDialog(QDialog):
): ):
status.set_payload("AI处方草稿缺少诊断或药材,已停止开方。") status.set_payload("AI处方草稿缺少诊断或药材,已停止开方。")
return return
status.set_payload("AI 已生成处方草稿,请逐味复核、修改并完成医师签名。") status.set_payload("AI 已生成处方草稿,请逐味复核并保存。")
self._open_prescription_editor_from_chat( self._open_prescription_editor_from_chat(
generation, generation,
diagnosis_id, diagnosis_id,
@@ -7177,45 +7178,46 @@ class AiConsultDialog(QDialog):
} }
seed.update({key: deepcopy(value) for key, value in draft.items() if key in allowed}) seed.update({key: deepcopy(value) for key, value in draft.items() if key in allowed})
seed["ai_assisted"] = True seed["ai_assisted"] = True
linked_fields = {
"diagnosis_id": diagnosis_id,
"appointment_id": seed["appointment_id"],
"case_record": deepcopy(seed["case_record"]),
"patient_id": seed["patient_id"],
"phone": seed["phone"],
}
def save_prescription(payload: dict[str, Any]) -> Any:
return invoke(
self.repository, "create_prescription", prescription=deepcopy(payload | linked_fields)
)
dialog = PrescriptionEditorDialog( dialog = PrescriptionEditorDialog(
self.repository, self.repository,
seed, seed,
mode="add", mode="add",
current_user=self._current_user(), current_user=self._current_user(),
permissions=self.permissions, permissions=self.permissions,
save_draft=save_prescription,
parent=self, parent=self,
) )
if dialog.exec() != QDialog.DialogCode.Accepted: if dialog.exec() != QDialog.DialogCode.Accepted:
status.set_payload("已取消开方,未保存或提交任何处方。") status.set_payload("已取消开方,未保存或提交任何处方。")
return return
saved = getattr(dialog, "saved_draft", None)
if saved is not None:
self._prescription_action_created(generation, diagnosis_id, status, saved)
return
status.set_payload("正在保存处方。")
payload = dialog.payload() payload = dialog.payload()
payload.update(
{
"diagnosis_id": diagnosis_id,
"appointment_id": seed["appointment_id"],
"case_record": deepcopy(seed["case_record"]),
"patient_id": seed["patient_id"],
"phone": seed["phone"],
}
)
status.set_payload("处方已填写,正在提交审核。")
frozen_payload = deepcopy(payload)
run_async( run_async(
lambda: invoke( lambda: save_prescription(payload),
self.repository, on_success=lambda result: self._prescription_action_created(generation, diagnosis_id, status, result),
"create_prescription",
prescription=frozen_payload,
),
on_success=lambda _result: self._prescription_action_created(
generation,
diagnosis_id,
status,
),
on_error=lambda error: self._prescription_action_error( on_error=lambda error: self._prescription_action_error(
generation, generation,
status, status,
error, error,
prefix="处方提交失败", prefix="处方保存失败",
), ),
) )
@@ -7224,11 +7226,14 @@ class AiConsultDialog(QDialog):
generation: int, generation: int,
diagnosis_id: int, diagnosis_id: int,
status: _ChatBubble, status: _ChatBubble,
prescription: Any,
) -> None: ) -> None:
if generation != self._generation or diagnosis_id != self.diagnosis_id: if generation != self._generation or diagnosis_id != self.diagnosis_id:
return return
status.set_payload("处方已开具并提交审核。") message, _ = saved_prescription_message(prescription, "处方已保存。")
status.set_payload(message)
status.set_time_text(_join_meta("系统", datetime.now().strftime("%H:%M"))) status.set_time_text(_join_meta("系统", datetime.now().strftime("%H:%M")))
resume_saved_prescription(self.repository, prescription, self)
self._reload_prescriptions(generation, diagnosis_id) self._reload_prescriptions(generation, diagnosis_id)
def _prescription_action_error( def _prescription_action_error(
@@ -3771,6 +3771,8 @@ class DiagnosisDialog(QDialog):
if reload_key == "prescription": if reload_key == "prescription":
text, kind = saved_prescription_message(result, text) text, kind = saved_prescription_message(result, text)
self._show_message(text, kind) self._show_message(text, kind)
if reload_key == "prescription":
resume_saved_prescription(self.repository, result, self)
self._loaded_tabs.discard(reload_key) self._loaded_tabs.discard(reload_key)
if reload_key == "chat": if reload_key == "chat":
QTimer.singleShot( QTimer.singleShot(
@@ -3783,8 +3785,6 @@ class DiagnosisDialog(QDialog):
) )
else: else:
self._ensure_tab_loaded(reload_key, force=True) self._ensure_tab_loaded(reload_key, force=True)
if reload_key == "prescription":
resume_saved_prescription(self.repository, result, self)
def _order_offset_changed(self, value: int) -> None: def _order_offset_changed(self, value: int) -> None:
self.order_offset_preview.setText(f"第 1 笔实单计为{_visit_slot_label(value)}") self.order_offset_preview.setText(f"第 1 笔实单计为{_visit_slot_label(value)}")
@@ -96,6 +96,7 @@ from PySide6.QtWidgets import (
QVBoxLayout, QVBoxLayout,
QWidget, QWidget,
) )
from shiboken6 import isValid
from ...core.esign import esign_config, esign_status from ...core.esign import esign_config, esign_status
from .. import icons from .. import icons
@@ -118,8 +119,15 @@ from ..widgets import (
) )
from .diagnosis import DiagnosisDialog as _StructuredDiagnosisDialog from .diagnosis import DiagnosisDialog as _StructuredDiagnosisDialog
from .prescription_esign import ( from .prescription_esign import (
PRESCRIPTION_UPLOAD_BEFORE_SIGNING_PROMPT,
PrescriptionEsignDialog, PrescriptionEsignDialog,
SigningLogDialog,
awaiting_prescription_upload,
can_upload_prescription,
open_saved_original, open_saved_original,
review_signature_time,
review_signing_status,
review_submission_time,
save_signed_original, save_signed_original,
signature_state, signature_state,
signature_time_text, signature_time_text,
@@ -1528,61 +1536,108 @@ class AdminDosageInput(SelectComboBox):
return self._maximum return self._maximum
class MultiSelectComboBox(QComboBox): class MultiSelectComboBox(SelectComboBox):
"""Compact fixed-option multi-select matching Element Plus ``multiple`` selects.""" """A checklist popup with a read-only summary of its checked options."""
def __init__(self, options: Sequence[str], parent: QWidget | None = None) -> None: def __init__(self, options: Sequence[str], parent: QWidget | None = None) -> None:
super().__init__(parent) super().__init__(parent)
self.setEditable(True) self.setEditable(True)
self.setCursor(Qt.CursorShape.PointingHandCursor) self.setCompleter(None)
if self.lineEdit() is not None: field = self.lineEdit()
self.lineEdit().setReadOnly(True) field.setReadOnly(True)
self.lineEdit().setPlaceholderText("请选择忌口内容(可多选)") field.setPlaceholderText("请选择忌口内容(可多选)")
self.lineEdit().setCursor(Qt.CursorShape.PointingHandCursor) field.setCursor(Qt.CursorShape.PointingHandCursor)
self._options = QStandardItemModel(self)
for option in options: for option in options:
self.addItem(option, option) item = QStandardItem(option)
self.setItemData( item.setCheckable(True)
self.count() - 1, Qt.CheckState.Unchecked, Qt.ItemDataRole.CheckStateRole item.setEditable(False)
) self._options.appendRow(item)
self.view().pressed.connect(self._toggle_item) self.setModel(self._options)
# QComboBox applies the clicked item's text after ``pressed``. Refresh self._pressed_item = QModelIndex()
# on the next event-loop tick so the field always shows every checked self.view().installEventFilter(self)
# value instead of only the last clicked one. self.view().viewport().installEventFilter(self)
self.currentIndexChanged.connect(lambda _index: QTimer.singleShot(0, self._refresh_text)) field.installEventFilter(self)
self.currentIndexChanged.connect(self._refresh_text)
self._refresh_text() self._refresh_text()
def _toggle_item(self, index: Any) -> None: def eventFilter(self, watched: QObject, event: QEvent) -> bool: # noqa: N802 - Qt virtual
row = index.row() view = self.view()
checked = self.itemData(row, Qt.ItemDataRole.CheckStateRole) == Qt.CheckState.Checked event_type = event.type()
self.setItemData( if (
row, watched is view.viewport()
Qt.CheckState.Unchecked if checked else Qt.CheckState.Checked, and isinstance(event, QMouseEvent)
Qt.ItemDataRole.CheckStateRole, and event.button() == Qt.MouseButton.LeftButton
):
index = view.indexAt(event.position().toPoint())
if event_type in (QEvent.Type.MouseButtonPress, QEvent.Type.MouseButtonDblClick):
self._pressed_item = index
view.setCurrentIndex(index)
return True
if event_type == QEvent.Type.MouseButtonRelease:
# Consume the release before QComboBox can commit one row and close the popup.
if index == self._pressed_item:
self._toggle_item(index)
self._pressed_item = QModelIndex()
return True
if (
watched is view
and event_type == QEvent.Type.KeyPress
and event.key() in (Qt.Key.Key_Space, Qt.Key.Key_Return, Qt.Key.Key_Enter)
):
if not event.isAutoRepeat():
self._toggle_item(view.currentIndex())
return True
if (
watched is self.lineEdit()
and event_type == QEvent.Type.MouseButtonPress
and event.button() == Qt.MouseButton.LeftButton
):
self.setFocus(Qt.FocusReason.MouseFocusReason)
self.showPopup()
return True
return super().eventFilter(watched, event)
def keyPressEvent(self, event: QKeyEvent) -> None: # noqa: N802 - Qt virtual
if event.key() in (Qt.Key.Key_Space, Qt.Key.Key_Down, Qt.Key.Key_Up):
self.showPopup()
return
super().keyPressEvent(event)
def wheelEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual
event.ignore()
def _toggle_item(self, index: QModelIndex) -> None:
item = self._options.itemFromIndex(index)
if item is None:
return
item.setCheckState(
Qt.CheckState.Unchecked
if item.checkState() == Qt.CheckState.Checked
else Qt.CheckState.Checked
) )
self._refresh_text() self._refresh_text()
def set_values(self, values: Iterable[Any]) -> None: def set_values(self, values: Iterable[Any]) -> None:
selected = {str(value).strip() for value in values if str(value).strip()} selected = {str(value).strip() for value in values if str(value).strip()}
for row in range(self.count()): for row in range(self._options.rowCount()):
self.setItemData( item = self._options.item(row)
row, item.setCheckState(
Qt.CheckState.Checked Qt.CheckState.Checked
if str(self.itemData(row)).strip() in selected if item.text().strip() in selected
else Qt.CheckState.Unchecked, else Qt.CheckState.Unchecked
Qt.ItemDataRole.CheckStateRole,
) )
self._refresh_text() self._refresh_text()
def values(self) -> list[str]: def values(self) -> list[str]:
return [ return [
str(self.itemData(row)) item.text()
for row in range(self.count()) for row in range(self._options.rowCount())
if self.itemData(row, Qt.ItemDataRole.CheckStateRole) == Qt.CheckState.Checked if (item := self._options.item(row)).checkState() == Qt.CheckState.Checked
] ]
def _refresh_text(self) -> None: def _refresh_text(self) -> None:
if self.lineEdit() is not None: self.lineEdit().setText("、".join(self.values()))
self.lineEdit().setText("、".join(self.values()))
_MEDICINE_NAME_ROLE = Qt.ItemDataRole.UserRole + 1 _MEDICINE_NAME_ROLE = Qt.ItemDataRole.UserRole + 1
@@ -3888,8 +3943,13 @@ class PrescriptionEditorDialog(QDialog):
banner.clear() banner.clear()
messages: list[str] = [] messages: list[str] = []
if self.mode == "edit": if self.mode == "edit":
uses_upload = review_submission_time(self._source, signature_state(self._source)) is not None
review_hint = (
"保存修改后,请重新上传处方。须电子签署的处方在医生签署后进入药师审核。"
if uses_upload else "保存修改后,该处方将重新进入「待审核」,需审核人员再次通过后方可生效。"
)
self.reaudit_banner.show_message( self.reaudit_banner.show_message(
"保存修改后,该处方将重新进入「待审核」,需审核人员再次通过后方可生效。", review_hint,
"info", "info",
) )
messages.append(self.reaudit_banner.label.text()) messages.append(self.reaudit_banner.label.text())
@@ -3903,9 +3963,9 @@ class PrescriptionEditorDialog(QDialog):
rejected = _int(self._source.get("audit_status"), -1) == 2 rejected = _int(self._source.get("audit_status"), -1) == 2
if rejected: if rejected:
remark = str(self._source.get("audit_remark") or "").strip() remark = str(self._source.get("audit_remark") or "").strip()
text = "当前消费者处方为「已驳回」\n保存修改后将清除驳回并变为「待审核」。" text = "当前消费者处方为「已驳回」\n保存修改后将清除驳回。"
if remark: if remark:
text += f"上次意见:{remark}" text += f"\n上次意见:{remark}"
self.consumer_reject_banner.show_message(text, "danger") self.consumer_reject_banner.show_message(text, "danger")
messages.append(self.consumer_reject_banner.label.text()) messages.append(self.consumer_reject_banner.label.text())
if _bool(self._source.get("business_prescription_audit_rejected")) and _int( if _bool(self._source.get("business_prescription_audit_rejected")) and _int(
@@ -3922,11 +3982,11 @@ class PrescriptionEditorDialog(QDialog):
self.business_reject_banner.show_message(text, "warning") self.business_reject_banner.show_message(text, "warning")
messages.append(self.business_reject_banner.label.text()) messages.append(self.business_reject_banner.label.text())
if voided and rejected: if voided and rejected:
revive = "当前处方已作废且已驳回。保存后将取消作废、清除驳回,并重新进入待审核。" revive = "当前处方已作废且已驳回。保存后将取消作废、清除驳回。"
elif voided: elif voided:
revive = "当前为已作废处方。保存后将取消作废,并重新进入待审核。" revive = "当前为已作废处方。保存后将取消作废。"
elif rejected: elif rejected:
revive = "当前为已驳回处方。保存后将清除驳回,并重新进入待审核。" revive = "当前为已驳回处方。保存后将清除驳回。"
else: else:
revive = "" revive = ""
if revive: if revive:
@@ -4475,10 +4535,11 @@ class PatchPatientDialog(QDialog):
class AuditPrescriptionDialog(QDialog): class AuditPrescriptionDialog(QDialog):
"""Approve or reject a pending prescription with the canonical DTO.""" """Approve or reject a pending prescription with the canonical DTO."""
def __init__(self, prescription: Any, parent: QWidget | None = None) -> None: def __init__(self, prescription: Any, parent: QWidget | None = None, *, allow_approval: bool = True) -> None:
super().__init__(parent) super().__init__(parent)
_apply_prescription_dialog_style(self) _apply_prescription_dialog_style(self)
self.prescription_id = _int(first_value(prescription, "id", "prescription_id")) self.prescription_id = _int(first_value(prescription, "id", "prescription_id"))
self._allow_approval = allow_approval
self.action = "" self.action = ""
self.setWindowTitle("处方审核") self.setWindowTitle("处方审核")
self.resize(500, 300) self.resize(500, 300)
@@ -4490,10 +4551,13 @@ class AuditPrescriptionDialog(QDialog):
root.addWidget(self.remark) root.addWidget(self.remark)
self.banner = MessageBanner() self.banner = MessageBanner()
root.addWidget(self.banner) root.addWidget(self.banner)
if not allow_approval:
self.banner.show_message("请先在管理后台完成药师审核签署,再提交审核通过。", "info")
buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Cancel) buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Cancel)
buttons.rejected.connect(self.reject) buttons.rejected.connect(self.reject)
approve = buttons.addButton("审核通过", QDialogButtonBox.ButtonRole.AcceptRole) approve = buttons.addButton("审核通过", QDialogButtonBox.ButtonRole.AcceptRole)
approve.setProperty("variant", "primary") approve.setProperty("variant", "primary")
approve.setEnabled(allow_approval)
approve.clicked.connect(lambda: self._choose("approve")) approve.clicked.connect(lambda: self._choose("approve"))
reject = buttons.addButton("驳回处方", QDialogButtonBox.ButtonRole.DestructiveRole) reject = buttons.addButton("驳回处方", QDialogButtonBox.ButtonRole.DestructiveRole)
reject.setProperty("variant", "danger") reject.setProperty("variant", "danger")
@@ -4501,6 +4565,8 @@ class AuditPrescriptionDialog(QDialog):
root.addWidget(buttons) root.addWidget(buttons)
def _choose(self, action: str) -> None: def _choose(self, action: str) -> None:
if action == "approve" and not self._allow_approval:
return
if action == "reject" and not self.remark.toPlainText().strip(): if action == "reject" and not self.remark.toPlainText().strip():
self.banner.show_message("驳回时请填写审核意见。", "warning") self.banner.show_message("驳回时请填写审核意见。", "warning")
return return
@@ -4770,21 +4836,24 @@ h1 {{ text-align:center; font-size:20px; font-weight:600; margin:0;
_SLIP_HOSPITAL_TITLE = "成都双流甄养堂互联网医院 处方笺" _SLIP_HOSPITAL_TITLE = "成都双流甄养堂互联网医院 处方笺"
_SLIP_COMPANY_LINE = "成都双流甄养堂互联网医院有限公司 联系方式:4001667339" _SLIP_COMPANY_LINE = "成都双流甄养堂互联网医院有限公司 联系方式:4001667339"
_SLIP_ADDRESS_LINE = "地址:四川省成都市双流区黄甲街道黄龙大道二段280号" _SLIP_ADDRESS_LINE = "地址:四川省成都市双流区黄甲街道黄龙大道二段280号"
_SLIP_SIGNATURE_BOUNDS = QSize(64, 20)
def _prescription_signature_size(signature: str, *, is_internal: bool) -> str: def _prescription_signature_size(signature: str, *, require_png: bool = False) -> str:
bounds = QSize(78, 36) if is_internal else QSize(76, 24) bounds = _SLIP_SIGNATURE_BOUNDS
if require_png and not signature.startswith("data:image/png;base64,iVBORw0KGgo"):
return ""
if signature.startswith("data:image/") and "," in signature: if signature.startswith("data:image/") and "," in signature:
try: try:
image = QImage.fromData(base64.b64decode(signature.split(",", 1)[1], validate=True)) image = QImage.fromData(base64.b64decode(signature.split(",", 1)[1], validate=True))
except ValueError: except ValueError:
return f'height="{bounds.height()}"' return "" if require_png else f'height="{bounds.height()}"'
if not image.isNull(): if not image.isNull():
size = image.size() size = image.size()
if size.width() > bounds.width() or size.height() > bounds.height(): if size.width() > bounds.width() or size.height() > bounds.height():
size = size.scaled(bounds, Qt.AspectRatioMode.KeepAspectRatio) size = size.scaled(bounds, Qt.AspectRatioMode.KeepAspectRatio)
return f'width="{max(1, size.width())}" height="{max(1, size.height())}"' return f'width="{max(1, size.width())}" height="{max(1, size.height())}"'
return f'height="{bounds.height()}"' return "" if require_png else f'height="{bounds.height()}"'
def render_prescription_html( def render_prescription_html(
@@ -5018,12 +5087,17 @@ def render_prescription_html(
days_text = f"{source.get('dose_count')}剂" days_text = f"{source.get('dose_count')}剂"
else: else:
days_text = "—" days_text = "—"
signing = signature_state(prescription)
doctor_name = source.get("doctor_name")
signer = signing.get("doctor_signer_name")
if signing.get("status") in ("signed", "voided") and isinstance(signer, str) and signer.strip():
doctor_name = signer.strip()
signature = str(source.get("doctor_signature") or "").strip() signature = str(source.get("doctor_signature") or "").strip()
signature_html = ( signature_html = (
f'<img class="signature" src="{html.escape(signature, quote=True)}" ' f'<img class="signature" src="{html.escape(signature, quote=True)}" '
f'{_prescription_signature_size(signature, is_internal=is_internal)} alt="医师签名" />' f'{_prescription_signature_size(signature)} alt="医师签名" />'
if signature if signature
else f'<span class="doctor-name">{esc(source.get("doctor_name"))}</span>' else f'<span class="doctor-name">{esc(doctor_name)}</span>'
) )
herb_html = herb_group(main, "主方", "main") + herb_group(aux, aux_title, "aux") herb_html = herb_group(main, "主方", "main") + herb_group(aux, aux_title, "aux")
@@ -5087,6 +5161,24 @@ def render_prescription_html(
f'<td><span class="meta-key">天数:</span> {html.escape(days_text)}</td>' f'<td><span class="meta-key">天数:</span> {html.escape(days_text)}</td>'
) )
hospital_colspan = 2 hospital_colspan = 2
review_row = ""
reviewer = signing.get("review_signer_name")
if review_signature_time(signing) and isinstance(reviewer, str) and reviewer.strip():
seal = signing.get("review_signature")
seal_size = (
_prescription_signature_size(seal, require_png=True)
if isinstance(seal, str) else ""
)
reviewer_html = esc(reviewer)
if seal_size:
reviewer_html = (
f'<img class="signature" src="{html.escape(seal, quote=True)}" '
f'{seal_size} alt="{esc(reviewer)}" />'
)
review_row = (
f'<tr><td colspan="{hospital_colspan}">'
f'<span class="doctor-title">审核药师</span>&nbsp;{reviewer_html}</td></tr>'
)
family = html.escape(_ensure_slip_fonts()) family = html.escape(_ensure_slip_fonts())
title_html = ( title_html = (
@@ -5166,7 +5258,8 @@ body {{ margin:0; padding:{body_padding}; background:{body_background}; color:#1
.pharmacy-key {{ color:#1f1f1f; }} .pharmacy-key {{ color:#1f1f1f; }}
.doctor-title {{ margin-right:8px; color:#6b7280; }} .doctor-title {{ margin-right:8px; color:#6b7280; }}
.doctor-name {{ font-size:13px; }} .doctor-name {{ font-size:13px; }}
.signature {{ max-width:76px; max-height:24px; vertical-align:middle; }} .signature {{ max-width:{_SLIP_SIGNATURE_BOUNDS.width()}px; max-height:{_SLIP_SIGNATURE_BOUNDS.height()}px;
vertical-align:middle; }}
.meta-key {{ color:#6b7280; margin-right:6px; }} .meta-key {{ color:#6b7280; margin-right:6px; }}
.hospital {{ height:auto; vertical-align:top; padding:10px 12px; font-size:12px; .hospital {{ height:auto; vertical-align:top; padding:10px 12px; font-size:12px;
color:#6b7280; line-height:1.65; }} color:#6b7280; line-height:1.65; }}
@@ -5201,6 +5294,7 @@ body {{ margin:0; padding:{body_padding}; background:{body_background}; color:#1
<table class="bottom" width="100%" cellspacing="0" cellpadding="0"><tr class="{'pharmacy-signoff' if is_internal else ''}"> <table class="bottom" width="100%" cellspacing="0" cellpadding="0"><tr class="{'pharmacy-signoff' if is_internal else ''}">
{bottom_row} {bottom_row}
</tr> </tr>
{review_row}
<tr><td class="hospital" colspan="{hospital_colspan}"> <tr><td class="hospital" colspan="{hospital_colspan}">
{_SLIP_COMPANY_LINE}<br/>{_SLIP_ADDRESS_LINE} {_SLIP_COMPANY_LINE}<br/>{_SLIP_ADDRESS_LINE}
</td></tr></table> </td></tr></table>
@@ -5494,6 +5588,155 @@ class _PrescriptionPaperPreview(QTextBrowser):
painter.end() painter.end()
class PrescriptionSigningPreview(QWidget):
"""Read-only clinical prescription available alongside the signing workflow."""
def __init__(self, repository: Any, prescription: Any, *, parent: QWidget | None = None) -> None:
super().__init__(parent)
self.setObjectName("PrescriptionSigningPreview")
self.setAccessibleName("处方预览")
self._prescription_id = _int(str(first_value(prescription, "id", "prescription_id")))
has_full_seed = self._has_clinical_content(prescription) or (
_bool(first_value(prescription, "is_system_auto")) and self._has_empty_slip(prescription)
)
self._prescription = _mapping(prescription) if has_full_seed else None
self._get_detail = getattr(repository, "get_prescription", None)
self._load_generation = 0
self._esign = signature_state(prescription)
self._has_live_esign_state = False
self.paper: _PrescriptionPaperPreview | None = None
self._layout = QVBoxLayout(self)
self._layout.setContentsMargins(0, 0, 0, 0)
self._layout.setSpacing(10)
heading = QLabel("处方预览", self)
heading.setObjectName("PrescriptionSigningHeading")
self._layout.addWidget(heading)
self._notice = QWidget(self)
notice_layout = QVBoxLayout(self._notice)
notice_layout.setContentsMargins(4, 4, 4, 4)
self.status_label = QLabel(self._notice)
self.status_label.setTextFormat(Qt.TextFormat.PlainText)
self.status_label.setWordWrap(True)
notice_layout.addWidget(self.status_label)
self.retry_button = QPushButton("重新加载处方", self._notice)
self.retry_button.setAutoDefault(False)
self.retry_button.clicked.connect(self._load_or_render)
notice_layout.addWidget(self.retry_button, 0, Qt.AlignmentFlag.AlignLeft)
notice_layout.addStretch(1)
self._layout.addWidget(self._notice, 1)
self._load_or_render()
@staticmethod
def _has_clinical_content(prescription: Any) -> bool:
herbs = _herb_rows(prescription)
return bool(herbs) and all(
str(row.get("name") or "").strip() and row.get("dosage") not in (None, "")
for row in herbs
)
@staticmethod
def _has_empty_slip(prescription: Any) -> bool:
herbs = get_value(prescription, "herbs")
return (
isinstance(herbs, (list, tuple)) and not herbs
and bool(first_value(prescription, "patient_name", "clinical_diagnosis"))
)
def _show_notice(self, message: str, *, retry: bool = False) -> None:
if self.paper is not None:
self.paper.hide()
self.status_label.setText(message)
self.retry_button.setVisible(retry)
self._notice.show()
def _load_or_render(self) -> None:
if self._prescription is not None:
self._render()
return
prescription_id = self._prescription_id
if prescription_id <= 0 or not callable(self._get_detail):
self._show_notice("处方明细暂不可用。")
return
self._load_generation += 1
generation = self._load_generation
self._show_notice("正在加载处方明细…")
run_async(
self._get_detail,
prescription_id,
on_success=lambda result: self._detail_loaded(result, generation),
on_error=lambda _error: self._detail_failed(generation),
)
def _detail_loaded(self, result: Any, generation: int) -> None:
if not isValid(self) or generation != self._load_generation:
return
detail_id = _int(str(first_value(result, "id", "prescription_id")))
if detail_id != self._prescription_id:
self._show_notice("返回的处方与当前处方不匹配,请重试。", retry=True)
return
if not (self._has_clinical_content(result) or self._has_empty_slip(result)):
self._show_notice("未获取到用药明细,请重试。", retry=True)
return
self._prescription = _mapping(result)
if not self._has_live_esign_state:
self._esign = signature_state(result) or self._esign
self._render()
def _detail_failed(self, generation: int) -> None:
if isValid(self) and generation == self._load_generation:
self._show_notice("无法加载处方明细,请重试。", retry=True)
def _signature_appearance(self, state: Mapping[str, Any]) -> tuple[str, str, str]:
prescription = self._prescription or {}
doctor = str(prescription.get("doctor_name") or "")
if state.get("status") not in ("signed", "voided"):
return doctor, "", ""
signer = state.get("doctor_signer_name")
if isinstance(signer, str) and signer.strip() and not str(prescription.get("doctor_signature") or "").strip():
doctor = signer.strip()
reviewer = state.get("review_signer_name")
reviewer = reviewer.strip() if isinstance(reviewer, str) and review_signature_time(state) else ""
seal = state.get("review_signature")
return doctor, reviewer, seal if reviewer and isinstance(seal, str) else ""
def set_esign_state(self, state: Mapping[str, Any]) -> None:
previous = self._esign
self._esign = dict(state)
self._has_live_esign_state = True
if (
self._prescription is not None
and self._signature_appearance(previous) != self._signature_appearance(self._esign)
):
self._render()
def _render(self) -> None:
if self._prescription is None:
return
try:
content = render_prescription_html(self._prescription | {"esign": self._esign}, variant="internal")
if self.paper is None:
self.paper = _PrescriptionPaperPreview(self._prescription, self, variant="internal")
self.paper.setObjectName("PrescriptionSigningPaper")
self.paper.setOpenLinks(False)
self.paper.setOpenExternalLinks(False)
self.paper.document().setDocumentMargin(0)
self.paper.setStyleSheet(
"QTextBrowser#PrescriptionSigningPaper { background-color: #F7F7F7; "
"border: 1px solid #E4E4E5; padding: 0; }"
)
self._layout.addWidget(self.paper, 1)
vertical_scroll = self.paper.verticalScrollBar()
scroll_position = vertical_scroll.value()
self.paper.setHtml(content)
vertical_scroll.setValue(scroll_position)
except Exception:
self._show_notice("无法显示处方预览,请重试。", retry=True)
return
self._notice.hide()
self.paper.show()
class PrescriptionDetailDialog(QDialog): class PrescriptionDetailDialog(QDialog):
diagnosis_requested = Signal(int) diagnosis_requested = Signal(int)
orders_requested = Signal(int) orders_requested = Signal(int)
@@ -5524,10 +5767,9 @@ class PrescriptionDetailDialog(QDialog):
self._saved_original: Path | None = None self._saved_original: Path | None = None
self.document = QTextDocument(self) self.document = QTextDocument(self)
self.document.setDocumentMargin(0) self.document.setDocumentMargin(0)
self.document.setHtml(render_prescription_html(prescription, variant="internal"))
self.user_document = QTextDocument(self) self.user_document = QTextDocument(self)
self.user_document.setDocumentMargin(0) self.user_document.setDocumentMargin(0)
self.user_document.setHtml(render_prescription_html(prescription, variant="user")) self._render_slip_previews()
self.setWindowTitle("查看处方") self.setWindowTitle("查看处方")
self.resize(920, 780) self.resize(920, 780)
root = QVBoxLayout(self) root = QVBoxLayout(self)
@@ -5546,6 +5788,10 @@ class PrescriptionDetailDialog(QDialog):
self.esign_button.setVisible(self.repository is not None and callable(getattr(self.repository, "get_prescription_esign_status", None))) self.esign_button.setVisible(self.repository is not None and callable(getattr(self.repository, "get_prescription_esign_status", None)))
self.esign_button.clicked.connect(self.open_esign) self.esign_button.clicked.connect(self.open_esign)
actions.addWidget(self.esign_button) actions.addWidget(self.esign_button)
self.signing_log_button = QPushButton("签署日志", self)
self.signing_log_button.setAutoDefault(False)
self.signing_log_button.clicked.connect(lambda: SigningLogDialog(self.esign, self).exec())
actions.addWidget(self.signing_log_button)
actions.addStretch(1) actions.addStretch(1)
print_button = QPushButton("打印") print_button = QPushButton("打印")
print_button.clicked.connect(self.print_slip) print_button.clicked.connect(self.print_slip)
@@ -5561,31 +5807,7 @@ class PrescriptionDetailDialog(QDialog):
root.addLayout(actions) root.addLayout(actions)
self.status_banner = MessageBanner(parent=self) self.status_banner = MessageBanner(parent=self)
self.status_banner.setObjectName("PrescriptionDetailStatusBanner") self.status_banner.setObjectName("PrescriptionDetailStatusBanner")
status_lines: list[str] = [] self._render_review_status()
if _bool(first_value(prescription, "void_status", "is_void", default=False)):
void_by = display_text(first_value(prescription, "void_by_name", default=""), "—")
void_time = display_text(first_value(prescription, "void_time", default=""), "—")
status_lines.append(f"已作废 作废人:{void_by} {void_time}")
audit_status = _int(first_value(prescription, "audit_status", default=-1), -1)
audit_label = {0: "待审核", 1: "已通过", 2: "已驳回"}.get(audit_status, "未知")
if not status_lines or audit_status == 2:
status_lines.append(f"消费者处方审核:{audit_label}")
if _bool(first_value(prescription, "business_prescription_audit_rejected", default=False)):
status_lines.append("业务订单处方审核:已驳回")
banner_kind = (
"danger"
if _bool(first_value(prescription, "void_status", default=False))
or audit_status == 2
or _bool(
first_value(prescription, "business_prescription_audit_rejected", default=False)
)
else "success"
if audit_status == 1
else "warning"
if audit_status == 0
else "info"
)
self.status_banner.show_message(" ".join(status_lines), banner_kind)
root.addWidget(self.status_banner) root.addWidget(self.status_banner)
self.esign_banner = MessageBanner(parent=self) self.esign_banner = MessageBanner(parent=self)
self.esign_banner.label.setTextFormat(Qt.TextFormat.PlainText) self.esign_banner.label.setTextFormat(Qt.TextFormat.PlainText)
@@ -5661,23 +5883,75 @@ class PrescriptionDetailDialog(QDialog):
def _esign_loaded(self, result: Any) -> None: def _esign_loaded(self, result: Any) -> None:
try: try:
self.esign = esign_status(result) current = esign_status(result)
except Exception as error: except Exception as error:
self._esign_failed(error) self._esign_failed(error)
return return
previous = self.esign
if review_signature_time(previous) != review_signature_time(current):
self._saved_original = None
self.esign = current
self._esign_unconfirmed = False self._esign_unconfirmed = False
if any(previous.get(key) != current.get(key) for key in (
"status", "doctor_signer_name", "review_signature", "review_signer_name", "review_signature_time",
)):
self._render_slip_previews()
self._render_review_status()
self._render_esign_status() self._render_esign_status()
self._sync_esign_export() self._sync_esign_export()
def _slip_prescription(self) -> dict[str, Any]:
return _mapping(self.prescription) | {"esign": self.esign}
def _render_slip_previews(self) -> None:
prescription = self._slip_prescription()
self.document.setHtml(render_prescription_html(prescription, variant="internal"))
self.user_document.setHtml(render_prescription_html(prescription, variant="user"))
def _render_review_status(self) -> None:
prescription = self.prescription
lines: list[str] = []
voided = _bool(first_value(prescription, "void_status", "is_void", default=False))
if voided:
void_by = display_text(first_value(prescription, "void_by_name", default=""), "—")
void_time = display_text(first_value(prescription, "void_time", default=""), "—")
lines.append(f"已作废 作废人:{void_by} {void_time}")
audit_status = _int(first_value(prescription, "audit_status", default=-1), -1)
label, kind = {
0: ("待审核", "warning"),
1: ("已通过", "success"),
2: ("已驳回", "danger"),
}.get(audit_status, ("未知", "info"))
if audit_status == 0:
if awaiting_prescription_upload(prescription, self.esign):
label = "待上传处方"
elif self.esign.get("required") is True and self.esign.get("status") != "signed":
label = "待签名"
if not voided or audit_status == 2:
lines.append(f"消费者处方审核:{label}")
business_rejected = _bool(first_value(prescription, "business_prescription_audit_rejected", default=False))
if business_rejected:
lines.append("业务订单处方审核:已驳回")
self.status_banner.show_message(" ".join(lines), "danger" if voided or business_rejected else kind)
def _render_esign_status(self) -> None: def _render_esign_status(self) -> None:
time_text = signature_time_text(self.esign) time_text = signature_time_text(self.esign)
if not (self.esign["enabled"] or self.esign["required"] or time_text): if not (self.esign["enabled"] or self.esign["required"] or time_text):
self.esign_banner.clear() self.esign_banner.clear()
return return
status = self.esign["status"] status = self.esign["status"]
label = str(self.esign.get("status_label") or status) awaiting_upload = awaiting_prescription_upload(self.prescription, self.esign)
label = review_signing_status(self.esign, awaiting_upload=awaiting_upload) or str(self.esign.get("status_label") or status)
environment = " · 沙箱测试" if self.esign["environment"] == "sandbox" and status != "legacy" else "" environment = " · 沙箱测试" if self.esign["environment"] == "sandbox" and status != "legacy" else ""
status_message = str(self.esign.get("message") or "") status_message = str(self.esign.get("message") or "")
if awaiting_upload:
if can_upload_prescription(self.repository, self.prescription, self.esign):
status_message = (
PRESCRIPTION_UPLOAD_BEFORE_SIGNING_PROMPT
if self.esign["required"] and status != "signed" else "请点击「上传处方」,提交药师审核。"
)
else:
status_message = status_message or "请开方医生上传处方。"
heading = f"电子签署:{label}{environment}" heading = f"电子签署:{label}{environment}"
if status_message: if status_message:
heading += f" {status_message}" heading += f" {status_message}"
@@ -5705,11 +5979,15 @@ class PrescriptionDetailDialog(QDialog):
original_available = not case_record and allowed and electronic and self._saved_original is not None original_available = not case_record and allowed and electronic and self._saved_original is not None
self.open_original_button.setVisible(original_available) self.open_original_button.setVisible(original_available)
self.open_original_button.setEnabled(original_available and not self._esign_busy) self.open_original_button.setEnabled(original_available and not self._esign_busy)
if not self._esign_unconfirmed and self.esign.get("can_sign") is True: if not self._esign_unconfirmed and can_upload_prescription(self.repository, self.prescription, self.esign):
self.esign_button.setText("去上传处方")
elif (not self._esign_unconfirmed and self.esign.get("can_sign") is True
and not awaiting_prescription_upload(self.prescription, self.esign)):
self.esign_button.setText("继续开方签名") self.esign_button.setText("继续开方签名")
else: else:
self.esign_button.setText("查看签署状态") self.esign_button.setText("查看签署状态")
self.esign_button.setEnabled(not self._esign_busy) self.esign_button.setEnabled(not self._esign_busy)
self.signing_log_button.setEnabled(not self._esign_busy and not self._esign_unconfirmed)
self.tabs.setEnabled(not self._esign_busy) self.tabs.setEnabled(not self._esign_busy)
def open_esign(self) -> None: def open_esign(self) -> None:
@@ -5729,7 +6007,7 @@ class PrescriptionDetailDialog(QDialog):
if self._is_case_record_selected(): if self._is_case_record_selected():
return render_case_record_image(self.prescription) return render_case_record_image(self.prescription)
return render_prescription_slip_image( return render_prescription_slip_image(
self.prescription, self._slip_prescription(),
variant=self._current_variant(), variant=self._current_variant(),
) )
@@ -6421,6 +6699,7 @@ __all__ = [
"PrescriptionEditorDialog", "PrescriptionEditorDialog",
"PrescriptionOrderDialog", "PrescriptionOrderDialog",
"PrescriptionOrderListDialog", "PrescriptionOrderListDialog",
"PrescriptionSigningPreview",
"PrescriptionTemplateDialog", "PrescriptionTemplateDialog",
"RemoteMedicineComboBox", "RemoteMedicineComboBox",
"SignaturePad", "SignaturePad",
@@ -46,6 +46,7 @@ from ..widgets import (
AI_MODELS: tuple[tuple[str, str, str], ...] = ( AI_MODELS: tuple[tuple[str, str, str], ...] = (
("qwen", "千问", "qwen3.6-35b"), ("qwen", "千问", "qwen3.6-35b"),
("openai", "OpenAI", "gpt-5.6-sol"), ("openai", "OpenAI", "gpt-5.6-sol"),
("doubao", "豆包", "doubao-seed-2.1-pro"),
) )
AI_MODEL_KEYS = frozenset(profile for profile, _label, _name in AI_MODELS) AI_MODEL_KEYS = frozenset(profile for profile, _label, _name in AI_MODELS)
AI_REPORT_EDIT_PERMISSIONS = ( AI_REPORT_EDIT_PERMISSIONS = (
@@ -4,6 +4,7 @@ from __future__ import annotations
from collections.abc import Callable, Mapping from collections.abc import Callable, Mapping
from hashlib import sha256 from hashlib import sha256
from html import escape
from pathlib import Path from pathlib import Path
from time import monotonic from time import monotonic
from typing import Any from typing import Any
@@ -23,10 +24,14 @@ from PySide6.QtGui import QDesktopServices
from PySide6.QtWidgets import ( from PySide6.QtWidgets import (
QDialog, QDialog,
QDialogButtonBox, QDialogButtonBox,
QFrame,
QHBoxLayout, QHBoxLayout,
QLabel, QLabel,
QLineEdit, QLineEdit,
QPushButton, QPushButton,
QScrollArea,
QSplitter,
QTextBrowser,
QVBoxLayout, QVBoxLayout,
QWidget, QWidget,
) )
@@ -58,6 +63,10 @@ _ESIGN_WRITE_PERMISSIONS = (
_SIGNABLE_STATES = ("pending", "authenticating", "failed") _SIGNABLE_STATES = ("pending", "authenticating", "failed")
_BEIJING_TIME = QTimeZone(b"Asia/Shanghai") _BEIJING_TIME = QTimeZone(b"Asia/Shanghai")
_SIGNATURE_TIME_SOURCES = {"tsa": "可信时间戳", "local": "签名记录时间"} _SIGNATURE_TIME_SOURCES = {"tsa": "可信时间戳", "local": "签名记录时间"}
_SIGNING_LOG_SOURCES = {**_SIGNATURE_TIME_SOURCES, "system": "系统记录时间"}
PRESCRIPTION_UPLOAD_PROMPT = "请在「已开处方」点击「上传处方」,提交药师审核。"
PRESCRIPTION_UPLOAD_BEFORE_SIGNING_PROMPT = "请先点击「上传处方」,随后完成医生签署。"
_REVIEW_PENDING_MESSAGE = "请有审核权限的药师在管理后台完成电子签署,随后刷新签署状态。"
_QUICK_AUTHORIZATION_STATUS = { _QUICK_AUTHORIZATION_STATUS = {
"missing": "尚未授权快捷签", "missing": "尚未授权快捷签",
"expired": "快捷签授权已过期", "expired": "快捷签授权已过期",
@@ -100,12 +109,62 @@ def signature_state(prescription: Any) -> dict[str, Any]:
return dict(value) if isinstance(value, Mapping) else {} return dict(value) if isinstance(value, Mapping) else {}
def review_submission_time(prescription: Any, state: Mapping[str, Any] | None = None) -> int | None:
value = first_value(state, "review_submitted_at", default=first_value(prescription, "review_submitted_at"))
return value if type(value) is int and value >= 0 else None
def can_upload_prescription(repository: Any, prescription: Any, state: Mapping[str, Any]) -> bool:
return (
review_submission_time(prescription, state) == 0
and first_value(state, "can_submit_for_review", default=first_value(prescription, "can_submit_for_review")) is True
and callable(getattr(repository, "submit_prescription_for_review", None))
)
def awaiting_prescription_upload(prescription: Any, state: Mapping[str, Any]) -> bool:
flag = first_value(state, "awaiting_upload", default=first_value(prescription, "awaiting_upload"))
if isinstance(flag, bool):
return flag
return review_submission_time(prescription, state) == 0 and (
state.get("status") in ("signed", "legacy")
or first_value(state, "can_submit_for_review", default=first_value(prescription, "can_submit_for_review")) is True
)
def can_review_uploaded_prescription(prescription: Any, state: Mapping[str, Any]) -> bool:
if review_submission_time(prescription, state) == 0 or awaiting_prescription_upload(prescription, state):
return False
flag = first_value(state, "can_review_prescription", default=first_value(prescription, "can_review_prescription"))
if isinstance(flag, bool):
return flag
return state.get("required") is not True or state.get("status") == "signed"
def _format_esign_time(value: Any) -> str: def _format_esign_time(value: Any) -> str:
if type(value) is not int or not 0 < value <= 253402300799: if type(value) is not int or not 0 < value <= 253402300799:
return "" return ""
return QDateTime.fromSecsSinceEpoch(value, _BEIJING_TIME).toString("yyyy-MM-dd HH:mm:ss") return QDateTime.fromSecsSinceEpoch(value, _BEIJING_TIME).toString("yyyy-MM-dd HH:mm:ss")
def review_signature_time(state: Mapping[str, Any]) -> str:
if state.get("status") not in ("signed", "voided"):
return ""
return _format_esign_time(state.get("review_signature_time"))
def review_signing_status(state: Mapping[str, Any], *, awaiting_upload: bool = False) -> str:
if awaiting_upload and state.get("status") in ("pending", "authenticating", "failed", "uncertain"):
return "待上传处方"
if state.get("status") != "signed":
return ""
if review_signature_time(state):
return "医生与药师已签署"
if awaiting_upload:
return "医生已签署,待上传处方"
return "医生已签署,待药师签署" if state.get("review_required") is True else ""
def signature_time_text(state: Mapping[str, Any]) -> str: def signature_time_text(state: Mapping[str, Any]) -> str:
"""Display the archived prescription's issue and signing events separately.""" """Display the archived prescription's issue and signing events separately."""
status = state.get("status") status = state.get("status")
@@ -121,22 +180,70 @@ def signature_time_text(state: Mapping[str, Any]) -> str:
if QDate.fromString(original_date, date_format).toString(date_format) == original_date: if QDate.fromString(original_date, date_format).toString(date_format) == original_date:
lines.append(f"原件记载日期:{original_date}(未记录开具时分秒)") lines.append(f"原件记载日期:{original_date}(未记录开具时分秒)")
review_time = review_signature_time(state)
doctor = "医生" if state.get("review_required") is True or review_time else ""
source = _SIGNATURE_TIME_SOURCES.get(str(state.get("signature_time_source"))) source = _SIGNATURE_TIME_SOURCES.get(str(state.get("signature_time_source")))
signature_time = _format_esign_time(state.get("signature_time")) if source else "" signature_time = _format_esign_time(state.get("signature_time")) if source else ""
if signature_time: if signature_time:
lines.append(f"签署时间:{signature_time}(北京时间 · {source})") lines.append(f"{doctor}签署时间:{signature_time}(北京时间 · {source})")
else: else:
completed = _format_esign_time(state.get("signed_at")) completed = _format_esign_time(state.get("signed_at"))
if completed or status == "signed" or state.get("can_download") is True: if completed or status == "signed" or state.get("can_download") is True:
lines.append("签署时间待核实") lines.append(f"{doctor}签署时间待核实")
if completed: if completed:
lines.append(f"系统验签完成时间:{completed}(北京时间)") lines.append(f"系统验签完成时间:{completed}(北京时间)")
if review_time:
name = state.get("review_signer_name")
if isinstance(name, str) and name.strip():
lines.append(f"签署药师:{name.strip()}")
lines.append(f"药师签署时间:{review_time}(北京时间 · 可信时间戳)")
return "\n".join(lines) return "\n".join(lines)
def can_continue_prescription_esign(state: Mapping[str, Any], permissions: Any) -> bool: class SigningLogDialog(QDialog):
"""Read-only signing events from the prescription status response."""
def __init__(self, state: Mapping[str, Any], parent: QWidget) -> None:
super().__init__(parent)
self.setWindowTitle("签署日志")
self.resize(640, 440)
self.setStyleSheet(clinical_stylesheet("QDialog { background:#FFFFFF; }"))
layout = QVBoxLayout(self)
self.entries = QTextBrowser(self)
self.entries.setOpenLinks(False)
layout.addWidget(self.entries, 1)
events = state.get("signing_log")
rows = []
for event in events if isinstance(events, list) else []:
if not isinstance(event, Mapping):
continue
timestamp = _format_esign_time(event.get("time"))
label, source = event.get("label"), event.get("source")
if not timestamp or not isinstance(label, str) or not isinstance(source, str):
continue
source_label = _SIGNING_LOG_SOURCES.get(source)
if not label.strip() or source_label is None:
continue
actor = event.get("actor_name")
actor = f" · {escape(actor.strip())}" if isinstance(actor, str) and actor.strip() else ""
message = event.get("message")
message = f"<br/>{escape(message.strip())}" if isinstance(message, str) and message.strip() else ""
rows.append(
f'<p style="margin:8px 4px 14px;"><b>{escape(label.strip())}</b>{actor}<br/>'
f'<span style="color:#526275;">{timestamp}(北京时间 · {source_label})</span>{message}</p>'
)
self.entries.setHtml("".join(rows) if rows else "<p>暂无签署日志。</p>")
close = QDialogButtonBox(QDialogButtonBox.StandardButton.Close, self)
close.button(QDialogButtonBox.StandardButton.Close).setText("关闭")
close.rejected.connect(self.reject)
layout.addWidget(close)
def can_continue_prescription_esign(state: Mapping[str, Any], permissions: Any, prescription: Any = None) -> bool:
return ( return (
state.get("enabled") is True not awaiting_prescription_upload(prescription, state)
and state.get("enabled") is True
and state.get("required") is True and state.get("required") is True
and ( and (
(state.get("status") in _SIGNABLE_STATES and state.get("can_sign") is True) (state.get("status") in _SIGNABLE_STATES and state.get("can_sign") is True)
@@ -157,11 +264,19 @@ def saved_prescription_message(prescription: Any, fallback: str) -> tuple[str, s
state = esign_status(signature_state(prescription)) state = esign_status(signature_state(prescription))
except Exception: except Exception:
return "处方已保存,电子签署状态尚未确认,请在处方详情查询。", "warning" return "处方已保存,电子签署状态尚未确认,请在处方详情查询。", "warning"
if awaiting_prescription_upload(prescription, state):
if state.get("status") == "signed":
return "处方已保存,医生已签署。" + PRESCRIPTION_UPLOAD_PROMPT, "success"
if state.get("required") is True:
return "处方草稿已保存。" + PRESCRIPTION_UPLOAD_BEFORE_SIGNING_PROMPT, "success"
return "处方草稿已保存。" + PRESCRIPTION_UPLOAD_PROMPT, "success"
if state.get("required") is True and state.get("status") != "signed": if state.get("required") is True and state.get("status") != "signed":
if state.get("verification_method") == "quick": if state.get("verification_method") == "quick":
return "处方草稿已保存,尚待完成电子签署。可在处方详情继续签署。", "warning" return "处方草稿已保存,尚待完成电子签署。可在处方详情继续签署。", "warning"
return "处方草稿已保存,尚待完成电子签署。可在处方详情继续验证身份或签名。", "warning" return "处方草稿已保存,尚待完成电子签署。可在处方详情继续验证身份或签名。", "warning"
if state.get("status") == "signed": if state.get("status") == "signed":
if state.get("review_required") is True and not review_signature_time(state):
return "处方已保存,医生已签署,等待药师签署。", "success"
return "处方已保存并完成电子签署,等待审核。", "success" return "处方已保存并完成电子签署,等待审核。", "success"
return fallback, "success" return fallback, "success"
@@ -171,7 +286,12 @@ def resume_saved_prescription(repository: Any, prescription: Any, parent: QWidge
state = esign_status(signature_state(prescription)) state = esign_status(signature_state(prescription))
except Exception: except Exception:
state = {} state = {}
if state.get("required") is True and state.get("status") != "signed": has_next_step = (
can_upload_prescription(repository, prescription, state)
if awaiting_prescription_upload(prescription, state)
else state.get("required") is True and state.get("status") != "signed"
)
if has_next_step:
dialog = PrescriptionEsignDialog(repository, prescription, parent=parent) dialog = PrescriptionEsignDialog(repository, prescription, parent=parent)
dialog.exec() dialog.exec()
return dialog.state.get("status") == "signed" return dialog.state.get("status") == "signed"
@@ -190,6 +310,11 @@ class PrescriptionEsignDialog(QDialog):
self.repository = repository self.repository = repository
self.prescription_id = int(first_value(prescription, "id", "prescription_id", default=0) or 0) self.prescription_id = int(first_value(prescription, "id", "prescription_id", default=0) or 0)
self._system_placeholder = first_value(prescription, "is_system_auto") in (True, 1, "1") self._system_placeholder = first_value(prescription, "is_system_auto") in (True, 1, "1")
initial_state = signature_state(prescription)
self._submission = {
key: first_value(initial_state, key, default=first_value(prescription, key))
for key in ("review_submitted_at", "awaiting_upload", "can_submit_for_review")
}
self.state: dict[str, Any] = {} self.state: dict[str, Any] = {}
self._saved_original: Path | None = None self._saved_original: Path | None = None
self._busy = False self._busy = False
@@ -213,43 +338,96 @@ class PrescriptionEsignDialog(QDialog):
self.poll_timer.timeout.connect(self._poll_identity) self.poll_timer.timeout.connect(self._poll_identity)
self.setWindowTitle("处方电子签署") self.setWindowTitle("处方电子签署")
self.setMinimumSize(900, 700) self.setMinimumSize(900, 700)
self.resize(1040, 800) self.resize(1240, 800)
self.setStyleSheet(clinical_stylesheet("QDialog { background:#FFFFFF; }")) self.setStyleSheet(clinical_stylesheet(
layout = QVBoxLayout(self) "QDialog { background: #FFFFFF; }"
layout.setContentsMargins(24, 24, 24, 24) "QFrame#PrescriptionSigningWorkflow { background: #FFFFFF; border: 1px solid #DFE6EF; border-radius: 10px; }"
layout.setSpacing(12) "QLabel#PrescriptionSigningHeading { font-size: 16px; font-weight: 600; color: #20354E; }"
self.steps = QWidget(self) "QScrollArea#PrescriptionSigningDetails { border: 0; background: #FFFFFF; }"
steps = QHBoxLayout(self.steps) "QWidget#PrescriptionSigningStatus { background: #FFFFFF; }"
))
self._build_workspace(prescription)
self.refresh()
def _build_workspace(self, prescription: Any) -> None:
# Prescription details share the same paper renderer as this preview.
from .prescription import PrescriptionSigningPreview
root = QVBoxLayout(self)
root.setContentsMargins(20, 20, 20, 20)
self.workspace_splitter = QSplitter(Qt.Orientation.Horizontal, self)
self.workspace_splitter.setChildrenCollapsible(False)
self.workspace_splitter.setHandleWidth(12)
root.addWidget(self.workspace_splitter)
self.prescription_preview = PrescriptionSigningPreview(self.repository, prescription, parent=self.workspace_splitter)
self.prescription_preview.setMinimumWidth(370)
self.status_changed.connect(self.prescription_preview.set_esign_state)
self.workspace_splitter.addWidget(self.prescription_preview)
self.workflow_panel = QFrame(self.workspace_splitter)
self.workflow_panel.setObjectName("PrescriptionSigningWorkflow")
self.workflow_panel.setAccessibleName("签署流程")
self.workflow_panel.setMinimumWidth(410)
self.workspace_splitter.addWidget(self.workflow_panel)
self.workspace_splitter.setStretchFactor(0, 3)
self.workspace_splitter.setStretchFactor(1, 2)
self.workspace_splitter.setSizes([650, 538])
workflow = QVBoxLayout(self.workflow_panel)
workflow.setContentsMargins(16, 14, 16, 14)
workflow.setSpacing(10)
heading = QLabel("签署流程", self.workflow_panel)
heading.setObjectName("PrescriptionSigningHeading")
workflow.addWidget(heading)
# Keep the native identity browser outside the scrollable status area.
self.workflow_scroll = QScrollArea(self.workflow_panel)
self.workflow_scroll.setObjectName("PrescriptionSigningDetails")
self.workflow_scroll.setWidgetResizable(True)
self.workflow_scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
self.workflow_scroll.setMinimumHeight(118)
workflow.addWidget(self.workflow_scroll, 1)
details = QWidget(self.workflow_scroll)
details.setObjectName("PrescriptionSigningStatus")
self.workflow_scroll.setWidget(details)
info = QVBoxLayout(details)
info.setContentsMargins(0, 0, 0, 0)
info.setSpacing(8)
self.steps = QWidget(details)
steps = QVBoxLayout(self.steps)
steps.setContentsMargins(0, 0, 0, 0) steps.setContentsMargins(0, 0, 0, 0)
steps.setSpacing(8) steps.setSpacing(5)
self.step_labels = [] self.step_labels = []
for title in ("处方草稿已保存", "验证医生身份", "签名并完成"): for title in ("保存草稿", "上传处方", "验证医生身份", "医生签署", "药师审核"):
if self.step_labels: label = QLabel(title, self.steps)
steps.addWidget(QLabel("→", self)) label.setAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter)
label = QLabel(title, self) label.setWordWrap(True)
label.setAlignment(Qt.AlignmentFlag.AlignCenter) steps.addWidget(label)
steps.addWidget(label, 1)
self.step_labels.append(label) self.step_labels.append(label)
layout.addWidget(self.steps) self.review_step_label = self.step_labels[-1]
info.addWidget(self.steps)
patient = str(first_value(prescription, "patient_name", default="") or "").strip() patient = str(first_value(prescription, "patient_name", default="") or "").strip()
reference = str(first_value(prescription, "sn", "prescription_no", default="") or "").strip() reference = str(first_value(prescription, "sn", "prescription_no", default="") or "").strip()
if patient or reference: if patient or reference:
summary = QLabel(" · ".join(text for text in (patient, reference) if text), self) summary = QLabel(" · ".join(text for text in (patient, reference) if text), details)
summary.setTextFormat(Qt.TextFormat.PlainText) summary.setTextFormat(Qt.TextFormat.PlainText)
summary.setWordWrap(True) summary.setWordWrap(True)
layout.addWidget(summary) info.addWidget(summary)
self.status_label = QLabel("正在确认签署状态…") self.status_label = QLabel("正在确认签署状态…", details)
self.status_label.setTextFormat(Qt.TextFormat.PlainText) self.status_label.setTextFormat(Qt.TextFormat.PlainText)
layout.addWidget(self.status_label) self.status_label.setWordWrap(True)
self.signature_time_label = QLabel(self) info.addWidget(self.status_label)
self.signature_time_label = QLabel(details)
self.signature_time_label.setTextFormat(Qt.TextFormat.PlainText) self.signature_time_label.setTextFormat(Qt.TextFormat.PlainText)
self.signature_time_label.setWordWrap(True) self.signature_time_label.setWordWrap(True)
self.signature_time_label.hide() self.signature_time_label.hide()
layout.addWidget(self.signature_time_label) info.addWidget(self.signature_time_label)
self.banner = MessageBanner(parent=self) self.banner = MessageBanner(parent=details)
self.banner.label.setTextFormat(Qt.TextFormat.PlainText) self.banner.label.setTextFormat(Qt.TextFormat.PlainText)
layout.addWidget(self.banner) info.addWidget(self.banner)
self.identity_details_container = QWidget(self) self.identity_details_container = QWidget(details)
details_layout = QVBoxLayout(self.identity_details_container) details_layout = QVBoxLayout(self.identity_details_container)
details_layout.setContentsMargins(0, 0, 0, 0) details_layout.setContentsMargins(0, 0, 0, 0)
details_hint = QLabel( details_hint = QLabel(
@@ -265,8 +443,8 @@ class PrescriptionEsignDialog(QDialog):
self.identity_number_input.setInputMethodHints(Qt.InputMethodHint.ImhSensitiveData | Qt.InputMethodHint.ImhNoPredictiveText) self.identity_number_input.setInputMethodHints(Qt.InputMethodHint.ImhSensitiveData | Qt.InputMethodHint.ImhNoPredictiveText)
details_layout.addWidget(self.identity_number_input) details_layout.addWidget(self.identity_number_input)
self.identity_details_container.hide() self.identity_details_container.hide()
layout.addWidget(self.identity_details_container) info.addWidget(self.identity_details_container)
self.sms_container = QWidget(self) self.sms_container = QWidget(details)
sms_layout = QVBoxLayout(self.sms_container) sms_layout = QVBoxLayout(self.sms_container)
sms_layout.setContentsMargins(0, 0, 0, 0) sms_layout.setContentsMargins(0, 0, 0, 0)
sms_label = QLabel("本张处方的短信验证码", self.sms_container) sms_label = QLabel("本张处方的短信验证码", self.sms_container)
@@ -282,12 +460,20 @@ class PrescriptionEsignDialog(QDialog):
sms_layout.addWidget(sms_label) sms_layout.addWidget(sms_label)
sms_layout.addWidget(self.sms_code_input) sms_layout.addWidget(self.sms_code_input)
self.sms_container.hide() self.sms_container.hide()
layout.addWidget(self.sms_container) info.addWidget(self.sms_container)
self.identity_container = QWidget(self) info.addStretch(1)
self.identity_container = QWidget(self.workflow_panel)
self.identity_container.setMinimumHeight(240)
self.identity_layout = QVBoxLayout(self.identity_container) self.identity_layout = QVBoxLayout(self.identity_container)
self.identity_layout.setContentsMargins(0, 0, 0, 0) self.identity_layout.setContentsMargins(0, 0, 0, 0)
layout.addWidget(self.identity_container, 1) self.identity_container.hide()
footer = QHBoxLayout() workflow.addWidget(self.identity_container, 2)
actions = QVBoxLayout()
actions.setSpacing(6)
self.upload_button = QPushButton("上传处方")
self.upload_button.clicked.connect(self.upload)
self.start_button = QPushButton("开始验证") self.start_button = QPushButton("开始验证")
self.start_button.clicked.connect(self.start) self.start_button.clicked.connect(self.start)
self.complete_button = QPushButton("继续验证") self.complete_button = QPushButton("继续验证")
@@ -306,36 +492,49 @@ class PrescriptionEsignDialog(QDialog):
self.open_original_button = QPushButton("打开已保存原件") self.open_original_button = QPushButton("打开已保存原件")
self.open_original_button.clicked.connect(self._open_saved_original) self.open_original_button.clicked.connect(self._open_saved_original)
self._action_buttons = ( self._action_buttons = (
self.start_button, self.complete_button, self.sign_button, self.doctor_identity_button, self.upload_button, self.start_button, self.complete_button, self.sign_button, self.doctor_identity_button,
self.refresh_button, self.verify_button, self.download_button, self.open_original_button, self.refresh_button, self.verify_button, self.download_button, self.open_original_button,
) )
for button in self._action_buttons: for button in self._action_buttons:
button.setAutoDefault(False) button.setAutoDefault(False)
footer.addWidget(button) actions.addWidget(button)
workflow.addLayout(actions)
footer = QHBoxLayout()
footer.addStretch(1) footer.addStretch(1)
self.signing_log_button = QPushButton("签署日志", self.workflow_panel)
self.signing_log_button.setAutoDefault(False)
self.signing_log_button.clicked.connect(lambda: SigningLogDialog(self.state, self).exec())
footer.addWidget(self.signing_log_button)
self.close_buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Close) self.close_buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Close)
self.close_buttons.button(QDialogButtonBox.StandardButton.Close).setText("关闭") self.close_buttons.button(QDialogButtonBox.StandardButton.Close).setText("关闭")
self.close_buttons.button(QDialogButtonBox.StandardButton.Close).setAutoDefault(False) self.close_buttons.button(QDialogButtonBox.StandardButton.Close).setAutoDefault(False)
self.close_buttons.rejected.connect(self.reject) self.close_buttons.rejected.connect(self.reject)
footer.addWidget(self.close_buttons) footer.addWidget(self.close_buttons)
layout.addLayout(footer) workflow.addLayout(footer)
self.refresh()
def _sync_actions(self) -> None: def _sync_actions(self) -> None:
available = not self._busy and not self._closed and not self._native_hide_pending available = not self._busy and not self._closed and not self._native_hide_pending
status = self.state.get("status") status = self.state.get("status")
requires_review = self.state.get("review_required") is True
review_done = bool(review_signature_time(self.state))
review_pending = status == "signed" and requires_review and not review_done
legacy = self._confirmed and status == "legacy" and self.state.get("required") is False legacy = self._confirmed and status == "legacy" and self.state.get("required") is False
incomplete = self._confirmed and self._needs_prescription_content() incomplete = self._confirmed and self._needs_prescription_content()
awaiting_upload = self._awaiting_upload()
signer = self._confirmed and self._can_sign() and not self._completion_sent signer = self._confirmed and self._can_sign() and not self._completion_sent
restart = self.state.get("identity_status") in {"FAIL", "EXPIRED"} restart = self.state.get("identity_status") in {"FAIL", "EXPIRED"}
main = None if legacy or incomplete else self.refresh_button main = None if legacy or incomplete else self.refresh_button
secondary = None secondary = None
sms_input = False sms_input = False
if self._confirmed and status in {"signed", "voided"} and self.state.get("can_download") is True: if self._confirmed and self._can_upload():
main = self.upload_button
if status == "signed" and self.state.get("can_download") is True:
secondary = self.download_button
elif self._confirmed and status in {"signed", "voided"} and self.state.get("can_download") is True:
main = self.download_button main = self.download_button
if self._saved_original is not None: if self._saved_original is not None:
secondary = self.open_original_button secondary = self.open_original_button
elif (self._confirmed and status == "uncertain" elif (self._confirmed and not awaiting_upload and status == "uncertain"
and all(self.state.get(key) is True for key in ("enabled", "required", "can_retry_verify"))): and all(self.state.get(key) is True for key in ("enabled", "required", "can_retry_verify"))):
main, secondary = self.verify_button, self.refresh_button main, secondary = self.verify_button, self.refresh_button
elif signer: elif signer:
@@ -379,7 +578,9 @@ class PrescriptionEsignDialog(QDialog):
else: else:
self.refresh_button.setText("查询签署结果" if self._completion_sent or status in {"signing", "signed", "uncertain"} else "重试查询状态") self.refresh_button.setText("查询签署结果" if self._completion_sent or status in {"signing", "signed", "uncertain"} else "重试查询状态")
for button in self._action_buttons: for button in self._action_buttons:
active = button in (main, secondary) or (sms_input and button is self.refresh_button) active = button in (main, secondary) or (
(sms_input or review_pending) and button is self.refresh_button
)
button.setVisible(active) button.setVisible(active)
button.setEnabled(active and available) button.setEnabled(active and available)
variant = "primary" if button is main else None variant = "primary" if button is main else None
@@ -392,29 +593,45 @@ class PrescriptionEsignDialog(QDialog):
self.sms_code_input.setText("") self.sms_code_input.setText("")
self.sms_container.setVisible(sms_input) self.sms_container.setVisible(sms_input)
self.sms_code_input.setEnabled(available and sms_input) self.sms_code_input.setEnabled(available and sms_input)
self.steps.setVisible(self._confirmed and not legacy and not incomplete) self.steps.setVisible(self._confirmed and (not legacy or awaiting_upload) and not incomplete)
self.signing_log_button.setEnabled(self._confirmed and available)
time_text = signature_time_text(self.state) if self._confirmed else "" time_text = signature_time_text(self.state) if self._confirmed else ""
self.signature_time_label.setText(time_text) self.signature_time_label.setText(time_text)
self.signature_time_label.setVisible(bool(time_text)) self.signature_time_label.setVisible(bool(time_text))
finished = status == "signed" doctor_done = status == "signed" or (
signing = self._identity_ready or self._completion_sent or status in {"signing", "uncertain", "signed"} status == "voided" and (self.state.get("can_download") is True or review_done)
self.step_labels[1].setText("核对快捷签授权" if self._uses_quick() else )
signing = self._identity_ready or self._completion_sent or status in {"signing", "uncertain"}
self.step_labels[2].setText("核对快捷签授权" if self._uses_quick() else
"短信确认签署意愿" if self._uses_sms() else "验证医生身份") "短信确认签署意愿" if self._uses_sms() else "验证医生身份")
for index, label in enumerate(self.step_labels): self.review_step_label.setText("药师审核签署" if requires_review or review_done else "药师审核")
complete = index == 0 or finished or (index == 1 and signing) uses_upload = review_submission_time(self._submission, self.state) is not None
current = not complete and index == (2 if signing else 1) visible_steps = (True, uses_upload, not legacy, not legacy, uses_upload or requires_review or review_done)
completed_steps = (True, not awaiting_upload, signing or doctor_done, doctor_done, review_done)
current_seen = status == "voided"
for label, visible, complete in zip(self.step_labels, visible_steps, completed_steps, strict=True):
label.setVisible(visible)
current = visible and not complete and not current_seen
current_seen = current_seen or current
color, background = (("#146452", "#E6F4EF") if complete else color, background = (("#146452", "#E6F4EF") if complete else
("#174B79", "#E9F2FC") if current else ("#526275", "#F2F5F8")) ("#174B79", "#E9F2FC") if current else ("#526275", "#F2F5F8"))
label.setStyleSheet(f"padding: 10px 8px; border-radius: 6px; color: {color}; background: {background};") label.setStyleSheet(f"padding: 6px 10px; border-radius: 6px; color: {color}; background: {background};")
label.setAccessibleDescription("已完成" if complete else "当前步骤" if current else "待完成") label.setAccessibleDescription("已完成" if complete else "当前步骤" if current else "待完成")
def _awaiting_upload(self) -> bool:
return awaiting_prescription_upload(self._submission, self.state)
def _can_upload(self) -> bool:
return can_upload_prescription(self.repository, self._submission, self.state)
def _can_sign(self) -> bool: def _can_sign(self) -> bool:
return (self.state.get("status") in _SIGNABLE_STATES return (not self._awaiting_upload() and self.state.get("status") in _SIGNABLE_STATES
and all(self.state.get(key) is True for key in ("enabled", "required", "can_sign"))) and all(self.state.get(key) is True for key in ("enabled", "required", "can_sign")))
def _needs_prescription_content(self) -> bool: def _needs_prescription_content(self) -> bool:
return self._system_placeholder and self.state.get("status") in {"legacy", "pending"} and not self._can_sign() return (self._system_placeholder and self.state.get("status") in {"legacy", "pending"}
and not self._can_upload() and not self._can_sign())
def _uses_sms(self) -> bool: def _uses_sms(self) -> bool:
return self.state.get("verification_method") == "sms" return self.state.get("verification_method") == "sms"
@@ -445,6 +662,7 @@ class PrescriptionEsignDialog(QDialog):
view.stop() view.stop()
self.identity_layout.removeWidget(view) self.identity_layout.removeWidget(view)
view.deleteLater() view.deleteLater()
self.identity_container.hide()
def _stop_flow(self) -> None: def _stop_flow(self) -> None:
self.poll_timer.stop() self.poll_timer.stop()
@@ -522,7 +740,11 @@ class PrescriptionEsignDialog(QDialog):
self._identity_native_window_id = None self._identity_native_window_id = None
def _apply_state(self, result: Any, *, after_sign: bool = False) -> None: def _apply_state(self, result: Any, *, after_sign: bool = False) -> None:
self.state = esign_status(result) state = esign_status(result)
if review_signature_time(self.state) != review_signature_time(state):
self._saved_original = None
self.state = state
self._submission.update({key: state[key] for key in self._submission if key in state})
self._confirmed = True self._confirmed = True
status = self.state["status"] status = self.state["status"]
self._retry_identity = False self._retry_identity = False
@@ -543,12 +765,32 @@ class PrescriptionEsignDialog(QDialog):
label, message = "签署结果待确认", "请查询签署结果。" label, message = "签署结果待确认", "请查询签署结果。"
if status == "legacy" and not self.state["required"]: if status == "legacy" and not self.state["required"]:
label = "沿用原有处方流程" if self.state["enabled"] else "电子签署功能已关闭" label = "沿用原有处方流程" if self.state["enabled"] else "电子签署功能已关闭"
if self._awaiting_upload():
label = "待上传处方"
self.status_label.setText(label) self.status_label.setText(label)
message = "此处方沿用原有处方流程。您可关闭此窗口,返回处方详情或列表。" message = "此处方沿用原有处方流程。您可关闭此窗口,返回处方详情或列表。"
if self.state.get("can_review_prescription") is True:
message = "处方已上传,等待药师审核。"
else: else:
self._show_status("签名已完成" if status == "signed" else label) review_status = review_signing_status(self.state, awaiting_upload=self._awaiting_upload())
self._show_status(review_status or ("签名已完成" if status == "signed" else label))
if review_status:
if review_signature_time(self.state):
message = "医生和药师的签名均已验签。"
elif not self._awaiting_upload():
server_message = self.state.get("message")
message = f"{server_message}\n{_REVIEW_PENDING_MESSAGE}" if server_message else _REVIEW_PENDING_MESSAGE
if self._needs_prescription_content(): if self._needs_prescription_content():
message = "此处方由系统占号生成。请开方医生先返回列表,编辑并补全处方内容。" message = "此处方由系统占号生成。请开方医生先返回列表,编辑并补全处方内容。"
elif self._awaiting_upload():
if self._can_upload():
message = (
PRESCRIPTION_UPLOAD_BEFORE_SIGNING_PROMPT
if self.state["required"] and status != "signed"
else "请点击「上传处方」,提交药师审核。"
)
else:
message = str(self.state.get("message") or "请开方医生上传处方。")
elif self._can_sign() and self._needs_quick_account_setup(): elif self._can_sign() and self._needs_quick_account_setup():
if self.state.get("doctor_identity_required") is True: if self.state.get("doctor_identity_required") is True:
if "signing_authorization_required" in self.state: if "signing_authorization_required" in self.state:
@@ -597,6 +839,8 @@ class PrescriptionEsignDialog(QDialog):
self._retry_identity = True self._retry_identity = True
self._show_status("身份验证状态待确认") self._show_status("身份验证状态待确认")
self.banner.show_message(f"{friendly_error(error)} 请重试验证状态。", "warning") self.banner.show_message(f"{friendly_error(error)} 请重试验证状态。", "warning")
elif method == "submit_prescription_for_review":
self.banner.show_message(f"{friendly_error(error)} 可重试上传处方。", "warning")
else: else:
self._confirmed = False self._confirmed = False
self.status_label.setText("签署结果尚未确认" if self._completion_sent else "处方签署状态尚未确认") self.status_label.setText("签署结果尚未确认" if self._completion_sent else "处方签署状态尚未确认")
@@ -622,6 +866,7 @@ class PrescriptionEsignDialog(QDialog):
self._busy = True self._busy = True
generation = self._generation generation = self._generation
proof_supplied = bool(identity_number) proof_supplied = bool(identity_number)
upload_confirmed = False
self._sync_actions() self._sync_actions()
repository, prescription_id = self.repository, self.prescription_id repository, prescription_id = self.repository, self.prescription_id
@@ -629,12 +874,23 @@ class PrescriptionEsignDialog(QDialog):
return isValid(self) and not self._closed and self._generation == generation return isValid(self) and not self._closed and self._generation == generation
def loaded(result: Any) -> None: def loaded(result: Any) -> None:
nonlocal upload_confirmed
if not current(): if not current():
return return
if self._native_hide_pending: if self._native_hide_pending:
QTimer.singleShot(0, lambda: loaded(result)) QTimer.singleShot(0, lambda: loaded(result))
return return
try: try:
if method == "submit_prescription_for_review":
submitted_at = review_submission_time(result)
if not submitted_at or first_value(result, "can_submit_for_review") is not False:
raise ValueError("处方上传结果格式不正确")
self._apply_state({
**self.state, "review_submitted_at": submitted_at, "awaiting_upload": False,
"can_submit_for_review": False, "can_sign": False, "can_retry_verify": False,
})
upload_confirmed = True
return
readiness_query = method in {"get_prescription_esign_identity_status", "verify_prescription_esign_willingness"} readiness_query = method in {"get_prescription_esign_identity_status", "verify_prescription_esign_willingness"}
if readiness_query: if readiness_query:
result = esign_identity_status(result) result = esign_identity_status(result)
@@ -678,7 +934,9 @@ class PrescriptionEsignDialog(QDialog):
self._sync_actions() self._sync_actions()
if not current(): if not current():
return return
if method == "get_prescription_esign_status": if upload_confirmed:
self.refresh()
elif method == "get_prescription_esign_status":
self._check_retained_identity() self._check_retained_identity()
elif (method == "get_prescription_esign_identity_status" and check_only and self._uses_quick() elif (method == "get_prescription_esign_identity_status" and check_only and self._uses_quick()
and self.state.get("identity_status") in {"FAIL", "EXPIRED"}): and self.state.get("identity_status") in {"FAIL", "EXPIRED"}):
@@ -713,6 +971,10 @@ class PrescriptionEsignDialog(QDialog):
self._stop_flow() self._stop_flow()
self._request("get_prescription_esign_status") self._request("get_prescription_esign_status")
def upload(self) -> None:
if self.upload_button.isEnabled() and self.isVisible():
self._request("submit_prescription_for_review")
def _check_retained_identity(self) -> None: def _check_retained_identity(self) -> None:
if (not self._check_identity_on_open or self._busy or not self.isVisible() if (not self._check_identity_on_open or self._busy or not self.isVisible()
or self._closed or not self._confirmed): or self._closed or not self._confirmed):
@@ -752,6 +1014,7 @@ class PrescriptionEsignDialog(QDialog):
view.failed.connect(lambda message, source=view: self._web_failed(source, message)) view.failed.connect(lambda message, source=view: self._web_failed(source, message))
view.initialized.connect(lambda source=view: self._identity_native_ready(source)) view.initialized.connect(lambda source=view: self._identity_native_ready(source))
self.identity_layout.addWidget(self.identity_view) self.identity_layout.addWidget(self.identity_view)
self.identity_container.show()
except Exception as error: except Exception as error:
self._stop_flow() self._stop_flow()
self.banner.show_message(friendly_error(error), "warning") self.banner.show_message(friendly_error(error), "warning")
@@ -971,8 +1234,8 @@ class PrescriptionEsignDialog(QDialog):
def saved(result: tuple[dict[str, Any], Path | None]) -> None: def saved(result: tuple[dict[str, Any], Path | None]) -> None:
if current(): if current():
state, output = result state, output = result
self._apply_state(state)
if output is None: if output is None:
self._apply_state(state)
return return
if path is None: if path is None:
self._saved_original = output self._saved_original = output
@@ -2039,8 +2039,8 @@ class AppointmentsPage(QWidget):
return return
message, kind = saved_prescription_message(prescription, "处方已保存并重新进入待审核。") message, kind = saved_prescription_message(prescription, "处方已保存并重新进入待审核。")
self.banner.show_message(message, kind) self.banner.show_message(message, kind)
self.refresh(silent=True)
resume_saved_prescription(self.repository, prescription, self) resume_saved_prescription(self.repository, prescription, self)
self.refresh(silent=True)
def _after_prescription_void(self) -> None: def _after_prescription_void(self) -> None:
show_toast(self, "处方已作废。需要再次开具时,请选择「重新开方」。", "success") show_toast(self, "处方已作废。需要再次开具时,请选择「重新开方」。", "success")
@@ -2167,8 +2167,8 @@ class AppointmentsPage(QWidget):
return return
message, kind = saved_prescription_message(prescription, "处方已开具并提交审核。") message, kind = saved_prescription_message(prescription, "处方已开具并提交审核。")
self.banner.show_message(message, kind) self.banner.show_message(message, kind)
self.refresh(silent=True)
resume_saved_prescription(self.repository, prescription, self) resume_saved_prescription(self.repository, prescription, self)
self.refresh(silent=True)
def _prescription_error(self, error: Exception, generation: int) -> None: def _prescription_error(self, error: Exception, generation: int) -> None:
if generation == self._prescription_generation: if generation == self._prescription_generation:
@@ -3464,8 +3464,8 @@ class ConsultationsPage(QWidget):
def _prescription_saved(self, prescription: Any, fallback: str) -> None: def _prescription_saved(self, prescription: Any, fallback: str) -> None:
message, kind = saved_prescription_message(prescription, fallback) message, kind = saved_prescription_message(prescription, fallback)
show_toast(self, message, kind) show_toast(self, message, kind)
self.refresh(silent=True)
resume_saved_prescription(self.repository, prescription, self) resume_saved_prescription(self.repository, prescription, self)
self.refresh(silent=True)
def _after_prescription_void(self) -> None: def _after_prescription_void(self) -> None:
show_toast(self, "处方已作废。需要再次开具时,请选择「重新开方」。", "success") show_toast(self, "处方已作废。需要再次开具时,请选择「重新开方」。", "success")
@@ -55,7 +55,13 @@ from ..design_system import PALETTE, clinical_stylesheet
from ..dialogs import DiagnosisDialog, present_ai_consult, present_order_detail from ..dialogs import DiagnosisDialog, present_ai_consult, present_order_detail
from ..dialogs.ai_consult import can_open_ai_consult from ..dialogs.ai_consult import can_open_ai_consult
from ..dialogs.prescription import PrescriptionOrderListDialog from ..dialogs.prescription import PrescriptionOrderListDialog
from ..dialogs.prescription_esign import PrescriptionEsignDialog, can_continue_prescription_esign from ..dialogs.prescription_esign import (
PrescriptionEsignDialog,
can_continue_prescription_esign,
can_review_uploaded_prescription,
review_signature_time,
review_submission_time,
)
from ..filter_disclosure import FilterDisclosure from ..filter_disclosure import FilterDisclosure
from ..infinite_list import InfiniteList from ..infinite_list import InfiniteList
from ..patient_orders_style import patient_orders_stylesheet from ..patient_orders_style import patient_orders_stylesheet
@@ -2679,6 +2685,7 @@ class PatientOrdersWorkspace(QWidget):
allowed("tcm.prescriptionOrder/auditPrescription") allowed("tcm.prescriptionOrder/auditPrescription")
and rx_audit == 0 and rx_audit == 0
and fulfillment not in {3, 4, 6} and fulfillment not in {3, 4, 6}
and can_review_uploaded_prescription(row, {})
): ):
actions.append(("audit_prescription", "处方审核", False)) actions.append(("audit_prescription", "处方审核", False))
if ( if (
@@ -3687,13 +3694,19 @@ class PatientsPage(QWidget):
def checked(state: dict[str, Any]) -> None: def checked(state: dict[str, Any]) -> None:
if self._order_review_generation != generation: if self._order_review_generation != generation:
return return
if review_submission_time(row, state) == 0:
self.order_workspace.banner.show_message("请开方医生上传处方后再审核。", "warning")
return
verified = state["required"] and state["status"] == "signed" and state["can_download"] verified = state["required"] and state["status"] == "signed" and state["can_download"]
historical = not state["required"] and state["status"] == "legacy" and not state["can_download"] historical = not state["required"] and state["status"] == "legacy" and not state["can_download"]
if verified and state.get("review_required") is True and not review_signature_time(state):
self.order_workspace.banner.show_message("请先在管理后台完成药师审核签署,再提交审核通过。", "warning")
return
if verified or historical: if verified or historical:
self.order_workspace.banner.clear() self.order_workspace.banner.clear()
self._submit_order_audit(order_id, prescription=True, action="approve") self._submit_order_audit(order_id, prescription=True, action="approve")
return return
if can_continue_prescription_esign(state, self.permissions): if can_continue_prescription_esign(state, self.permissions, row):
dialog = PrescriptionEsignDialog(self.repository, {"id": prescription_id, "esign": state}, parent=self) dialog = PrescriptionEsignDialog(self.repository, {"id": prescription_id, "esign": state}, parent=self)
dialog.exec() dialog.exec()
self.order_workspace.banner.show_message("请在签署验签通过后,再点击处方审核。", "info") self.order_workspace.banner.show_message("请在签署验签通过后,再点击处方审核。", "info")
@@ -92,8 +92,13 @@ from ..dialogs.prescription import (
) )
from ..dialogs.prescription_esign import ( from ..dialogs.prescription_esign import (
PrescriptionEsignDialog, PrescriptionEsignDialog,
awaiting_prescription_upload,
can_continue_prescription_esign, can_continue_prescription_esign,
can_review_uploaded_prescription,
can_upload_prescription,
resume_saved_prescription, resume_saved_prescription,
review_signature_time,
review_submission_time,
saved_prescription_message, saved_prescription_message,
signature_state, signature_state,
) )
@@ -357,7 +362,7 @@ class _RowDecorationDelegate(QStyledItemDelegate):
def _row_action_button( def _row_action_button(
kind: str, kind: str | None,
tooltip: str, tooltip: str,
callback: Callable[[], None], callback: Callable[[], None],
parent: QWidget, parent: QWidget,
@@ -379,8 +384,9 @@ def _row_action_button(
button.setCursor(Qt.CursorShape.PointingHandCursor) button.setCursor(Qt.CursorShape.PointingHandCursor)
width = max(64, button.fontMetrics().horizontalAdvance(label) + 26) if label else 28 width = max(64, button.fontMetrics().horizontalAdvance(label) + 26) if label else 28
button.setFixedSize(width, 28) button.setFixedSize(width, 28)
button.setIcon(_painted_icon(kind, "danger" if danger else "accent", 15)) if kind:
button.setIconSize(QSize(15, 15)) button.setIcon(_painted_icon(kind, "danger" if danger else "accent", 15))
button.setIconSize(QSize(15, 15))
button.setEnabled(enabled) button.setEnabled(enabled)
button.clicked.connect(callback) button.clicked.connect(callback)
return button return button
@@ -439,6 +445,8 @@ def prescription_status(row: Any) -> tuple[str, str]:
if status == 1: if status == 1:
return "已通过", "success" return "已通过", "success"
signature = signature_state(row) signature = signature_state(row)
if awaiting_prescription_upload(row, signature) and not _voided(row):
return "待上传处方", "warning"
if signature.get("required") is True and signature.get("status") not in {"signed", "voided"}: if signature.get("required") is True and signature.get("status") not in {"signed", "voided"}:
if signature.get("status") == "signing": if signature.get("status") == "signing":
return "签名处理中", "warning" return "签名处理中", "warning"
@@ -474,8 +482,7 @@ def _is_pending_audit(row: Any) -> bool:
def can_audit(row: Any) -> bool: def can_audit(row: Any) -> bool:
signature = signature_state(row) return _is_pending_audit(row) and can_review_uploaded_prescription(row, signature_state(row))
return _is_pending_audit(row) and (signature.get("required") is not True or signature.get("status") == "signed")
def can_edit_or_delete(row: Any) -> bool: def can_edit_or_delete(row: Any) -> bool:
@@ -1442,6 +1449,8 @@ class PrescriptionsPage(QWidget):
toolbar.addWidget(self.create_order_button) toolbar.addWidget(self.create_order_button)
self.edit_button = self._action_button("编辑", "cf.prescription/edit", self._edit_selected) self.edit_button = self._action_button("编辑", "cf.prescription/edit", self._edit_selected)
toolbar.addWidget(self.edit_button) toolbar.addWidget(self.edit_button)
self.upload_button = self._action_button("上传处方", None, self._upload_selected)
toolbar.addWidget(self.upload_button)
self.audit_button = self._action_button( self.audit_button = self._action_button(
"审核", "cf.prescription/audit", self._audit_selected "审核", "cf.prescription/audit", self._audit_selected
) )
@@ -1602,6 +1611,7 @@ class PrescriptionsPage(QWidget):
"编辑": "pencil", "编辑": "pencil",
"删除": "trash", "删除": "trash",
"重新开方": "plus", "重新开方": "plus",
"上传处方": "send",
}.get(text) }.get(text)
if icon_kind: if icon_kind:
button.setIcon( button.setIcon(
@@ -1827,6 +1837,14 @@ class PrescriptionsPage(QWidget):
actions_host, label="AI", actions_host, label="AI",
) )
) )
if self._can_upload(row):
actions.addWidget(
_row_action_button(
None, "上传处方",
lambda _checked=False, target=row: self._run_row_action(target, self._upload_selected),
actions_host, label="上传处方", mutation=True,
)
)
can_reissue = self._can_reissue(row) can_reissue = self._can_reissue(row)
can_change = _can_change_issued_prescription(row) can_change = _can_change_issued_prescription(row)
show_changes = can_change or not _voided(row) show_changes = can_change or not _voided(row)
@@ -2155,11 +2173,17 @@ class PrescriptionsPage(QWidget):
can_change = _can_change_issued_prescription(row) can_change = _can_change_issued_prescription(row)
self.edit_button.setEnabled(active and can_change) self.edit_button.setEnabled(active and can_change)
pending_audit = _is_pending_audit(row) pending_audit = _is_pending_audit(row)
can_review = has_permission(self.permissions, "cf.prescription/audit") state = signature_state(row)
can_sign = pending_audit and can_continue_prescription_esign(signature_state(row), self.permissions) can_sign = pending_audit and can_continue_prescription_esign(state, self.permissions, row)
can_review = has_permission(self.permissions, "cf.prescription/audit") and can_audit(row)
can_upload = self._can_upload(row)
self.upload_button.setVisible(can_upload)
self.upload_button.setEnabled(active and can_upload)
self.audit_button.setText("继续签署" if can_sign else "审核") self.audit_button.setText("继续签署" if can_sign else "审核")
self.audit_button.setVisible(can_review or can_sign) self.audit_button.setVisible(can_sign or can_review)
self.audit_button.setEnabled(active and not self._audit_check_pending and pending_audit and (can_review or can_sign)) self.audit_button.setEnabled(
active and not self._audit_check_pending and (can_sign or can_review)
)
can_void = self._can_void(row) can_void = self._can_void(row)
self.void_button.setVisible(can_void) self.void_button.setVisible(can_void)
self.void_button.setEnabled(active and can_void) self.void_button.setEnabled(active and can_void)
@@ -2174,6 +2198,12 @@ class PrescriptionsPage(QWidget):
def _can_reissue(self, row: Any) -> bool: def _can_reissue(self, row: Any) -> bool:
return can_reissue_prescription(row, self.current_user, self.permissions) return can_reissue_prescription(row, self.current_user, self.permissions)
def _can_upload(self, row: Any) -> bool:
return (
_is_pending_audit(row)
and can_upload_prescription(self.repository, row, signature_state(row))
)
def _set_mutation_pending(self, pending: bool) -> None: def _set_mutation_pending(self, pending: bool) -> None:
self._mutation_pending = pending self._mutation_pending = pending
self.add_button.setEnabled(not pending) self.add_button.setEnabled(not pending)
@@ -2257,8 +2287,11 @@ class PrescriptionsPage(QWidget):
) )
dialog.diagnosis_requested.connect(self._open_diagnosis) dialog.diagnosis_requested.connect(self._open_diagnosis)
dialog.orders_requested.connect(lambda prescription_id: self._open_orders(prescription_id)) dialog.orders_requested.connect(lambda prescription_id: self._open_orders(prescription_id))
submitted_at = review_submission_time(detail, dialog.esign)
dialog.exec() dialog.exec()
if not was_signed and dialog.esign.get("status") == "signed": if review_submission_time(detail, dialog.esign) != submitted_at or (
not was_signed and dialog.esign.get("status") == "signed"
):
self.refresh() self.refresh()
def _open_diagnosis(self, diagnosis_id: int) -> None: def _open_diagnosis(self, diagnosis_id: int) -> None:
@@ -2439,9 +2472,10 @@ class PrescriptionsPage(QWidget):
message, kind = saved_prescription_message(prescription, fallback) message, kind = saved_prescription_message(prescription, fallback)
self.banner.show_message(message, kind) self.banner.show_message(message, kind)
show_toast(self, message, kind, 3600) show_toast(self, message, kind, 3600)
self.refresh()
if resume_saved_prescription(self.repository, prescription, self): if resume_saved_prescription(self.repository, prescription, self):
self._mutation_success("电子签署已完成,处方等待审核。") self._mutation_success("医生签署已完成,等待药师审核。")
else:
self.refresh()
def _delete_selected(self) -> None: def _delete_selected(self) -> None:
row = self._selected() row = self._selected()
@@ -2498,13 +2532,36 @@ class PrescriptionsPage(QWidget):
on_finished=lambda: self._set_mutation_pending(False), on_finished=lambda: self._set_mutation_pending(False),
) )
def _upload_selected(self) -> None:
row = self._selected()
if self._mutation_pending or not self._can_upload(row):
return
prescription_id = _int(first_value(row, "id", "prescription_id"), 0)
if prescription_id <= 0:
self.banner.show_message("处方 ID 无效,请刷新列表后重试。", "warning")
return
state = signature_state(row)
message = (
"处方已上传,请点击「继续签署」。"
if state.get("required") is True and state.get("status") != "signed"
else "处方已上传,等待药师审核。"
)
self._set_mutation_pending(True)
run_async(
lambda: self.repository.submit_prescription_for_review(prescription_id),
on_success=lambda _result: self._mutation_success(message),
on_error=self._mutation_error,
on_finished=lambda: self._set_mutation_pending(False),
)
def _audit_selected(self) -> None: def _audit_selected(self) -> None:
row = self._selected() row = self._selected()
if self._mutation_pending or self._audit_check_pending or not _is_pending_audit(row): if self._mutation_pending or self._audit_check_pending or not _is_pending_audit(row):
return return
can_review = has_permission(self.permissions, "cf.prescription/audit") can_review = has_permission(self.permissions, "cf.prescription/audit")
signing_action = can_continue_prescription_esign(signature_state(row), self.permissions) local_state = signature_state(row)
if not (can_review or signing_action): signing_action = can_continue_prescription_esign(local_state, self.permissions, row)
if not (signing_action or (can_review and can_audit(row))):
return return
prescription_id = _int(first_value(row, "id", "prescription_id"), 0) prescription_id = _int(first_value(row, "id", "prescription_id"), 0)
if prescription_id <= 0: if prescription_id <= 0:
@@ -2523,25 +2580,28 @@ class PrescriptionsPage(QWidget):
or _int(first_value(selected, "id", "prescription_id"), 0) != prescription_id or _int(first_value(selected, "id", "prescription_id"), 0) != prescription_id
): ):
return return
if can_continue_prescription_esign(state, self.permissions): if can_continue_prescription_esign(state, self.permissions, selected):
draft = {**_row_mapping(selected), "id": prescription_id, "esign": state} draft = {**_row_mapping(selected), "id": prescription_id, "esign": state}
dialog = PrescriptionEsignDialog(self.repository, draft, parent=self) dialog = PrescriptionEsignDialog(self.repository, draft, parent=self)
dialog.exec() dialog.exec()
if dialog.state.get("status") == "signed": if dialog.state.get("status") == "signed":
self._mutation_success("电子签署已完成,处方等待审核。") self._mutation_success("医生签署已完成,等待药师审核。")
return return
status = state["status"] status = state["status"]
if (state["required"] and status == "signed") or (not state["required"] and status == "legacy"): eligible_status = (state["required"] and status == "signed") or (not state["required"] and status == "legacy")
if eligible_status and can_review_uploaded_prescription(selected, state):
if signing_action: if signing_action:
if status == "signed": if status == "signed":
self._mutation_success("电子签署已完成,处方等待审核。") self._mutation_success("医生签署已完成,等待药师审核。")
else: else:
self.refresh() self.refresh()
elif can_review: elif can_review:
self._open_audit_dialog(selected) self._open_audit_dialog(selected, state)
return return
if status == "voided": if status == "voided":
message = "处方已作废,请刷新列表。" message = "处方已作废,请刷新列表。"
elif awaiting_prescription_upload(selected, state) or review_submission_time(selected, state) == 0:
message = "请开方医生上传处方后再审核。"
elif _truthy(first_value(selected, "is_system_auto")): elif _truthy(first_value(selected, "is_system_auto")):
message = "请开方医生编辑并补全系统占号处方,再完成电子签署。" message = "请开方医生编辑并补全系统占号处方,再完成电子签署。"
elif not state["enabled"]: elif not state["enabled"]:
@@ -2550,6 +2610,8 @@ class PrescriptionsPage(QWidget):
message = "处方正在电子签署,请稍后再审核。" message = "处方正在电子签署,请稍后再审核。"
elif status == "uncertain": elif status == "uncertain":
message = "请开方医生核对处方签署结果,确认完成后再审核。" message = "请开方医生核对处方签署结果,确认完成后再审核。"
elif status == "signed":
message = "医生签署尚未通过验签,请核对签署状态后再审核。"
else: else:
message = "请开方医生完成电子签署后再审核。" message = "请开方医生完成电子签署后再审核。"
self.banner.show_message(message, "warning") self.banner.show_message(message, "warning")
@@ -2567,8 +2629,9 @@ class PrescriptionsPage(QWidget):
on_finished=finished, on_finished=finished,
) )
def _open_audit_dialog(self, row: Any) -> None: def _open_audit_dialog(self, row: Any, state: Mapping[str, Any]) -> None:
dialog = AuditPrescriptionDialog(row, self) allow_approval = state.get("review_required") is not True or bool(review_signature_time(state))
dialog = AuditPrescriptionDialog(row, self, allow_approval=allow_approval)
if dialog.exec() != QDialog.DialogCode.Accepted: if dialog.exec() != QDialog.DialogCode.Accepted:
return return
payload = dialog.payload() payload = dialog.payload()
+101 -34
View File
@@ -116,8 +116,8 @@ STATUS_TEXT = {1: "待接诊", 2: "已取消", 3: "已完成", 4: "已过号"}
RECEPTION_STATUSES = {1, 4} RECEPTION_STATUSES = {1, 4}
NOTE_LIMIT = 500 NOTE_LIMIT = 500
MAX_NOTE_MEDIA = 99 MAX_NOTE_MEDIA = 99
AI_ANALYSIS_MODELS = ("qwen", "openai") AI_ANALYSIS_MODELS = ("qwen", "openai", "doubao")
AI_ANALYSIS_MODEL_LABELS = {"qwen": "千问", "openai": "OpenAI"} AI_ANALYSIS_MODEL_LABELS = {"qwen": "千问", "openai": "OpenAI", "doubao": "豆包"}
_ASYNC_REQUEST_CANCELLED = object() _ASYNC_REQUEST_CANCELLED = object()
_ASYNC_REQUEST_DEFERRED = object() _ASYNC_REQUEST_DEFERRED = object()
_AI_AUTOMATIC_GENERATION_SETTLE_SECONDS = 0.25 _AI_AUTOMATIC_GENERATION_SETTLE_SECONDS = 0.25
@@ -2098,7 +2098,7 @@ def _analysis_value(payload: Mapping[str, Any], key: str) -> Any:
def _patient_report_model(payload: Mapping[str, Any]) -> str: def _patient_report_model(payload: Mapping[str, Any]) -> str:
"""Return the only two model identifiers accepted by the desktop.""" """Return one of the model identifiers accepted by the desktop."""
raw = str( raw = str(
payload.get("model_key") payload.get("model_key")
@@ -2110,9 +2110,21 @@ def _patient_report_model(payload: Mapping[str, Any]) -> str:
return "qwen" return "qwen"
if raw in {"openai", "gpt"} or raw.startswith("gpt"): if raw in {"openai", "gpt"} or raw.startswith("gpt"):
return "openai" return "openai"
if raw in {"doubao", "ark", "volcengine"} or "doubao" in raw:
return "doubao"
return "" return ""
def _next_ai_analysis_model(model: str) -> str | None:
"""千问之后按顺序补齐其余模型;返回 None 表示本轮已到最后一个模型。"""
try:
index = AI_ANALYSIS_MODELS.index(model)
except ValueError:
return None
return AI_ANALYSIS_MODELS[index + 1] if index + 1 < len(AI_ANALYSIS_MODELS) else None
def _normalize_patient_report(payload: Mapping[str, Any]) -> dict[str, Any] | None: def _normalize_patient_report(payload: Mapping[str, Any]) -> dict[str, Any] | None:
"""Flatten a saved server snapshot into the existing structured card contract.""" """Flatten a saved server snapshot into the existing structured card contract."""
@@ -3193,7 +3205,7 @@ class _ReceptionAiAnalysisDialog(QDialog):
title = QLabel("患者级 AI 诊断报告", header) title = QLabel("患者级 AI 诊断报告", header)
title.setObjectName("ReceptionAiAnalysisDialogTitle") title.setObjectName("ReceptionAiAnalysisDialogTitle")
title.setProperty("dialogRole", "title") title.setProperty("dialogRole", "title")
subtitle = QLabel("查看千问与 OpenAI 的历次患者报告快照", header) subtitle = QLabel("查看千问、OpenAI 与豆包的历次患者报告快照", header)
subtitle.setObjectName("ReceptionAiAnalysisDialogSubtitle") subtitle.setObjectName("ReceptionAiAnalysisDialogSubtitle")
subtitle.setProperty("dialogRole", "subtitle") subtitle.setProperty("dialogRole", "subtitle")
heading.addWidget(title) heading.addWidget(title)
@@ -5135,7 +5147,7 @@ class ReceptionPage(QWidget):
self.ai_analysis_model_selector = _ReceptionAiModelCombo(analysis_card) self.ai_analysis_model_selector = _ReceptionAiModelCombo(analysis_card)
self.ai_analysis_model_selector.setObjectName("ReceptionAiAnalysisModelSelector") self.ai_analysis_model_selector.setObjectName("ReceptionAiAnalysisModelSelector")
self.ai_analysis_model_selector.setAccessibleName("选择卡片分析模型") self.ai_analysis_model_selector.setAccessibleName("选择卡片分析模型")
self.ai_analysis_model_selector.setToolTip("切换千问与 OpenAI 分析") self.ai_analysis_model_selector.setToolTip("切换千问、OpenAI 与豆包分析")
for model_key in AI_ANALYSIS_MODELS: for model_key in AI_ANALYSIS_MODELS:
self.ai_analysis_model_selector.addItem( self.ai_analysis_model_selector.addItem(
AI_ANALYSIS_MODEL_LABELS[model_key], AI_ANALYSIS_MODEL_LABELS[model_key],
@@ -5326,13 +5338,13 @@ class ReceptionPage(QWidget):
self.ai_analysis_history_button = QPushButton("历史报告", analysis_card) self.ai_analysis_history_button = QPushButton("历史报告", analysis_card)
self.ai_analysis_history_button.setObjectName("ReceptionAiHistoryButton") self.ai_analysis_history_button.setObjectName("ReceptionAiHistoryButton")
self.ai_analysis_history_button.setAccessibleName("查看历次 AI 报告快照") self.ai_analysis_history_button.setAccessibleName("查看历次 AI 报告快照")
self.ai_analysis_history_button.setToolTip("查看并切换千问与 OpenAI 历史报告") self.ai_analysis_history_button.setToolTip("查看并切换千问、OpenAI 与豆包历史报告")
self.ai_analysis_history_button.clicked.connect(self._open_ai_analysis_dialog) self.ai_analysis_history_button.clicked.connect(self._open_ai_analysis_dialog)
report_footer.addWidget(self.ai_analysis_history_button) report_footer.addWidget(self.ai_analysis_history_button)
self.ai_analysis_regenerate_button = QPushButton("重新分析", analysis_card) self.ai_analysis_regenerate_button = QPushButton("重新分析", analysis_card)
self.ai_analysis_regenerate_button.setObjectName("ReceptionAiRegenerateButton") self.ai_analysis_regenerate_button.setObjectName("ReceptionAiRegenerateButton")
self.ai_analysis_regenerate_button.setAccessibleName("重新生成患者级 AI 报告") self.ai_analysis_regenerate_button.setAccessibleName("重新生成患者级 AI 报告")
self.ai_analysis_regenerate_button.setToolTip("依次生成新的千问和 OpenAI 快照") self.ai_analysis_regenerate_button.setToolTip("依次生成新的千问、OpenAI 和豆包快照")
self.ai_analysis_regenerate_button.clicked.connect( self.ai_analysis_regenerate_button.clicked.connect(
self._regenerate_patient_ai_reports self._regenerate_patient_ai_reports
) )
@@ -5528,10 +5540,11 @@ class ReceptionPage(QWidget):
self._ai_analysis_active_model = "qwen" self._ai_analysis_active_model = "qwen"
self._ai_analysis_model_states["qwen"] = state self._ai_analysis_model_states["qwen"] = state
self._ai_analysis_model_messages["qwen"] = message self._ai_analysis_model_messages["qwen"] = message
self._ai_analysis_model_states["openai"] = ( for secondary in AI_ANALYSIS_MODELS[1:]:
state if state in {"empty", "permission"} else "waiting" self._ai_analysis_model_states[secondary] = (
) state if state in {"empty", "permission"} else "waiting"
self._ai_analysis_model_messages["openai"] = "" )
self._ai_analysis_model_messages[secondary] = ""
selector_index = self.ai_analysis_model_selector.findData("qwen") selector_index = self.ai_analysis_model_selector.findData("qwen")
if selector_index >= 0: if selector_index >= 0:
self.ai_analysis_model_selector.blockSignals(True) self.ai_analysis_model_selector.blockSignals(True)
@@ -5626,15 +5639,41 @@ class ReceptionPage(QWidget):
) )
qwen_ready = "qwen" in self._ai_analysis_payloads qwen_ready = "qwen" in self._ai_analysis_payloads
openai_state = self._ai_analysis_model_states["openai"] secondary_models = AI_ANALYSIS_MODELS[1:]
openai_message = self._ai_analysis_model_messages["openai"] secondary_states = [self._ai_analysis_model_states[key] for key in secondary_models]
if qwen_ready and openai_state == "loading": loading_labels = [
secondary_message = "千问结果已显示,OpenAI 正在生成…" AI_ANALYSIS_MODEL_LABELS[key]
elif qwen_ready and openai_state == "error": for key in secondary_models
secondary_message = f"千问结果已保留;{openai_message}" if self._ai_analysis_model_states[key] == "loading"
elif qwen_ready and openai_state == "success": ]
secondary_message = "千问与 OpenAI 均已完成,可切换对照。" failed_messages = [
elif qwen_ready and openai_state == "unsupported": self._ai_analysis_model_messages[key]
for key in secondary_models
if self._ai_analysis_model_states[key] == "error"
]
# 失败优先于进行中:已失败的模型不会因后续模型仍在生成而被隐藏。
if "error" in secondary_states:
secondary_state = "error"
elif "loading" in secondary_states:
secondary_state = "loading"
elif all(item == "success" for item in secondary_states):
secondary_state = "success"
elif all(item == "unsupported" for item in secondary_states):
secondary_state = "unsupported"
else:
secondary_state = secondary_states[0]
if qwen_ready and secondary_state == "loading":
secondary_message = f"千问结果已显示,{'、'.join(loading_labels)} 正在生成…"
elif qwen_ready and secondary_state == "error":
secondary_message = "千问结果已保留;" + ";".join(
message for message in failed_messages if message
) + (f";{'、'.join(loading_labels)} 正在生成…" if loading_labels else "")
elif qwen_ready and secondary_state == "success":
secondary_message = (
f"{'、'.join(AI_ANALYSIS_MODEL_LABELS[key] for key in AI_ANALYSIS_MODELS)}"
" 均已完成,可切换对照。"
)
elif qwen_ready and secondary_state == "unsupported":
secondary_message = "千问结果已显示;当前数据源仅支持千问分析。" secondary_message = "千问结果已显示;当前数据源仅支持千问分析。"
else: else:
secondary_message = "" secondary_message = ""
@@ -5646,7 +5685,7 @@ class ReceptionPage(QWidget):
if success and payload is not None if success and payload is not None
else "" else ""
) )
if current_snapshot_time and (openai_state == "success" or not secondary_message): if current_snapshot_time and (secondary_state == "success" or not secondary_message):
secondary_message = f"快照时间:{current_snapshot_time[:16]}" secondary_message = f"快照时间:{current_snapshot_time[:16]}"
if self._ai_analysis_regenerating: if self._ai_analysis_regenerating:
active_label = AI_ANALYSIS_MODEL_LABELS.get( active_label = AI_ANALYSIS_MODEL_LABELS.get(
@@ -5654,11 +5693,11 @@ class ReceptionPage(QWidget):
self._ai_analysis_regeneration_model or "千问", self._ai_analysis_regeneration_model or "千问",
) )
secondary_message = f"正在生成新的{active_label}快照,历史版本会保留。" secondary_message = f"正在生成新的{active_label}快照,历史版本会保留。"
openai_state = "loading" secondary_state = "loading"
elif self._ai_analysis_operation_error: elif self._ai_analysis_operation_error:
secondary_message = self._ai_analysis_operation_error secondary_message = self._ai_analysis_operation_error
openai_state = "error" secondary_state = "error"
self._set_ai_analysis_secondary_status(openai_state, secondary_message) self._set_ai_analysis_secondary_status(secondary_state, secondary_message)
self.ai_analysis_card.setProperty("analysisState", state) self.ai_analysis_card.setProperty("analysisState", state)
self.ai_analysis_card.style().unpolish(self.ai_analysis_card) self.ai_analysis_card.style().unpolish(self.ai_analysis_card)
@@ -5980,12 +6019,14 @@ class ReceptionPage(QWidget):
self._ai_analysis_payloads[model] = grouped[model][0] self._ai_analysis_payloads[model] = grouped[model][0]
self._ai_analysis_model_states[model] = "success" self._ai_analysis_model_states[model] = "success"
self._ai_analysis_model_messages[model] = "" self._ai_analysis_model_messages[model] = ""
else: elif replace or self._ai_analysis_model_states.get(model) not in {"error", "loading"}:
# 追加单个新快照时,保留其他模型尚未结束或已失败的状态与原因。
self._ai_analysis_model_states[model] = "missing" self._ai_analysis_model_states[model] = "missing"
self._ai_analysis_model_messages[model] = "" self._ai_analysis_model_messages[model] = ""
if self._ai_analysis_active_model not in self._ai_analysis_payloads: if self._ai_analysis_active_model not in self._ai_analysis_payloads:
self._ai_analysis_active_model = ( self._ai_analysis_active_model = next(
"qwen" if "qwen" in self._ai_analysis_payloads else "openai" (key for key in AI_ANALYSIS_MODELS if key in self._ai_analysis_payloads),
"qwen",
) )
selector_index = self.ai_analysis_model_selector.findData( selector_index = self.ai_analysis_model_selector.findData(
self._ai_analysis_active_model self._ai_analysis_active_model
@@ -6436,9 +6477,10 @@ class ReceptionPage(QWidget):
self._ai_analysis_model_states[model] = "success" self._ai_analysis_model_states[model] = "success"
self._ai_analysis_model_messages[model] = "" self._ai_analysis_model_messages[model] = ""
self._sync_ai_analysis_view() self._sync_ai_analysis_view()
if model == "qwen": next_model = _next_ai_analysis_model(model)
if next_model is not None:
self._request_patient_ai_generation( self._request_patient_ai_generation(
"openai", next_model,
effective_generation, effective_generation,
effective_appointment_id, effective_appointment_id,
patient_id, patient_id,
@@ -6475,9 +6517,21 @@ class ReceptionPage(QWidget):
else: else:
self._ai_analysis_model_states[model] = "error" self._ai_analysis_model_states[model] = "error"
self._ai_analysis_model_messages[model] = message self._ai_analysis_model_messages[model] = message
prefix = "千问新快照已保留;" if model == "openai" and "qwen" in self._ai_analysis_payloads else "" prefix = "千问新快照已保留;" if model != "qwen" and "qwen" in self._ai_analysis_payloads else ""
self._ai_analysis_operation_error = f"{prefix}{message}" self._ai_analysis_operation_error = f"{prefix}{message}"
self._sync_ai_analysis_view() self._sync_ai_analysis_view()
# 千问之后的某个模型失败,不阻断其余模型继续补齐;失败原因保留在该模型状态里。
next_model = _next_ai_analysis_model(model) if model != "qwen" else None
context = self._current_patient_ai_context(patient_id)
if next_model is not None and context is not None:
effective_generation, effective_appointment_id, _patient_id = context
self._request_patient_ai_generation(
next_model,
effective_generation,
effective_appointment_id,
patient_id,
settle_before_request=True,
)
def _patient_ai_generation_finished( def _patient_ai_generation_finished(
self, self,
@@ -6617,7 +6671,7 @@ class ReceptionPage(QWidget):
diagnosis_id, diagnosis_id,
): ):
return return
if model == "openai" and not self._ai_analysis_supports_models: if model != "qwen" and not self._ai_analysis_supports_models:
self._ai_analysis_model_states[model] = "unsupported" self._ai_analysis_model_states[model] = "unsupported"
self._ai_analysis_model_messages[model] = "" self._ai_analysis_model_messages[model] = ""
self._sync_ai_analysis_view() self._sync_ai_analysis_view()
@@ -6764,11 +6818,12 @@ class ReceptionPage(QWidget):
self._ai_analysis_model_messages[model] = "" self._ai_analysis_model_messages[model] = ""
self._sync_ai_analysis_view() self._sync_ai_analysis_view()
if model == "qwen": next_model = _next_ai_analysis_model(model)
if next_model is not None:
method = getattr(self.repository, "get_diagnosis_ai_analysis", None) method = getattr(self.repository, "get_diagnosis_ai_analysis", None)
if callable(method): if callable(method):
self._request_ai_analysis_model( self._request_ai_analysis_model(
"openai", next_model,
method, method,
request_generation, request_generation,
appointment_id, appointment_id,
@@ -6803,6 +6858,18 @@ class ReceptionPage(QWidget):
f"{label}分析加载失败:{friendly_error(error)}" f"{label}分析加载失败:{friendly_error(error)}"
) )
self._sync_ai_analysis_view() self._sync_ai_analysis_view()
# 与患者快照一致:千问之后的模型失败不阻断其余模型。
next_model = _next_ai_analysis_model(model) if model != "qwen" else None
method = getattr(self.repository, "get_diagnosis_ai_analysis", None)
if next_model is not None and callable(method):
self._request_ai_analysis_model(
next_model,
method,
request_generation,
appointment_id,
diagnosis_id,
settle_before_request=True,
)
def _ai_analysis_finished( def _ai_analysis_finished(
self, self,
@@ -6869,7 +6936,7 @@ class ReceptionPage(QWidget):
self._set_ai_analysis_state("error", "当前患者缺少诊单编号,无法重试。") self._set_ai_analysis_state("error", "当前患者缺少诊单编号,无法重试。")
return return
model = self._ai_analysis_active_model model = self._ai_analysis_active_model
if model == "openai" and self._ai_analysis_model_states[model] == "error": if model != "qwen" and self._ai_analysis_model_states[model] == "error":
method = getattr(self.repository, "get_diagnosis_ai_analysis", None) method = getattr(self.repository, "get_diagnosis_ai_analysis", None)
if callable(method): if callable(method):
self._request_ai_analysis_model( self._request_ai_analysis_model(
+3
View File
@@ -875,6 +875,7 @@ class ShellWindow(QMainWindow):
""" """
logout_requested = Signal() logout_requested = Signal()
close_requested = Signal()
video_requested = Signal(dict) video_requested = Signal(dict)
page_changed = Signal(str) page_changed = Signal(str)
update_check_requested = Signal() update_check_requested = Signal()
@@ -2237,6 +2238,8 @@ class ShellWindow(QMainWindow):
def closeEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual def closeEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual
self.chat_notifications.stop() self.chat_notifications.stop()
super().closeEvent(event) super().closeEvent(event)
if event.isAccepted():
self.close_requested.emit()
def _open_chat_notification(self, notification: ChatNotification) -> None: def _open_chat_notification(self, notification: ChatNotification) -> None:
"""Take the doctor where the notification's work actually lives.""" """Take the doctor where the notification's work actually lives."""
+13 -1
View File
@@ -381,9 +381,21 @@ def run_async(
worker = Worker(function, *args, **kwargs) worker = Worker(function, *args, **kwargs)
_RUNNING_WORKERS.add(worker) _RUNNING_WORKERS.add(worker)
session_handler = _AUTHENTICATION_EXPIRED_HANDLER
def dispatch_error(error: Exception, _traceback: str) -> None:
# An earlier session's in-flight failure cannot dismiss a newly
# authenticated shell or open an error dialog over its login window.
if (
isinstance(error, AuthenticationExpiredError)
and session_handler is not _AUTHENTICATION_EXPIRED_HANDLER
):
return
_dispatch_async_error(error, on_error)
if on_success is not None: if on_success is not None:
worker.signals.result.connect(on_success) worker.signals.result.connect(on_success)
worker.signals.error.connect(lambda exc, _tb: _dispatch_async_error(exc, on_error)) worker.signals.error.connect(dispatch_error)
if on_finished is not None: if on_finished is not None:
worker.signals.finished.connect(on_finished) worker.signals.finished.connect(on_finished)
worker.signals.finished.connect(lambda: _RUNNING_WORKERS.discard(worker)) worker.signals.finished.connect(lambda: _RUNNING_WORKERS.discard(worker))
+8 -1
View File
@@ -21,6 +21,8 @@ SYNC_TIMEOUT_SECONDS = 45.0
_WORKER_SLOTS = BoundedSemaphore(4) _WORKER_SLOTS = BoundedSemaphore(4)
_CANCEL_SLOTS = BoundedSemaphore(4) _CANCEL_SLOTS = BoundedSemaphore(4)
_ACTIONS = frozenset({"summary", "followup", "reply"}) _ACTIONS = frozenset({"summary", "followup", "reply"})
# 千问是服务端各任务的默认模型;医生在面板中切换后才显式携带。
_MODELS = frozenset({"qwen", "openai", "doubao"})
def _integer(value: Any, *, minimum: int) -> int | None: def _integer(value: Any, *, minimum: int) -> int | None:
@@ -104,6 +106,7 @@ class _RequestError(Exception):
class _Job: class _Job:
identity: dict[str, Any] identity: dict[str, Any]
action: str action: str
model: str | None = None
cancelled: Event = field(default_factory=Event) cancelled: Event = field(default_factory=Event)
completed: bool = False completed: bool = False
succeeded: bool = False succeeded: bool = False
@@ -193,8 +196,11 @@ class ImAiController:
return True return True
if event != "im-ai-request" or message["requestId"] in self._seen: if event != "im-ai-request" or message["requestId"] in self._seen:
return False return False
model = message.get("model")
if model is not None and (not isinstance(model, str) or model not in _MODELS):
return False
self._seen.append(message["requestId"]) self._seen.append(message["requestId"])
job = _Job(identity, message["action"]) job = _Job(identity, message["action"], model)
if self._running is not None: if self._running is not None:
self._cancel(self._running) self._cancel(self._running)
self._current = job self._current = job
@@ -269,6 +275,7 @@ class ImAiController:
events = self.repository.stream_diagnosis_ai( events = self.repository.stream_diagnosis_ai(
self.diagnosis_id, prompt, task=task, self.diagnosis_id, prompt, task=task,
request_id=job.identity["requestId"], cancelled=job.cancelled.is_set, request_id=job.identity["requestId"], cancelled=job.cancelled.is_set,
**({"model": job.model} if job.model not in (None, "qwen") else {}),
) )
try: try:
for event in events: for event in events:
@@ -20,7 +20,7 @@ from ..core.transcript_text import simplified_transcript
MAX_IMAGE_BYTES = 10 * 1024 * 1024 MAX_IMAGE_BYTES = 10 * 1024 * 1024
_SLOTS = BoundedSemaphore(4) _SLOTS = BoundedSemaphore(4)
_MODELS = {"qwen", "openai"} _MODELS = {"qwen", "openai", "doubao"}
_BUSINESS_MESSAGES = { _BUSINESS_MESSAGES = {
"GPT 模型接口配置异常,请管理员检查 Dify 中的模型 API 地址。": "GPT 模型接口配置异常,请管理员检查 Dify 中的模型 API 地址。", "GPT 模型接口配置异常,请管理员检查 Dify 中的模型 API 地址。": "GPT 模型接口配置异常,请管理员检查 Dify 中的模型 API 地址。",
"千问 模型接口配置异常,请管理员检查 Dify 中的模型 API 地址。": "千问 模型接口配置异常,请管理员检查 Dify 中的模型 API 地址。", "千问 模型接口配置异常,请管理员检查 Dify 中的模型 API 地址。": "千问 模型接口配置异常,请管理员检查 Dify 中的模型 API 地址。",
+1 -1
View File
@@ -255,7 +255,7 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
def analyzeTongueScreenshotModel(self, request_id: str, data_url: str, model: str) -> None: # noqa: N802 def analyzeTongueScreenshotModel(self, request_id: str, data_url: str, model: str) -> None: # noqa: N802
if (not isinstance(request_id, str) or len(request_id) != 36 if (not isinstance(request_id, str) or len(request_id) != 36
or not isinstance(data_url, str) or len(data_url) > 14 * 1024 * 1024 or not isinstance(data_url, str) or len(data_url) > 14 * 1024 * 1024
or not isinstance(model, str) or model not in {"qwen", "openai"}): or not isinstance(model, str) or model not in {"qwen", "openai", "doubao"}):
return return
self._callback({"source": "doctor-call", "event": "tongue-screenshot-analyze", self._callback({"source": "doctor-call", "event": "tongue-screenshot-analyze",
"requestId": request_id, "dataUrl": data_url, "model": model}) "requestId": request_id, "dataUrl": data_url, "model": model})
+46 -10
View File
@@ -367,14 +367,31 @@ def test_prescription_action_with_write_permission_but_without_ai_grant_is_block
dialog.close() dialog.close()
def test_prescription_action_opens_editor_and_forces_current_diagnosis_ownership( @pytest.mark.parametrize("esign_enabled", [False, True])
def test_prescription_action_opens_upload_once_with_current_diagnosis_ownership(
application: QApplication, application: QApplication,
immediate_async: None, immediate_async: None,
monkeypatch: pytest.MonkeyPatch, monkeypatch: pytest.MonkeyPatch,
esign_enabled: bool,
) -> None: ) -> None:
created: list[dict[str, Any]] = [] created: list[dict[str, Any]] = []
editor_seeds: list[dict[str, Any]] = [] editor_seeds: list[dict[str, Any]] = []
upload_receipts: list[dict[str, Any]] = []
current_user = {"id": 12, "name": "甄医生"} current_user = {"id": 12, "name": "甄医生"}
receipt = {
"id": 9001,
"esign": {
"enabled": esign_enabled,
"required": esign_enabled,
"environment": "sandbox",
"status": "pending" if esign_enabled else "legacy",
"can_sign": False,
"can_download": False,
"review_submitted_at": 0,
"awaiting_upload": True,
"can_submit_for_review": True,
},
}
class Repository: class Repository:
def get_diagnosis_detail( def get_diagnosis_detail(
@@ -419,7 +436,10 @@ def test_prescription_action_opens_editor_and_forces_current_diagnosis_ownership
def create_prescription(self, prescription: dict[str, Any]) -> dict[str, Any]: def create_prescription(self, prescription: dict[str, Any]) -> dict[str, Any]:
created.append(prescription) created.append(prescription)
return {"id": 9001, **prescription} return receipt
def submit_prescription_for_review(self, prescription_id: int) -> None:
raise AssertionError(f"uploading {prescription_id} requires a separate click")
def list_prescriptions_by_diagnosis( def list_prescriptions_by_diagnosis(
self, self,
@@ -427,10 +447,6 @@ def test_prescription_action_opens_editor_and_forces_current_diagnosis_ownership
) -> list[dict[str, Any]]: ) -> list[dict[str, Any]]:
return [{"id": 9001, "diagnosis_id": diagnosis_id, "sn": "RX-9001"}] return [{"id": 9001, "diagnosis_id": diagnosis_id, "sn": "RX-9001"}]
class FakeSignal:
def connect(self, _slot: Any) -> None:
return None
class FakeEditor: class FakeEditor:
def __init__( def __init__(
self, self,
@@ -441,9 +457,12 @@ def test_prescription_action_opens_editor_and_forces_current_diagnosis_ownership
editor_seeds.append(seed) editor_seeds.append(seed)
assert kwargs["mode"] == "add" assert kwargs["mode"] == "add"
assert kwargs["current_user"] == current_user assert kwargs["current_user"] == current_user
self.diagnosis_requested = FakeSignal() self.save_draft = kwargs["save_draft"]
self.saved_draft = None
def exec(self) -> Any: def exec(self) -> Any:
if esign_enabled:
self.saved_draft = self.save_draft(self.payload())
return ai_consult_module.QDialog.DialogCode.Accepted return ai_consult_module.QDialog.DialogCode.Accepted
@staticmethod @staticmethod
@@ -452,17 +471,32 @@ def test_prescription_action_opens_editor_and_forces_current_diagnosis_ownership
"diagnosis_id": 999, "diagnosis_id": 999,
"appointment_id": 998, "appointment_id": 998,
"case_record": {"forged": True}, "case_record": {"forged": True},
"patient_id": 997,
"phone": "13900000000",
"doctor_name": "甄医生", "doctor_name": "甄医生",
"herbs": [{"name": "茯苓", "dosage": 10, "unit": "g"}], "herbs": [{"name": "茯苓", "dosage": 10, "unit": "g"}],
} }
from doctor_workstation.ui.dialogs import prescription as prescription_module class FakeUploadDialog:
def __init__(self, _repository: Any, prescription: dict[str, Any], **_kwargs: Any) -> None:
assert prescription is receipt
self.state = prescription["esign"]
upload_receipts.append(prescription)
def exec(self) -> None:
return None
from doctor_workstation.ui.dialogs import (
prescription as prescription_module,
prescription_esign as prescription_esign_module,
)
monkeypatch.setattr( monkeypatch.setattr(
prescription_module, prescription_module,
"PrescriptionEditorDialog", "PrescriptionEditorDialog",
FakeEditor, FakeEditor,
) )
monkeypatch.setattr(prescription_esign_module, "PrescriptionEsignDialog", FakeUploadDialog)
host = QWidget() host = QWidget()
host.current_user = current_user # type: ignore[attr-defined] host.current_user = current_user # type: ignore[attr-defined]
dialog = AiConsultDialog( dialog = AiConsultDialog(
@@ -484,7 +518,9 @@ def test_prescription_action_opens_editor_and_forces_current_diagnosis_ownership
assert editor_seeds[0]["diagnosis_id"] == 501 assert editor_seeds[0]["diagnosis_id"] == 501
assert editor_seeds[0]["appointment_id"] == 801 assert editor_seeds[0]["appointment_id"] == 801
assert editor_seeds[0]["herbs"][0]["name"] == "茯苓" assert editor_seeds[0]["herbs"][0]["name"] == "茯苓"
assert created and created[0]["diagnosis_id"] == 501 assert len(created) == 1
assert upload_receipts == [receipt]
assert created[0]["diagnosis_id"] == 501
assert created[0]["appointment_id"] == 801 assert created[0]["appointment_id"] == 801
assert created[0]["case_record"] == {"chief_complaint": "性功能下降"} assert created[0]["case_record"] == {"chief_complaint": "性功能下降"}
assert created[0]["patient_id"] == 301 assert created[0]["patient_id"] == 301
@@ -495,7 +531,7 @@ def test_prescription_action_opens_editor_and_forces_current_diagnosis_ownership
browser.toPlainText() browser.toPlainText()
for browser in dialog.findChildren(QTextBrowser, "AiConsultBubbleText") for browser in dialog.findChildren(QTextBrowser, "AiConsultBubbleText")
] ]
assert any("处方已开具并提交审核" in body for body in bodies) assert any("处方草稿已保存" in body and "上传处方" in body for body in bodies)
dialog.close() dialog.close()
host.close() host.close()
+20
View File
@@ -98,6 +98,26 @@ def test_invalid_identity_or_action_cannot_read_patient_context(changes):
assert not repository.sync_calls and not repository.stream_calls assert not repository.sync_calls and not repository.stream_calls
@pytest.mark.parametrize("model,forwarded", [(None, None), ("qwen", None), ("openai", "openai"), ("doubao", "doubao")])
def test_selected_model_is_forwarded_only_when_not_the_task_default(model, forwarded):
repository = Repository()
service = controller(repository)
assert service.handle(request(service, **({} if model is None else {"model": model})))
assert service.wait()
assert service.take_result()["status"] == "success"
_diagnosis_id, _prompt, options = repository.stream_calls[0]
assert options.get("model") == forwarded
assert ("model" in options) is (forwarded is not None)
@pytest.mark.parametrize("model", ["deepseek", "", "Doubao", 1, ["doubao"]])
def test_unknown_model_cannot_start_a_request(model):
repository = Repository()
service = controller(repository)
assert not service.handle(request(service, model=model))
assert not repository.sync_calls and not repository.stream_calls
def test_permission_default_denied_and_each_host_has_unique_session(): def test_permission_default_denied_and_each_host_has_unique_session():
repository = Repository() repository = Repository()
disabled = im_ai.ImAiController( disabled = im_ai.ImAiController(
+117 -3
View File
@@ -2,8 +2,11 @@
from __future__ import annotations from __future__ import annotations
from concurrent.futures import ThreadPoolExecutor
from datetime import date from datetime import date
from pathlib import Path from pathlib import Path
from threading import Event
from time import time
from typing import Any from typing import Any
import pytest import pytest
@@ -11,6 +14,7 @@ import pytest
from doctor_workstation.core.errors import ( from doctor_workstation.core.errors import (
ApiBusinessError, ApiBusinessError,
ApiProtocolError, ApiProtocolError,
ApiTransportError,
AuthenticationExpiredError, AuthenticationExpiredError,
RepositoryNotFoundError, RepositoryNotFoundError,
) )
@@ -415,6 +419,8 @@ class _StubApiClient:
self.token = "" self.token = ""
self.get_calls: list[tuple[str, dict[str, Any]]] = [] self.get_calls: list[tuple[str, dict[str, Any]]] = []
self.post_calls: list[tuple[str, dict[str, Any]]] = [] self.post_calls: list[tuple[str, dict[str, Any]]] = []
self.deadline = int(time()) + 3600
self.post_tokens: list[str] = []
def set_token(self, token: str) -> None: def set_token(self, token: str) -> None:
"""Retain the synthetic login token.""" """Retain the synthetic login token."""
@@ -445,13 +451,17 @@ class _StubApiClient:
return {"appointment": {"id": params["id"]}, "doctor_notes": []} return {"appointment": {"id": params["id"]}, "doctor_notes": []}
return {"lists": [], "count": 0, "extend": {}} return {"lists": [], "count": 0, "extend": {}}
def post(self, endpoint: str, payload: dict[str, Any] | None = None) -> Any: def post(self, endpoint: str, payload: dict[str, Any] | None = None, *,
headers: dict[str, str] | None = None, timeout: float | None = None) -> Any:
"""Return synthetic mutation data and record the exact JSON payload.""" """Return synthetic mutation data and record the exact JSON payload."""
body = dict(payload or {}) body = dict(payload or {})
self.post_calls.append((endpoint, body)) self.post_calls.append((endpoint, body))
self.post_tokens.append((headers or {}).get("token", self.token))
if endpoint == "login/account": if endpoint == "login/account":
return {"token": "remote-token", "is_paw": 1} return {"token": "remote-token", "is_paw": 1, "desktop_expires_at": self.deadline}
if endpoint == "login/desktopHeartbeat":
return {"desktop_expires_at": self.deadline}
if endpoint == "tcm.prescriptionLibrary/add": if endpoint == "tcm.prescriptionLibrary/add":
return {"id": 9} return {"id": 9}
if endpoint == "tcm.diagnosis/getCallSignature": if endpoint == "tcm.diagnosis/getCallSignature":
@@ -473,6 +483,8 @@ def test_remote_repository_uses_all_confirmed_endpoints_without_network() -> Non
repository = RemoteDoctorRepository(client) # type: ignore[arg-type] repository = RemoteDoctorRepository(client) # type: ignore[arg-type]
session = repository.login(" doctor ", "secret") session = repository.login(" doctor ", "secret")
assert client.post_calls == [("login/account", {"account": "doctor", "password": "secret", "terminal": 21})]
assert session.desktop_expires_at == client.deadline
assert session.token == "remote-token" assert session.token == "remote-token"
assert repository.get_current_user().name == "远程医生" assert repository.get_current_user().name == "远程医生"
assert [path for path, _ in client.get_calls].count("auth.admin/mySelf") == 1 assert [path for path, _ in client.get_calls].count("auth.admin/mySelf") == 1
@@ -588,6 +600,8 @@ def test_remote_login_persists_only_after_session_validation(
) )
assert saved == [] assert saved == []
assert client.post_calls[-1] == ("login/logout", {})
assert client.post_tokens[-1] == "remote-token"
assert client.token == "" assert client.token == ""
assert store.load_token() is None assert store.load_token() is None
@@ -604,6 +618,10 @@ def test_remote_login_applies_remember_account_to_token_store(tmp_path: Path) ->
assert store.load_token(scope=client.base_url) == "remote-token" assert store.load_token(scope=client.base_url) == "remote-token"
repository.logout() repository.logout()
assert client.post_calls[-1] == ("login/logout", {})
assert client.post_tokens[-1] == "remote-token"
assert store.load_token() is None
assert store.load_account() == "doctor"
repository.login("doctor", "secret", remember_account=False) repository.login("doctor", "secret", remember_account=False)
assert store.load_account() is None assert store.load_account() is None
assert store.load_token(scope=client.base_url) == "remote-token" assert store.load_token(scope=client.base_url) == "remote-token"
@@ -614,7 +632,8 @@ def test_expired_persisted_token_is_removed_during_restore(tmp_path: Path) -> No
client = _FailingProfileClient(AuthenticationExpiredError("expired", code=-1)) client = _FailingProfileClient(AuthenticationExpiredError("expired", code=-1))
store = TokenStore(tmp_path / "credentials.json", keyring_backend=None) store = TokenStore(tmp_path / "credentials.json", keyring_backend=None)
store.save_token("expired-token", account="doctor", scope=client.base_url) store.save_token("expired-token", account="doctor", scope=client.base_url,
desktop_expires_at=client.deadline)
repository = RemoteDoctorRepository(client, store) # type: ignore[arg-type] repository = RemoteDoctorRepository(client, store) # type: ignore[arg-type]
with pytest.raises(AuthenticationExpiredError): with pytest.raises(AuthenticationExpiredError):
@@ -625,6 +644,101 @@ def test_expired_persisted_token_is_removed_during_restore(tmp_path: Path) -> No
assert store.load_account() == "doctor" assert store.load_account() == "doctor"
@pytest.mark.parametrize("deadline", [0, 1])
def test_old_web_or_past_cutoff_token_is_discarded_without_network(tmp_path: Path, deadline: int) -> None:
client = _StubApiClient()
store = TokenStore(tmp_path / "credentials.json", keyring_backend=None)
store.save_token("saved-token", account="doctor", scope=client.base_url, desktop_expires_at=deadline)
repository = RemoteDoctorRepository(client, store) # type: ignore[arg-type]
with pytest.raises(AuthenticationExpiredError):
repository.restore_session()
repository.logout()
assert client.post_calls == client.get_calls == []
assert store.load_account() == "doctor"
assert store.load_token() is None
def test_restore_requires_live_heartbeat_and_keeps_earlier_cutoff(tmp_path: Path) -> None:
client = _StubApiClient()
store = TokenStore(tmp_path / "credentials.json", keyring_backend=None)
store.save_token("desktop-token", scope=client.base_url, desktop_expires_at=client.deadline - 10)
repository = RemoteDoctorRepository(client, store) # type: ignore[arg-type]
session = repository.restore_session()
assert session and session.desktop_expires_at == client.deadline - 10
assert client.post_calls == [("login/desktopHeartbeat", {})]
assert client.post_tokens == ["desktop-token"]
assert client.get_calls == [("auth.admin/mySelf", {})]
def test_network_loss_during_restore_preserves_token_for_retry(tmp_path: Path, monkeypatch: Any) -> None:
client = _StubApiClient()
store = TokenStore(tmp_path / "credentials.json", keyring_backend=None)
store.save_token("desktop-token", scope=client.base_url, desktop_expires_at=client.deadline)
repository = RemoteDoctorRepository(client, store) # type: ignore[arg-type]
def offline(*_args: Any, **_kwargs: Any) -> Any:
raise ApiTransportError("offline")
monkeypatch.setattr(client, "post", offline)
with pytest.raises(ApiTransportError):
repository.restore_session()
assert client.token == ""
assert client.get_calls == []
assert store.load_token() == "desktop-token"
def test_logout_after_network_loss_clears_credentials_and_never_retries(tmp_path: Path, monkeypatch: Any) -> None:
client = _StubApiClient()
store = TokenStore(tmp_path / "credentials.json", keyring_backend=None)
repository = RemoteDoctorRepository(client, store) # type: ignore[arg-type]
repository.login("doctor", "secret", remember_account=True)
attempts = []
def offline(endpoint: str, _payload: dict, **kwargs: Any) -> Any:
attempts.append((endpoint, kwargs["headers"]["token"]))
raise ApiTransportError("offline")
monkeypatch.setattr(client, "post", offline)
repository.logout()
repository.logout()
assert attempts == [("login/logout", "remote-token")]
assert client.token == ""
assert store.load_token() is None
assert store.load_account() == "doctor"
def test_app_close_during_login_retires_issued_token_before_transport_close(tmp_path: Path, monkeypatch: Any) -> None:
client = _StubApiClient()
store = TokenStore(tmp_path / "credentials.json", keyring_backend=None)
repository = RemoteDoctorRepository(client, store) # type: ignore[arg-type]
profile_started = Event()
finish_profile = Event()
get_profile = client.get
closes = []
def pending_profile(endpoint: str) -> Any:
profile_started.set()
assert finish_profile.wait(3)
return get_profile(endpoint)
monkeypatch.setattr(client, "get", pending_profile)
monkeypatch.setattr(client, "close", lambda: closes.append(client.token), raising=False)
with ThreadPoolExecutor(max_workers=2) as pool:
login = pool.submit(repository.login, "doctor", "secret", remember_account=True)
assert profile_started.wait(3)
shutdown = pool.submit(repository.close)
finish_profile.set()
assert login.result(timeout=3).token == "remote-token"
shutdown.result(timeout=3)
assert store.load_account() == "doctor"
assert store.load_token() is None
assert closes == [""]
assert client.post_calls[-1] == ("login/logout", {})
assert client.post_tokens[-1] == "remote-token"
def test_restore_never_sends_token_to_a_different_api_scope(tmp_path: Path) -> None: def test_restore_never_sends_token_to_a_different_api_scope(tmp_path: Path) -> None:
"""Changing the configured server invalidates automatic token reuse.""" """Changing the configured server invalidates automatic token reuse."""
+17 -11
View File
@@ -81,13 +81,13 @@ def _detail(appointment_id: int, patient_id: int, diagnosis_id: int) -> dict[str
def _snapshot(model: str, version: int, stamp: str) -> dict[str, Any]: def _snapshot(model: str, version: int, stamp: str) -> dict[str, Any]:
label = "OpenAI" if model == "openai" else "千问" label = {"openai": "OpenAI", "doubao": "豆包"}.get(model, "千问")
return { return {
"id": version * 10 + (2 if model == "openai" else 1), "id": version * 10 + {"openai": 2, "doubao": 3}.get(model, 1),
"patient_id": 301, "patient_id": 301,
"model_key": model, "model_key": model,
"model_label": label, "model_label": label,
"model_name": "gpt-demo" if model == "openai" else "qwen-demo", "model_name": {"openai": "gpt-demo", "doubao": "doubao-demo"}.get(model, "qwen-demo"),
"version": version, "version": version,
"generated_at": stamp, "generated_at": stamp,
"report": { "report": {
@@ -211,7 +211,7 @@ def test_saved_history_is_rendered_without_automatic_generation(
page.close() page.close()
def test_empty_database_and_manual_refresh_append_qwen_then_openai( def test_empty_database_and_manual_refresh_append_every_model_in_order(
application: QApplication, application: QApplication,
immediate_async: None, immediate_async: None,
) -> None: ) -> None:
@@ -254,18 +254,20 @@ def test_empty_database_and_manual_refresh_append_qwen_then_openai(
page._select_record(detail["appointment"]) page._select_record(detail["appointment"])
application.processEvents() application.processEvents()
assert repository.calls == [("list", 302), ("generate", "qwen"), ("generate", "openai")] assert repository.calls == [
assert [len(page._ai_analysis_histories[key]) for key in ("qwen", "openai")] == [1, 1] ("list", 302), ("generate", "qwen"), ("generate", "openai"), ("generate", "doubao"),
]
assert [len(page._ai_analysis_histories[key]) for key in ("qwen", "openai", "doubao")] == [1, 1, 1]
page.ai_analysis_regenerate_button.click() page.ai_analysis_regenerate_button.click()
application.processEvents() application.processEvents()
assert repository.calls[-2:] == [("generate", "qwen"), ("generate", "openai")] assert repository.calls[-3:] == [("generate", "qwen"), ("generate", "openai"), ("generate", "doubao")]
assert [len(page._ai_analysis_histories[key]) for key in ("qwen", "openai")] == [2, 2] assert [len(page._ai_analysis_histories[key]) for key in ("qwen", "openai", "doubao")] == [2, 2, 2]
page.close() page.close()
def test_openai_failure_keeps_new_qwen_snapshot( def test_openai_failure_keeps_new_qwen_snapshot_and_still_generates_doubao(
application: QApplication, application: QApplication,
immediate_async: None, immediate_async: None,
) -> None: ) -> None:
@@ -281,7 +283,7 @@ def test_openai_failure_keeps_new_qwen_snapshot(
def generate_patient_ai_report(self, patient_id: int, *, model: str) -> dict[str, Any]: def generate_patient_ai_report(self, patient_id: int, *, model: str) -> dict[str, Any]:
if model == "openai": if model == "openai":
raise RuntimeError("OpenAI 暂时不可用") raise RuntimeError("OpenAI 暂时不可用")
row = _snapshot("qwen", 1, "2026-08-14 10:30:00") row = _snapshot(model, 1, "2026-08-14 10:30:00")
row["patient_id"] = patient_id row["patient_id"] = patient_id
return { return {
"patient_id": patient_id, "patient_id": patient_id,
@@ -305,7 +307,11 @@ def test_openai_failure_keeps_new_qwen_snapshot(
assert page.ai_summary_label.text() == "千问第 1 版诊断建议" assert page.ai_summary_label.text() == "千问第 1 版诊断建议"
assert len(page._ai_analysis_histories["qwen"]) == 1 assert len(page._ai_analysis_histories["qwen"]) == 1
assert page._ai_analysis_model_states["openai"] == "error" assert page._ai_analysis_model_states["openai"] == "error"
assert "千问新快照已保留" in page.ai_analysis_secondary_status.text() # 第二个模型失败不阻断第三个模型补齐。
assert page._ai_analysis_model_states["doubao"] == "success"
assert len(page._ai_analysis_histories["doubao"]) == 1
assert "千问结果已保留" in page.ai_analysis_secondary_status.text()
assert "OpenAI新快照生成失败" in page.ai_analysis_secondary_status.text()
page.close() page.close()
+35
View File
@@ -528,6 +528,10 @@ def test_order_action_matrix_requires_exact_permissions_and_states(
"ddcode", "ddcode",
"withdraw", "withdraw",
] ]
for submission_time, review_ready in ((0, False), (1_760_000_000, False), (1_760_000_000, True)):
current = {**pending, "review_submitted_at": submission_time, "can_review_prescription": review_ready}
available = {key for key, _label, _danger in workspace._available_actions(current)}
assert ("audit_prescription" in available) is review_ready
assert [key for key, _label, _danger in workspace._available_actions(shipped)] == [ assert [key for key, _label, _danger in workspace._available_actions(shipped)] == [
"revoke_pay_audit", "revoke_pay_audit",
"ddcode", "ddcode",
@@ -618,6 +622,37 @@ def test_order_approval_routes_unsigned_prescription_before_audit(
application.processEvents() application.processEvents()
@pytest.mark.parametrize("review_signed", [False, True])
def test_order_approval_requires_pharmacist_signature_when_enabled(
application: QApplication,
immediate_async: None,
monkeypatch: pytest.MonkeyPatch,
review_signed: bool,
) -> None:
signed_at = 1_760_000_000
status = {
"enabled": True, "required": True, "environment": "sandbox", "status": "signed",
"can_sign": False, "can_download": True, "review_submitted_at": signed_at - 10,
"review_required": True, "review_signature_time": signed_at if review_signed else 0,
"can_review_prescription": False,
}
row = {
"id": 70, "prescription_id": 52, "prescription_audit_status": 0, "fulfillment_status": 1,
"review_submitted_at": signed_at - 10, "can_review_prescription": True,
}
approved = []
repository = SimpleNamespace(get_prescription_esign_status=lambda _id: status)
page = PatientsPage(repository, PermissionSet(["tcm.prescriptionOrder/auditPrescription"]))
monkeypatch.setattr(page, "_submit_order_audit", lambda order_id, **_kwargs: approved.append(order_id))
monkeypatch.setattr(QInputDialog, "getItem", staticmethod(lambda *_args, **_kwargs: ("通过", True)))
page._handle_order_action("audit_prescription", row)
assert approved == ([70] if review_signed else [])
if not review_signed:
assert "管理后台" in page.order_workspace.banner.label.text()
page.close()
application.processEvents()
def test_shell_uses_demo_session_menu_and_fits_minimum_window( def test_shell_uses_demo_session_menu_and_fits_minimum_window(
application: QApplication, application: QApplication,
immediate_async: None, immediate_async: None,
+255 -3
View File
@@ -13,8 +13,8 @@ os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
import httpx import httpx
import pytest import pytest
from PySide6.QtCore import Qt, Signal from PySide6.QtCore import QBuffer, QIODevice, Qt, Signal
from PySide6.QtGui import QDesktopServices from PySide6.QtGui import QColor, QDesktopServices, QImage
from PySide6.QtTest import QTest from PySide6.QtTest import QTest
from PySide6.QtWidgets import QApplication, QDialog, QFileDialog, QLineEdit, QWidget from PySide6.QtWidgets import QApplication, QDialog, QFileDialog, QLineEdit, QWidget
@@ -714,7 +714,9 @@ def test_authentication_stays_embedded_and_only_server_readiness_can_sign(
) )
dialog = esign_module.PrescriptionEsignDialog(repository, {"id": 7, "esign": state()}) dialog = esign_module.PrescriptionEsignDialog(repository, {"id": 7, "esign": state()})
dialog.show() dialog.show()
assert [label.text() for label in dialog.step_labels] == ["处方草稿已保存", "验证医生身份", "签名并完成"] assert [label.text() for label in dialog.step_labels if not label.isHidden()] == [
"保存草稿", "验证医生身份", "医生签署",
]
assert dialog.start_button.isEnabled() assert dialog.start_button.isEnabled()
assert not dialog.sign_button.isVisible() assert not dialog.sign_button.isVisible()
dialog.start_button.click() dialog.start_button.click()
@@ -896,6 +898,75 @@ def test_signing_and_detail_display_archived_issue_and_signature_times(
detail.close() detail.close()
def test_verified_pharmacist_updates_both_copies_signing_steps_and_log(
immediate: None, tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
) -> None:
repository = Repository()
repository.status = state(
"signed", review_required=True, signature_time=1795000007, signature_time_source="tsa",
)
detail = prescription_module.PrescriptionDetailDialog({"id": 7}, repository=repository)
signing = esign_module.PrescriptionEsignDialog(repository, {"id": 7})
assert "待药师签署" in detail.esign_banner.label.text()
assert "待药师签署" in signing.status_label.text()
assert signing.review_step_label.accessibleDescription() == "当前步骤"
assert not signing.review_step_label.isHidden() and signing.refresh_button.isEnabled()
assert "管理后台" in signing.banner.label.text()
assert "审核药师" not in detail.user_document.toPlainText()
detail._saved_original = signing._saved_original = tmp_path / "doctor-only.pdf"
image = QImage(160, 60, QImage.Format.Format_ARGB32)
image.fill(QColor("red"))
buffer = QBuffer()
assert buffer.open(QIODevice.OpenModeFlag.WriteOnly) and image.save(buffer, "PNG")
signature = "data:image/png;base64," + bytes(buffer.data().toBase64()).decode("ascii")
repository.status.update(
doctor_signer_name="签名医生",
review_signer_name="张药师",
review_signature_time=1795000017,
review_signature=signature,
signing_log=[
{"event": "doctor_signed", "time": 1795000007, "source": "tsa",
"label": "医生已签署", "actor_name": "签名医生"},
{"event": "pharmacist_signed", "time": 1795000017, "source": "tsa",
"label": "药师已签署", "actor_name": "张药师", "message": "<b>签章验签成功</b>"},
{"event": "invalid", "time": -1, "source": "system", "label": "无效记录"},
],
)
detail.refresh_esign()
signing.refresh()
assert signing.review_step_label.accessibleDescription() == "已完成"
assert "药师签署时间:2026-11-18 19:06:57(北京时间 · 可信时间戳)" in signing.signature_time_label.text()
assert "医生与药师已签署" in detail.esign_banner.label.text()
assert detail._saved_original is None and signing._saved_original is None
assert detail.tabs.tabText(1) == "处方联"
for document in (detail.document, detail.user_document):
assert "审核药师" in document.toPlainText()
assert "签名医生" in document.toPlainText()
assert f'src="{signature}"' in document.toHtml()
log_views = []
monkeypatch.setattr(
esign_module.SigningLogDialog, "exec", lambda dialog: log_views.append(dialog.entries.toPlainText()),
)
detail.signing_log_button.click()
signing.signing_log_button.click()
assert len(log_views) == 2 and log_views[0] == log_views[1]
assert "医生已签署 · 签名医生" in log_views[0]
assert "药师已签署 · 张药师" in log_views[0]
assert "2026-11-18 19:06:57(北京时间 · 可信时间戳)" in log_views[0]
assert "<b>签章验签成功</b>" in log_views[0]
assert "无效记录" not in log_views[0]
repository.status["review_signature"] = "https://example.test/forged.png"
detail.refresh_esign()
for document in (detail.document, detail.user_document):
assert "张药师" in document.toPlainText()
assert "forged.png" not in document.toHtml()
detail.close()
signing.close()
def test_download_validates_original_and_hash_before_writing( def test_download_validates_original_and_hash_before_writing(
immediate: None, tmp_path: Path immediate: None, tmp_path: Path
) -> None: ) -> None:
@@ -1124,6 +1195,187 @@ def test_reviewer_without_signing_authority_gets_doctor_instruction(
page.close() page.close()
@pytest.mark.parametrize("previously_signed", [False, True])
def test_issued_prescription_requires_upload_and_verified_doctor_signature_for_audit(
immediate: None, monkeypatch: pytest.MonkeyPatch, previously_signed: bool,
) -> None:
signed = state("signed", review_required=False)
pending = state("pending", review_required=False, can_sign=True)
upload_attempts = []
audit_calls = []
row = {
"id": 7, "audit_status": 0, "esign": signed if previously_signed else pending,
"review_submitted_at": 0, "can_review_prescription": False,
}
def upload(prescription_id: int) -> dict[str, Any]:
upload_attempts.append(prescription_id)
if len(upload_attempts) == 1:
raise ApiBusinessError("上传失败,请重试")
receipt = {"review_submitted_at": 1_760_000_000, "can_submit_for_review": False}
row.update(receipt)
row["can_review_prescription"] = previously_signed
return receipt
def repository(owner: bool) -> Any:
def status() -> dict[str, Any]:
awaiting_upload = row["review_submitted_at"] == 0
return {
**row["esign"], "review_submitted_at": row["review_submitted_at"],
"awaiting_upload": awaiting_upload, "can_submit_for_review": owner and awaiting_upload,
"can_review_prescription": row["can_review_prescription"],
}
return SimpleNamespace(
list_prescriptions=lambda **_filters: {"lists": [Prescription.from_dict({**row, "esign": status()})], "count": 1},
get_prescription_esign_status=lambda _id: status(),
submit_prescription_for_review=upload,
audit_prescription=lambda prescription_id, **audit: audit_calls.append((prescription_id, audit)),
)
def approve(dialog: Any) -> int:
dialog._choose("approve")
return dialog.result()
monkeypatch.setattr(page_module, "show_toast", lambda *_args: None)
monkeypatch.setattr(page_module.AuditPrescriptionDialog, "exec", approve)
doctor = page_module.PrescriptionsPage(repository(True), PermissionSet("cf.prescription/edit"))
reviewer = page_module.PrescriptionsPage(repository(False), PermissionSet("cf.prescription/audit"))
doctor.refresh()
reviewer.refresh()
assert page_module.prescription_status(doctor.table.current_data()) == ("待上传处方", "warning")
assert doctor.audit_button.isHidden()
assert reviewer.audit_button.isHidden()
assert not reviewer.audit_button.isEnabled()
assert reviewer.upload_button.isHidden()
reviewer._audit_selected()
assert not audit_calls
upload_button = doctor.upload_button
assert upload_button.isEnabled() and not upload_button.isHidden()
upload_button.click()
assert "上传失败" in doctor.banner.label.text()
assert upload_button.isEnabled()
row_action = doctor.table.cellWidget(0, 2)
row_upload = next(button for button in row_action.findChildren(type(upload_button)) if button.text() == "上传处方")
row_upload.click()
assert upload_attempts == [7, 7]
assert upload_button.isHidden()
if not previously_signed:
assert page_module.prescription_status(doctor.table.current_data()) == ("待签名", "warning")
assert doctor.audit_button.text() == "继续签署" and doctor.audit_button.isEnabled()
reviewer.refresh()
assert reviewer.audit_button.isHidden()
row.update(esign=signed)
reviewer.refresh()
assert reviewer.audit_button.isHidden()
row["can_review_prescription"] = True
doctor.refresh()
assert page_module.prescription_status(doctor.table.current_data()) == ("待审核", "warning")
assert page_module.can_audit(doctor.table.current_data())
reviewer.refresh()
assert not reviewer.audit_button.isHidden()
assert reviewer.audit_button.isEnabled()
reviewer.audit_button.click()
assert audit_calls == [(7, {"action": "approve", "remark": ""})]
doctor.close()
reviewer.close()
def test_saved_draft_offers_explicit_upload_before_doctor_signing(
immediate: None, monkeypatch: pytest.MonkeyPatch,
) -> None:
repository = Repository()
repository.status = state(
"pending", review_submitted_at=0, awaiting_upload=True, can_submit_for_review=True,
can_review_prescription=False, review_required=True,
)
record = {
"id": 7, "audit_status": 0, "esign": repository.status,
"patient_name": "测试患者", "herbs": [{"name": "样例药材甲", "dosage": 1}],
}
def upload(prescription_id: int) -> dict[str, Any]:
assert prescription_id == 7
repository.calls.append("upload")
receipt = {"review_submitted_at": 1_760_000_000, "can_submit_for_review": False}
if repository.calls.count("upload") == 1:
raise ApiBusinessError("上传失败,请重试")
repository.status = {**repository.status, **receipt, "awaiting_upload": False}
return receipt
def finish(dialog: esign_module.PrescriptionEsignDialog) -> None:
dialog.resize(dialog.minimumSize())
dialog.show()
preview = dialog.prescription_preview
assert dialog.workspace_splitter.widget(0) is preview
assert dialog.workspace_splitter.widget(1) is dialog.workflow_panel
assert preview.geometry().right() < dialog.workflow_panel.geometry().left()
assert "样例药材甲" in preview.paper.toPlainText()
assert dialog.workflow_panel.isAncestorOf(dialog.upload_button)
assert [label.text() for label in dialog.step_labels if not label.isHidden()] == [
"保存草稿", "上传处方", "验证医生身份", "医生签署", "药师审核签署",
]
assert dialog.step_labels[1].accessibleDescription() == "当前步骤"
assert dialog.upload_button.isVisible() and not dialog.start_button.isEnabled()
assert repository.calls == ["status"]
dialog.start()
assert repository.calls == ["status"]
dialog.upload_button.click()
assert "上传失败" in dialog.banner.label.text()
assert dialog.upload_button.isEnabled() and not dialog.start_button.isEnabled()
dialog.upload_button.click()
assert repository.calls == ["status", "upload", "upload", "status"]
assert dialog.step_labels[1].accessibleDescription() == "已完成"
assert dialog.step_labels[2].accessibleDescription() == "当前步骤"
assert dialog.upload_button.isHidden() and dialog.start_button.isEnabled()
dialog.close()
monkeypatch.setattr(repository, "submit_prescription_for_review", upload, raising=False)
monkeypatch.setattr(esign_module.PrescriptionEsignDialog, "exec", finish)
assert esign_module.saved_prescription_message(record, "已提交审核") == (
"处方草稿已保存。" + esign_module.PRESCRIPTION_UPLOAD_BEFORE_SIGNING_PROMPT, "success",
)
assert not esign_module.resume_saved_prescription(repository, record, None)
def test_review_submission_repository_uses_prescription_id_and_validates_receipt() -> None:
calls = []
response = {"review_submitted_at": 1_760_000_000, "can_submit_for_review": False}
def post(endpoint: str, payload: dict[str, Any]) -> dict[str, Any]:
calls.append((endpoint, payload))
return response.copy()
repository = RemoteDoctorRepository(SimpleNamespace(post=post))
assert repository.submit_prescription_for_review(7) == response
assert calls == [("tcm.prescription/submitForReview", {"id": 7})]
response["review_submitted_at"] = 0
with pytest.raises(ApiProtocolError, match="处方上传结果格式不正确"):
repository.submit_prescription_for_review(7)
def test_signed_prescription_details_show_upload_before_pharmacist_signing(immediate: None) -> None:
signature = Repository()
signature.status = state("signed", review_required=True, review_submitted_at=0)
record = {"id": 7, "audit_status": 0, "esign": signature.status, "review_submitted_at": 0}
assert esign_module.saved_prescription_message(record, "已提交审核") == (
"处方已保存,医生已签署。" + esign_module.PRESCRIPTION_UPLOAD_PROMPT, "success",
)
signing = esign_module.PrescriptionEsignDialog(signature, record)
detail = prescription_module.PrescriptionDetailDialog(record, repository=signature)
assert "待上传处方" in signing.status_label.text()
assert "待上传处方" in detail.status_banner.label.text()
signature.status = {**signature.status, "review_submitted_at": 1_760_000_000}
signing.refresh()
detail.refresh_esign()
assert "待药师签署" in signing.status_label.text()
assert "待审核" in detail.status_banner.label.text()
signing.close()
detail.close()
def test_saved_response_without_state_warns_without_claiming_completion( def test_saved_response_without_state_warns_without_claiming_completion(
immediate: None, monkeypatch: pytest.MonkeyPatch immediate: None, monkeypatch: pytest.MonkeyPatch
) -> None: ) -> None:
+174 -14
View File
@@ -10,6 +10,7 @@ import pytest
from PySide6.QtCore import QBuffer, QDate, QEvent, QIODevice, QObject, QSize, Qt from PySide6.QtCore import QBuffer, QDate, QEvent, QIODevice, QObject, QSize, Qt
from PySide6.QtGui import QColor, QImage, QPainter, QTextDocument from PySide6.QtGui import QColor, QImage, QPainter, QTextDocument
from PySide6.QtPdf import QPdfDocument from PySide6.QtPdf import QPdfDocument
from PySide6.QtTest import QTest
from PySide6.QtWidgets import QApplication, QComboBox, QDialog, QMessageBox, QPushButton, QWidget from PySide6.QtWidgets import QApplication, QComboBox, QDialog, QMessageBox, QPushButton, QWidget
from doctor_workstation import app as app_module from doctor_workstation import app as app_module
@@ -21,6 +22,7 @@ from doctor_workstation.ui.dialogs.prescription import (
PrescriptionDetailDialog, PrescriptionDetailDialog,
PrescriptionEditorDialog, PrescriptionEditorDialog,
PrescriptionOrderDialog, PrescriptionOrderDialog,
PrescriptionSigningPreview,
PrescriptionTemplateDialog, PrescriptionTemplateDialog,
RemoteMedicineComboBox, RemoteMedicineComboBox,
build_prescription_clinical_diagnosis, build_prescription_clinical_diagnosis,
@@ -479,6 +481,47 @@ def test_editor_builds_complete_add_payload(
application.processEvents() application.processEvents()
@pytest.mark.parametrize("saved_dietary_taboo", [["辛辣食物", "浓茶"], "辛辣食物, 浓茶"])
def test_editor_dietary_taboo_popup_supports_consecutive_selections(
application: QApplication,
immediate_async: None,
saved_dietary_taboo: list[str] | str,
) -> None:
editor = PrescriptionEditorDialog(
SimpleNamespace(), prescription={"dietary_taboo": saved_dietary_taboo}, mode="edit"
)
editor.show()
editor.body_scroll.ensureWidgetVisible(editor.dietary_taboo)
application.processEvents()
selector = editor.dietary_taboo
field = selector.lineEdit()
assert field.text() == "辛辣食物、浓茶"
QTest.mouseClick(field, Qt.MouseButton.LeftButton)
view = selector.view()
assert view.isVisible()
for row, expected in (
(1, "辛辣食物、生冷食物、浓茶"),
(2, "辛辣食物、生冷食物、油腻食物、浓茶"),
(0, "生冷食物、油腻食物、浓茶"),
):
point = view.visualRect(selector.model().index(row, 0)).center()
QTest.mouseClick(view.viewport(), Qt.MouseButton.LeftButton, pos=point)
assert view.isVisible()
assert field.text() == expected
QTest.keyClick(view, Qt.Key.Key_Down)
QTest.keyClick(view, Qt.Key.Key_Space)
assert view.isVisible()
QTest.keyClick(view, Qt.Key.Key_Escape)
assert not view.isVisible()
assert field.text() == "油腻食物、浓茶"
assert editor.payload()["dietary_taboo"] == ["油腻食物", "浓茶"]
editor.close()
application.processEvents()
def test_esign_draft_save_retries_without_discarding_form( def test_esign_draft_save_retries_without_discarding_form(
application: QApplication, application: QApplication,
immediate_async: None, immediate_async: None,
@@ -645,29 +688,146 @@ def test_prescription_window_footer_preserves_draft_on_void_failure(
@pytest.mark.parametrize("variant", ["internal", "user"]) @pytest.mark.parametrize("variant", ["internal", "user"])
def test_prescription_preview_scales_signature_proportionately( @pytest.mark.parametrize("print_layout", [False, True])
application: QApplication, variant: str, @pytest.mark.parametrize(
("image_size", "expected_size"),
[((300, 150), (40, 20)), ((384, 60), (64, 10)), ((20, 10), (20, 10))],
)
def test_prescription_slip_scales_both_signatures_proportionately(
application: QApplication,
variant: str,
print_layout: bool,
image_size: tuple[int, int],
expected_size: tuple[int, int],
) -> None: ) -> None:
image = QImage(300, 150, QImage.Format.Format_ARGB32) signatures = []
image.fill(QColor("black")) for color in ("black", "red"):
buffer = QBuffer() image = QImage(*image_size, QImage.Format.Format_ARGB32)
assert buffer.open(QIODevice.OpenModeFlag.WriteOnly) image.fill(QColor(color))
assert image.save(buffer, "PNG") buffer = QBuffer()
signature = "data:image/png;base64," + bytes(buffer.data().toBase64()).decode("ascii") assert buffer.open(QIODevice.OpenModeFlag.WriteOnly)
assert image.save(buffer, "PNG")
signatures.append("data:image/png;base64," + bytes(buffer.data().toBase64()).decode("ascii"))
doctor_signature, review_signature = signatures
rendered = render_prescription_html({
"doctor_signature": doctor_signature,
"esign": {
"status": "signed",
"review_signer_name": "张药师",
"review_signature_time": 1795000017,
"review_signature": review_signature,
},
}, variant=variant, print_layout=print_layout)
width, height = expected_size
for signature in signatures:
assert f'src="{signature}" width="{width}" height="{height}"' in rendered
document = QTextDocument() document = QTextDocument()
document.setHtml(render_prescription_html({"doctor_signature": signature}, variant=variant)) document.setHtml(rendered)
signature_sizes = [] signature_sizes = {}
block = document.begin() block = document.begin()
while block.isValid(): while block.isValid():
fragments = block.begin() fragments = block.begin()
while not fragments.atEnd(): while not fragments.atEnd():
image_format = fragments.fragment().charFormat().toImageFormat() image_format = fragments.fragment().charFormat().toImageFormat()
if image_format.name() == signature: if image_format.name() in signatures:
signature_sizes.append((image_format.width(), image_format.height())) signature_sizes[image_format.name()] = (image_format.width(), image_format.height())
fragments += 1 fragments += 1
block = block.next() block = block.next()
expected_size = (72, 36) if variant == "internal" else (48, 24) assert signature_sizes == dict.fromkeys(signatures, expected_size)
assert signature_sizes == [expected_size]
def test_signing_preview_uses_full_seed_and_updates_visible_signatures(
application: QApplication,
immediate_async: None,
) -> None:
def unexpected_detail(prescription_id: int) -> None:
pytest.fail(f"Complete prescription {prescription_id} should not be reloaded")
prescription = Prescription.from_dict({
"id": 71,
"patient_name": "虚构患者",
"clinical_diagnosis": "测试诊断",
"prescription_type": "饮片",
"dosage_amount": 20,
"dosage_unit": "ml",
"dose_count": 3,
"herbs": [{"name": "白术", "dosage": 6}],
"esign": {"status": "pending"},
})
preview = PrescriptionSigningPreview(SimpleNamespace(get_prescription=unexpected_detail), prescription)
assert preview.paper is not None and preview.paper.isReadOnly()
document = preview.paper.document()
for text in ("虚构患者", "测试诊断", "白术 (6克)", "18克", "一次20ml"):
assert text in document.toPlainText()
revision = document.revision()
preview.set_esign_state({"status": "pending", "message": "等待核验"})
assert document.revision() == revision
signed = {
"status": "signed",
"doctor_signer_name": "签名医生",
"review_signer_name": "审核药师姓名",
"review_signature_time": 1795000017,
}
preview.set_esign_state(signed)
for text in ("签名医生", "审核药师姓名", "白术 (6克)"):
assert text in document.toPlainText()
revision = document.revision()
preview.set_esign_state(signed | {"review_signature_time": 1795000020})
assert document.revision() == revision
def test_signing_preview_retries_wrong_detail_and_ignores_stale_response(
application: QApplication,
monkeypatch: pytest.MonkeyPatch,
) -> None:
requests = []
def defer_detail(function: Any, prescription_id: int, *, on_success: Any, on_error: Any) -> None:
requests.append((prescription_id, on_success))
monkeypatch.setattr(dialog_module, "run_async", defer_detail)
seed = {"id": 72, "esign": {"status": "pending"}}
repository = SimpleNamespace(get_prescription=lambda _prescription_id: None)
preview = PrescriptionSigningPreview(repository, seed)
assert "正在加载" in preview.status_label.text()
assert requests[0][0] == 72
preview.set_esign_state({"status": "signed", "doctor_signer_name": "签名医生"})
herbs = [{"name": "甘草", "dosage": 3}]
requests[0][1]({"id": 73, "patient_name": "其他患者", "herbs": herbs})
assert preview.paper is None
assert "不匹配" in preview.status_label.text() and not preview.retry_button.isHidden()
preview.retry_button.click()
assert requests[1][0] == 72
requests[0][1](seed | {"patient_name": "过时结果", "herbs": herbs})
assert preview.paper is None
requests[1][1](seed | {"patient_name": "当前患者", "herbs": herbs})
assert preview.paper is not None
text = preview.paper.toPlainText()
assert "当前患者" in text and "甘草 (3克)" in text and "签名医生" in text
def test_signing_preview_renders_an_intentionally_empty_saved_prescription(
application: QApplication,
immediate_async: None,
) -> None:
prescription = Prescription.from_dict({
"id": 73,
"patient_name": "虚构患者",
"clinical_diagnosis": "系统代开诊断",
"is_system_auto": 1,
"herbs": [],
})
preview = PrescriptionSigningPreview(
SimpleNamespace(get_prescription=lambda _prescription_id: prescription),
{"id": 73},
)
assert preview.paper is not None
for text in ("虚构患者", "系统代开诊断", "暂无药材明细"):
assert text in preview.paper.toPlainText()
def test_unsigned_draft_shows_signing_state_before_audit() -> None: def test_unsigned_draft_shows_signing_state_before_audit() -> None:
+10 -7
View File
@@ -740,7 +740,7 @@ def test_silent_queue_polls_reuse_rows_and_do_not_restart_detail_or_ai(
assert repository.queue_calls == 4 assert repository.queue_calls == 4
assert repository.detail_calls == 1 assert repository.detail_calls == 1
assert repository.analysis_calls == [(210, "qwen"), (210, "openai")] assert repository.analysis_calls == [(210, "qwen"), (210, "openai"), (210, "doubao")]
assert page.queue_list.item(0) is first_item assert page.queue_list.item(0) is first_item
assert page.queue_list.itemWidget(first_item) is first_row assert page.queue_list.itemWidget(first_item) is first_row
assert first_item.data(Qt.ItemDataRole.UserRole)["server_revision"] == 4 assert first_item.data(Qt.ItemDataRole.UserRole)["server_revision"] == 4
@@ -748,7 +748,7 @@ def test_silent_queue_polls_reuse_rows_and_do_not_restart_detail_or_ai(
page.refresh() page.refresh()
assert repository.detail_calls == 2 assert repository.detail_calls == 2
assert repository.analysis_calls == [(210, "qwen"), (210, "openai")] assert repository.analysis_calls == [(210, "qwen"), (210, "openai"), (210, "doubao")]
assert page.queue_list.item(0) is first_item assert page.queue_list.item(0) is first_item
page.close() page.close()
@@ -1683,14 +1683,14 @@ def test_reception_auto_loads_structured_ai_analysis_and_matches_reference_geome
page._select_record(detail["appointment"]) page._select_record(detail["appointment"])
application.processEvents() application.processEvents()
assert analysis_calls == [(233, "qwen"), (233, "openai")] assert analysis_calls == [(233, "qwen"), (233, "openai"), (233, "doubao")]
assert [ assert [
( (
page.ai_analysis_model_selector.itemText(index), page.ai_analysis_model_selector.itemText(index),
page.ai_analysis_model_selector.itemData(index), page.ai_analysis_model_selector.itemData(index),
) )
for index in range(page.ai_analysis_model_selector.count()) for index in range(page.ai_analysis_model_selector.count())
] == [("千问", "qwen"), ("OpenAI", "openai")] ] == [("千问", "qwen"), ("OpenAI", "openai"), ("豆包", "doubao")]
assert page.ai_analysis_model_selector.currentData() == "qwen" assert page.ai_analysis_model_selector.currentData() == "qwen"
assert page._ai_analysis_state == "success" assert page._ai_analysis_state == "success"
assert page.ai_analysis_stack.currentWidget() is page.ai_analysis_content_page assert page.ai_analysis_stack.currentWidget() is page.ai_analysis_content_page
@@ -1798,7 +1798,7 @@ def test_reception_dual_ai_queues_openai_only_after_qwen_is_visible(
assert len(queued_async) == 2 assert len(queued_async) == 2
assert calls == [] assert calls == []
assert page.ai_analysis_model_selector.currentData() == "qwen" assert page.ai_analysis_model_selector.currentData() == "qwen"
assert page._ai_analysis_model_states == {"qwen": "loading", "openai": "waiting"} assert page._ai_analysis_model_states == {"qwen": "loading", "openai": "waiting", "doubao": "waiting"}
qwen_result = queued_async[1]["function"](*queued_async[1]["args"]) qwen_result = queued_async[1]["function"](*queued_async[1]["args"])
assert calls == [(283, "qwen")] assert calls == [(283, "qwen")]
@@ -2009,6 +2009,7 @@ def test_reception_ai_analysis_permission_error_retry_states(
(234, "qwen"), (234, "qwen"),
(234, "qwen"), (234, "qwen"),
(234, "openai"), (234, "openai"),
(234, "doubao"),
] ]
assert page._ai_analysis_state == "success" assert page._ai_analysis_state == "success"
assert page.ai_analysis_expand_button.isEnabled() assert page.ai_analysis_expand_button.isEnabled()
@@ -2063,14 +2064,16 @@ def test_saved_diagnosis_forces_a_fresh_structured_ai_analysis(
PermissionSet(["tcm.diagnosis/aiAnalysis"]), PermissionSet(["tcm.diagnosis/aiAnalysis"]),
) )
page.refresh() page.refresh()
assert repository.analysis_calls == [(238, "qwen"), (238, "openai")] assert repository.analysis_calls == [(238, "qwen"), (238, "openai"), (238, "doubao")]
page._diagnosis_saved() page._diagnosis_saved()
assert repository.analysis_calls == [ assert repository.analysis_calls == [
(238, "qwen"), (238, "qwen"),
(238, "openai"), (238, "openai"),
(238, "doubao"),
(238, "qwen"), (238, "qwen"),
(238, "openai"), (238, "openai"),
(238, "doubao"),
] ]
assert "第 2 次qwen分析" in page.ai_risk_label.text() assert "第 2 次qwen分析" in page.ai_risk_label.text()
@@ -2172,7 +2175,7 @@ def test_ai_analysis_dialog_switches_complete_cached_payloads_without_requests(
calls_before_dialog = list(repository.analysis_calls) calls_before_dialog = list(repository.analysis_calls)
page.ai_analysis_expand_button.click() page.ai_analysis_expand_button.click()
assert calls_before_dialog == [(239, "qwen"), (239, "openai")] assert calls_before_dialog == [(239, "qwen"), (239, "openai"), (239, "doubao")]
assert repository.analysis_calls == calls_before_dialog assert repository.analysis_calls == calls_before_dialog
assert len(dialogs) == 1 assert len(dialogs) == 1
dialog = dialogs[0] dialog = dialogs[0]
+19 -1
View File
@@ -782,6 +782,24 @@ def test_remote_diagnosis_ai_stream_normalises_chunks_in_order() -> None:
assert client.post_calls == [] assert client.post_calls == []
def test_remote_diagnosis_ai_stream_sends_only_a_whitelisted_selected_model() -> None:
payloads: list[dict[str, Any]] = []
class StreamingClient(RecordingClient):
def post_event_stream(self, endpoint: str, payload: dict[str, Any], **kwargs: Any):
payloads.append(dict(payload))
yield {"event": "done", "data": {"model_label": "豆包", "answer": "完成"}}
repository = RemoteDoctorRepository(StreamingClient())
list(repository.stream_diagnosis_ai(501, "请总结", task="summary", model="doubao"))
list(repository.stream_diagnosis_ai(501, "请总结", task="summary"))
assert payloads[0]["model"] == "doubao"
assert "model" not in payloads[1]
with pytest.raises(ValueError, match="qwen, openai or doubao"):
list(repository.stream_diagnosis_ai(501, "请总结", model="deepseek"))
assert len(payloads) == 2
@pytest.mark.parametrize("status_code", [404, 405]) @pytest.mark.parametrize("status_code", [404, 405])
def test_remote_diagnosis_ai_stream_falls_back_for_missing_route(status_code: int) -> None: def test_remote_diagnosis_ai_stream_falls_back_for_missing_route(status_code: int) -> None:
class MissingStreamClient(RecordingClient): class MissingStreamClient(RecordingClient):
@@ -915,7 +933,7 @@ def test_remote_diagnosis_ai_analysis_uses_exact_post_contract() -> None:
calls_before_validation = list(client.post_calls) calls_before_validation = list(client.post_calls)
timeouts_before_validation = list(client.timeouts) timeouts_before_validation = list(client.timeouts)
with pytest.raises(ValueError, match="qwen or openai"): with pytest.raises(ValueError, match="qwen, openai or doubao"):
repository.get_diagnosis_ai_analysis(501, model="invalid") # type: ignore[arg-type] repository.get_diagnosis_ai_analysis(501, model="invalid") # type: ignore[arg-type]
with pytest.raises(ValueError, match="positive"): with pytest.raises(ValueError, match="positive"):
repository.get_diagnosis_ai_analysis(0) repository.get_diagnosis_ai_analysis(0)
+12
View File
@@ -167,6 +167,18 @@ def shell_window(
application.processEvents() application.processEvents()
def test_minimize_preserves_session_and_close_requests_application_exit(
shell_window: ShellWindow, application: QApplication
) -> None:
exits = []
shell_window.close_requested.connect(lambda: exits.append(True))
shell_window.showMinimized()
application.processEvents()
assert exits == []
shell_window.close()
assert exits == [True]
def test_legacy_shell_matches_reference_geometry_at_both_acceptance_sizes( def test_legacy_shell_matches_reference_geometry_at_both_acceptance_sizes(
application: QApplication, application: QApplication,
shell_window: ShellWindow, shell_window: ShellWindow,
+60
View File
@@ -18,6 +18,7 @@ from PySide6.QtWidgets import (
from doctor_workstation import app as app_module from doctor_workstation import app as app_module
from doctor_workstation.app import ApplicationController from doctor_workstation.app import ApplicationController
from doctor_workstation.config import AppConfig from doctor_workstation.config import AppConfig
from doctor_workstation.core import Session
from doctor_workstation.core.errors import AuthenticationExpiredError from doctor_workstation.core.errors import AuthenticationExpiredError
from doctor_workstation.services import DemoDoctorRepository from doctor_workstation.services import DemoDoctorRepository
from doctor_workstation.ui import login as login_module from doctor_workstation.ui import login as login_module
@@ -186,6 +187,65 @@ def test_controller_session_expiry_returns_to_login_once() -> None:
assert messages == ["登录状态已失效,请重新登录。"] assert messages == ["登录状态已失效,请重新登录。"]
def test_idle_heartbeat_is_single_flight_and_offline_wake_observes_cutoff(monkeypatch: Any) -> None:
now = [100.0]
queued = []
messages = []
timer_delays = []
session = Session(token="first", desktop_expires_at=200)
repository = SimpleNamespace(desktop_heartbeat=lambda _token: 200)
controller = SimpleNamespace(
current_repository=repository, _desktop_session=session, _shutting_down=False,
_heartbeat_pending=False, _next_heartbeat_at=100, _session_workers=object(),
_desktop_timer=SimpleNamespace(start=timer_delays.append),
_logout=lambda *, message: messages.append(message),
)
controller._check_desktop_session = lambda: ApplicationController._check_desktop_session(controller)
monkeypatch.setattr(app_module, "time", SimpleNamespace(time=lambda: now[0]))
monkeypatch.setattr(app_module, "run_async", lambda fn, token, **opts: queued.append((fn, token, opts)))
controller._check_desktop_session()
controller._check_desktop_session()
assert len(queued) == 1 and queued[0][:2] == (repository.desktop_heartbeat, "first")
queued[0][2]["on_error"](RuntimeError("offline"))
now[0] = 114
controller._check_desktop_session()
assert len(queued) == 1
now[0] = 115
controller._check_desktop_session()
assert len(queued) == 2
queued[1][2]["on_success"](400)
assert session.desktop_expires_at == 200
now[0] = 199.75
controller._check_desktop_session()
assert timer_delays[-1] == 250
assert not messages
now[0] = 205 # Resume with a heartbeat still in flight.
controller._check_desktop_session()
assert len(queued) == 3
assert messages == ["已到北京时间 05:00,请重新登录医生工作站。"]
def test_old_worker_expiry_cannot_log_out_new_account() -> None:
application = QApplication.instance() or QApplication([])
errors: list[Exception] = []
workers = []
pool = SimpleNamespace(start=lambda worker, _priority: workers.append(worker))
def expired() -> None:
raise AuthenticationExpiredError("first session expired", code=-1)
try:
set_authentication_expired_handler(lambda error: errors.append(error) is None)
widget_module.run_async(expired, on_error=errors.append, pool=pool)
set_authentication_expired_handler(lambda error: errors.append(error) is None)
workers[0].run()
application.processEvents()
assert not errors
finally:
set_authentication_expired_handler(None)
def test_persisted_session_restore_blocks_manual_submit_before_worker_start( def test_persisted_session_restore_blocks_manual_submit_before_worker_start(
monkeypatch: Any, monkeypatch: Any,
) -> None: ) -> None:
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+2 -2
View File
@@ -6,8 +6,8 @@
<meta name="color-scheme" content="light" /> <meta name="color-scheme" content="light" />
<link rel="icon" type="image/png" href="./favicon.png" /> <link rel="icon" type="image/png" href="./favicon.png" />
<title>视频面诊</title> <title>视频面诊</title>
<script type="module" crossorigin src="./assets/index-D15F7NRw.js"></script> <script type="module" crossorigin src="./assets/index-DnfCezBT.js"></script>
<link rel="stylesheet" crossorigin href="./assets/index-Do0GoLfO.css"> <link rel="stylesheet" crossorigin href="./assets/index-s1DhGM4I.css">
</head> </head>
<body> <body>
<div id="app"></div> <div id="app"></div>
+3 -1
View File
@@ -10,7 +10,7 @@ import { transcriptionStatus } from './transcription-status'
import { emptyVideoAiState } from './video-ai-types' import { emptyVideoAiState } from './video-ai-types'
import type { VideoAiState } from './video-ai-types' import type { VideoAiState } from './video-ai-types'
import { appendAiDraft, shouldClearSubmittedDraft } from './im-ai' import { appendAiDraft, shouldClearSubmittedDraft } from './im-ai'
import type { ImAiAction, ImAiState } from './im-ai' import type { ImAiAction, ImAiModel, ImAiState } from './im-ai'
import { aiPanelBounds, clampAiPanelWidth, resizeAiPanelByKey } from './im-ai-layout' import { aiPanelBounds, clampAiPanelWidth, resizeAiPanelByKey } from './im-ai-layout'
interface ChatMessage { interface ChatMessage {
@@ -83,6 +83,7 @@ const props = defineProps<{
onRequestImAi: (action: ImAiAction) => void onRequestImAi: (action: ImAiAction) => void
onRegenerateImAi: (action: ImAiAction) => void onRegenerateImAi: (action: ImAiAction) => void
onCancelImAi: () => void onCancelImAi: () => void
onImAiModel?: (model: ImAiModel) => void
onSendText: (text: string) => Promise<void> onSendText: (text: string) => Promise<void>
onSendAttachment: (file: File) => Promise<void> onSendAttachment: (file: File) => Promise<void>
onLoadMore: () => Promise<void> onLoadMore: () => Promise<void>
@@ -792,6 +793,7 @@ watch(
@request="onRequestImAi" @request="onRequestImAi"
@regenerate="onRegenerateImAi" @regenerate="onRegenerateImAi"
@cancel="onCancelImAi" @cancel="onCancelImAi"
@model="onImAiModel?.($event)"
@apply="applyAiDraft" @apply="applyAiDraft"
@close="closeAi" @close="closeAi"
@open-diagnosis="runAction(onOpenDiagnosis)" @open-diagnosis="runAction(onOpenDiagnosis)"
+17 -1
View File
@@ -1,6 +1,7 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed, nextTick, ref, watch } from 'vue' import { computed, nextTick, ref, watch } from 'vue'
import type { ImAiAction, ImAiState } from './im-ai' import { IM_AI_MODELS, IM_AI_MODEL_LABELS } from './im-ai'
import type { ImAiAction, ImAiModel, ImAiState } from './im-ai'
import { renderImAiMarkdown } from './im-ai-markdown' import { renderImAiMarkdown } from './im-ai-markdown'
const props = defineProps<{ const props = defineProps<{
@@ -17,6 +18,7 @@ const emit = defineEmits<{
apply: [] apply: []
close: [] close: []
openDiagnosis: [] openDiagnosis: []
model: [model: ImAiModel]
}>() }>()
const panel = ref<HTMLElement | null>(null) const panel = ref<HTMLElement | null>(null)
const closeButton = ref<HTMLButtonElement | null>(null) const closeButton = ref<HTMLButtonElement | null>(null)
@@ -27,6 +29,7 @@ const actions: { key: ImAiAction; label: string }[] = [
{ key: 'followup', label: '建议追问' }, { key: 'followup', label: '建议追问' },
{ key: 'reply', label: '起草回复' }, { key: 'reply', label: '起草回复' },
] ]
const model = ref<ImAiModel>('qwen')
const busy = computed(() => ['loading', 'streaming'].includes(props.state.status)) const busy = computed(() => ['loading', 'streaming'].includes(props.state.status))
const pendingAction = computed(() => props.state.pendingAction || (busy.value ? props.state.action : null)) const pendingAction = computed(() => props.state.pendingAction || (busy.value ? props.state.action : null))
const generating = computed(() => Boolean(pendingAction.value)) const generating = computed(() => Boolean(pendingAction.value))
@@ -52,6 +55,13 @@ watch([() => props.state.contextKey, () => props.state.action] as const, ([conte
}) })
}, { flush: 'pre' }) }, { flush: 'pre' })
function selectModel(event: Event): void {
const next = (event.target as HTMLSelectElement).value as ImAiModel
if (!IM_AI_MODELS.includes(next)) return
model.value = next
emit('model', next)
}
function regenerate(): void { function regenerate(): void {
if (!props.state.action || generating.value) return if (!props.state.action || generating.value) return
scrollPositions.delete(props.state.action) scrollPositions.delete(props.state.action)
@@ -131,6 +141,12 @@ function onKeydown(event: KeyboardEvent): void {
<span v-if="completedActions.includes(action.key)" class="im-ai-tool__saved" aria-label="已有内容">·</span> <span v-if="completedActions.includes(action.key)" class="im-ai-tool__saved" aria-label="已有内容">·</span>
</button> </button>
</div> </div>
<label class="im-ai-model" title="之后的生成使用所选模型;已生成的内容保留原模型标注">
<span>模型</span>
<select :value="model" :disabled="!state.available || generating" @change="selectModel">
<option v-for="key in IM_AI_MODELS" :key="key" :value="key">{{ IM_AI_MODEL_LABELS[key] }}</option>
</select>
</label>
<div ref="resultBody" class="im-ai-body" tabindex="0" aria-label="AI 结果"> <div ref="resultBody" class="im-ai-body" tabindex="0" aria-label="AI 结果">
<div v-if="state.status === 'unavailable'" class="im-ai-empty"> <div v-if="state.status === 'unavailable'" class="im-ai-empty">
<strong>AI 助手暂不可用</strong> <strong>AI 助手暂不可用</strong>
@@ -12,10 +12,10 @@ const props = defineProps<{
const emit = defineEmits<{ close: []; save: [] }>() const emit = defineEmits<{ close: []; save: [] }>()
const models = TONGUE_SCREENSHOT_MODELS const models = TONGUE_SCREENSHOT_MODELS
const labels = TONGUE_SCREENSHOT_MODEL_LABELS const labels = TONGUE_SCREENSHOT_MODEL_LABELS
const modelNames = models.map((model) => labels[model]).join(' + ')
const activeModel = ref<TongueScreenshotModel>('qwen') const activeModel = ref<TongueScreenshotModel>('qwen')
const states = ref<Record<TongueScreenshotModel, TongueScreenshotPreviewState>>({ const states = ref(Object.fromEntries(models.map((model) => [model, emptyTongueScreenshotPreview()])) as
qwen: emptyTongueScreenshotPreview(), openai: emptyTongueScreenshotPreview(), Record<TongueScreenshotModel, TongueScreenshotPreviewState>)
})
const state = computed(() => states.value[activeModel.value]) const state = computed(() => states.value[activeModel.value])
let userSelected = false let userSelected = false
let firstResultShown = false let firstResultShown = false
@@ -31,7 +31,8 @@ function controller(model: TongueScreenshotModel) {
}, },
}) })
} }
const previews = { qwen: controller('qwen'), openai: controller('openai') } const previews = Object.fromEntries(models.map((model) => [model, controller(model)])) as
Record<TongueScreenshotModel, ReturnType<typeof controller>>
watch(() => props.image, (image) => { watch(() => props.image, (image) => {
activeModel.value = 'qwen'; userSelected = false; firstResultShown = false activeModel.value = 'qwen'; userSelected = false; firstResultShown = false
for (const model of models) void previews[model].open(image) for (const model of models) void previews[model].open(image)
@@ -72,7 +73,7 @@ function retry(): void { void previews[activeModel.value].retry() }
<section class="screenshot-dialog"> <section class="screenshot-dialog">
<header> <header>
<div> <div>
<p class="eyebrow">患者视频截图 · 千问 + GPT</p> <p class="eyebrow">患者视频截图 · {{ modelNames }}</p>
<h2 id="screenshot-preview-title">舌象分析与中医诊断参考</h2> <h2 id="screenshot-preview-title">舌象分析与中医诊断参考</h2>
</div> </div>
<button type="button" aria-label="关闭截图预览" :disabled="busy" @click="close">×</button> <button type="button" aria-label="关闭截图预览" :disabled="busy" @click="close">×</button>
@@ -83,7 +84,7 @@ function retry(): void { void previews[activeModel.value].retry() }
</div> </div>
<section class="tongue-analysis" aria-labelledby="tongue-analysis-title"> <section class="tongue-analysis" aria-labelledby="tongue-analysis-title">
<header><h3 id="tongue-analysis-title">AI 舌象分析</h3></header> <header><h3 id="tongue-analysis-title">AI 舌象分析</h3></header>
<p class="tongue-analysis__intro">默认使用千问 + GPT 自动分析同一截图,结果分别保留。</p> <p class="tongue-analysis__intro">默认使用{{ modelNames }}自动分析同一截图,结果分别保留。</p>
<div class="tongue-analysis__tabs" role="tablist" aria-label="舌象分析模型"> <div class="tongue-analysis__tabs" role="tablist" aria-label="舌象分析模型">
<button v-for="model in models" :id="`tongue-tab-${model}`" :key="model" type="button" role="tab" <button v-for="model in models" :id="`tongue-tab-${model}`" :key="model" type="button" role="tab"
:aria-selected="activeModel === model" aria-controls="tongue-model-panel" :tabindex="activeModel === model ? 0 : -1" :aria-selected="activeModel === model" aria-controls="tongue-model-panel" :tabindex="activeModel === model ? 0 : -1"
@@ -96,7 +97,7 @@ function retry(): void { void previews[activeModel.value].retry() }
<div v-if="state.phase === 'loading'" class="tongue-analysis__status" role="status" aria-live="polite"> <div v-if="state.phase === 'loading'" class="tongue-analysis__status" role="status" aria-live="polite">
<span class="tongue-analysis__spinner" aria-hidden="true" /> <span class="tongue-analysis__spinner" aria-hidden="true" />
<strong>{{ labels[activeModel] }} 正在分析舌苔特征…</strong> <strong>{{ labels[activeModel] }} 正在分析舌苔特征…</strong>
<p>两个模型独立返回。可切换查看,也可直接确认保存截图。</p> <p>各模型独立返回。可切换查看,也可直接确认保存截图。</p>
</div> </div>
<div v-else-if="state.phase === 'error' || state.phase === 'unavailable'" class="tongue-analysis__status tongue-analysis__status--error" role="alert"> <div v-else-if="state.phase === 'error' || state.phase === 'unavailable'" class="tongue-analysis__status tongue-analysis__status--error" role="alert">
<strong>{{ state.phase === 'unavailable' ? '截图分析暂不可用' : `${labels[activeModel]} 本次分析未完成` }}</strong> <strong>{{ state.phase === 'unavailable' ? '截图分析暂不可用' : `${labels[activeModel]} 本次分析未完成` }}</strong>
@@ -144,7 +145,7 @@ function retry(): void { void previews[activeModel.value].retry() }
<p class="tongue-analysis__note">仅供医生结合问诊、脉象等复核,不自动写入诊断或发送给患者。</p> <p class="tongue-analysis__note">仅供医生结合问诊、脉象等复核,不自动写入诊断或发送给患者。</p>
</section> </section>
</div> </div>
<p class="screenshot-dialog__hint">截图会自动发送至千问和 GPT 进行 AI 分析;只有点击“确认并上传”才会保存到患者资料。</p> <p class="screenshot-dialog__hint">截图会自动发送至{{ models.map((model) => labels[model]).join('、') }}进行 AI 分析;只有点击“确认并上传”才会保存到患者资料。</p>
<footer> <footer>
<button class="screenshot-cancel" type="button" :disabled="busy" @click="close">取消</button> <button class="screenshot-cancel" type="button" :disabled="busy" @click="close">取消</button>
<button class="screenshot-confirm" type="button" :disabled="busy" @click="emit('save')">{{ busy ? '正在上传…' : '确认并上传' }}</button> <button class="screenshot-confirm" type="button" :disabled="busy" @click="emit('save')">{{ busy ? '正在上传…' : '确认并上传' }}</button>
+14 -2
View File
@@ -1,6 +1,9 @@
import { imAiMarkdownToPlainText } from './im-ai-markdown' import { imAiMarkdownToPlainText } from './im-ai-markdown'
export type ImAiAction = 'summary' | 'followup' | 'reply' export type ImAiAction = 'summary' | 'followup' | 'reply'
export type ImAiModel = 'qwen' | 'doubao' | 'openai'
export const IM_AI_MODELS: readonly ImAiModel[] = ['qwen', 'doubao', 'openai']
export const IM_AI_MODEL_LABELS: Record<ImAiModel, string> = { qwen: '千问', doubao: '豆包', openai: 'GPT' }
export type ImAiStatus = 'unavailable' | 'idle' | 'loading' | 'streaming' | 'success' | 'error' | 'cancelled' export type ImAiStatus = 'unavailable' | 'idle' | 'loading' | 'streaming' | 'success' | 'error' | 'cancelled'
export interface ImAiCapabilities { export interface ImAiCapabilities {
@@ -31,6 +34,8 @@ export interface ImAiIdentity {
export interface ImAiRequest extends ImAiIdentity { export interface ImAiRequest extends ImAiIdentity {
source: 'doctor-call' source: 'doctor-call'
event: 'im-ai-request' | 'im-ai-cancel' event: 'im-ai-request' | 'im-ai-cancel'
/** 仅新请求携带;省略时由服务端按任务默认模型生成。 */
model?: ImAiModel
} }
export interface ImAiResult extends ImAiIdentity { export interface ImAiResult extends ImAiIdentity {
@@ -123,6 +128,7 @@ export function createImAiController(options: ControllerOptions) {
let pending: ImAiIdentity | null = null let pending: ImAiIdentity | null = null
let timer: number | null = null let timer: number | null = null
let selectedAction: ImAiAction | null = null let selectedAction: ImAiAction | null = null
let model: ImAiModel = 'qwen'
let initialSummaryTimer: number | null = null let initialSummaryTimer: number | null = null
let initialSummaryWaiting = false let initialSummaryWaiting = false
const results = new Map<ImAiAction, ImAiState>() const results = new Map<ImAiAction, ImAiState>()
@@ -240,7 +246,8 @@ export function createImAiController(options: ControllerOptions) {
notifyCancel(identity) notifyCancel(identity)
}, IM_AI_DEADLINE_MS) }, IM_AI_DEADLINE_MS)
try { try {
options.notify({ source: 'doctor-call', event: 'im-ai-request', ...identity }) // 默认千问时不携带 model,保持旧请求原样;其余模型由服务端白名单再校验。
options.notify({ source: 'doctor-call', event: 'im-ai-request', ...identity, ...(model !== 'qwen' ? { model } : {}) })
} catch { } catch {
if (pending !== identity) return if (pending !== identity) return
release() release()
@@ -283,7 +290,12 @@ export function createImAiController(options: ControllerOptions) {
}) })
} }
return { request, regenerate, receive, cancel, reset, updateReadiness, dismissInitialSummary, getState: () => state } /** 只影响之后发起的生成;已生成的结果仍保留并标注原模型。 */
function setModel(next: ImAiModel): void {
if (IM_AI_MODELS.includes(next)) model = next
}
return { request, regenerate, receive, cancel, reset, updateReadiness, dismissInitialSummary, setModel, getState: () => state }
} }
/** The only AI-to-composer operation; it cannot send or overwrite existing text. */ /** The only AI-to-composer operation; it cannot send or overwrite existing text. */
+1
View File
@@ -2388,6 +2388,7 @@ createApp(App, {
onRequestImAi: imAi.request, onRequestImAi: imAi.request,
onRegenerateImAi: imAi.regenerate, onRegenerateImAi: imAi.regenerate,
onCancelImAi: imAi.cancel, onCancelImAi: imAi.cancel,
onImAiModel: imAi.setModel,
onSendText: sendText, onSendText: sendText,
onSendAttachment: sendAttachment, onSendAttachment: sendAttachment,
onLoadMore: () => loadMessages(true), onLoadMore: () => loadMessages(true),
+4 -1
View File
@@ -339,6 +339,9 @@ button:disabled { cursor: not-allowed; opacity: .55; }
.im-ai-close:hover { background: var(--accent-soft); color: var(--accent); } .im-ai-close:hover { background: var(--accent-soft); color: var(--accent); }
.im-ai-tools { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 5px; padding: 0 14px 14px; border-bottom: 1px solid var(--border); } .im-ai-tools { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 5px; padding: 0 14px 14px; border-bottom: 1px solid var(--border); }
.im-ai-tools button { min-height: 36px; padding: 7px 4px; border: 1px solid var(--border); border-radius: var(--radius-small); background: var(--surface); color: var(--muted); font-size: 12px; white-space: nowrap; } .im-ai-tools button { min-height: 36px; padding: 7px 4px; border: 1px solid var(--border); border-radius: var(--radius-small); background: var(--surface); color: var(--muted); font-size: 12px; white-space: nowrap; }
.im-ai-model { display: flex; align-items: center; gap: 8px; padding: 8px 14px; border-bottom: 1px solid var(--border); color: var(--muted); font-size: 12px; }
.im-ai-model select { flex: 1; min-height: 30px; padding: 4px 8px; border: 1px solid var(--border); border-radius: var(--radius-small); background: var(--surface); color: var(--heading); font-size: 12px; }
.im-ai-model select:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
.im-ai-tools button:enabled:hover, .im-ai-tools button:enabled:hover,
.im-ai-tools .im-ai-tool--selected { border-color: var(--border-strong); background: var(--accent-soft); color: var(--accent-hover); } .im-ai-tools .im-ai-tool--selected { border-color: var(--border-strong); background: var(--accent-soft); color: var(--accent-hover); }
.im-ai-tools .im-ai-tool--selected { font-weight: 600; } .im-ai-tools .im-ai-tool--selected { font-weight: 600; }
@@ -860,7 +863,7 @@ button:disabled { cursor: not-allowed; opacity: .55; }
.tongue-analysis h3 { margin: 0; font-size: 16px; color: var(--heading); } .tongue-analysis h3 { margin: 0; font-size: 16px; color: var(--heading); }
.tongue-analysis__model { color: var(--muted); font-size: 11px; } .tongue-analysis__model { color: var(--muted); font-size: 11px; }
.tongue-analysis__intro { margin: 6px 0 12px; color: var(--muted); font-size: 12px; } .tongue-analysis__intro { margin: 6px 0 12px; color: var(--muted); font-size: 12px; }
.tongue-analysis__tabs { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 8px; margin-bottom: 14px; } .tongue-analysis__tabs { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px; margin-bottom: 14px; }
.tongue-analysis__tabs button { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 4px 8px; min-height: 44px; padding: 8px 10px; border: 1px solid var(--border); border-radius: var(--radius-control); color: var(--muted); background: var(--surface); cursor: pointer; } .tongue-analysis__tabs button { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 4px 8px; min-height: 44px; padding: 8px 10px; border: 1px solid var(--border); border-radius: var(--radius-control); color: var(--muted); background: var(--surface); cursor: pointer; }
.tongue-analysis__tabs button[aria-selected="true"] { border-color: var(--accent); background: var(--accent-soft); color: var(--accent); } .tongue-analysis__tabs button[aria-selected="true"] { border-color: var(--accent); background: var(--accent-soft); color: var(--accent); }
.tongue-analysis__tabs span { font-size: 11px; } .tongue-analysis__tabs span { font-size: 11px; }
+5 -5
View File
@@ -1,6 +1,6 @@
export type TongueScreenshotModel = 'qwen' | 'openai' export type TongueScreenshotModel = 'qwen' | 'openai' | 'doubao'
export const TONGUE_SCREENSHOT_MODELS: readonly TongueScreenshotModel[] = ['qwen', 'openai'] export const TONGUE_SCREENSHOT_MODELS: readonly TongueScreenshotModel[] = ['qwen', 'openai', 'doubao']
export const TONGUE_SCREENSHOT_MODEL_LABELS: Record<TongueScreenshotModel, string> = { qwen: '千问', openai: 'GPT' } export const TONGUE_SCREENSHOT_MODEL_LABELS: Record<TongueScreenshotModel, string> = { qwen: '千问', openai: 'GPT', doubao: '豆包' }
export interface TongueScreenshotResult { export interface TongueScreenshotResult {
model: TongueScreenshotModel model: TongueScreenshotModel
@@ -85,7 +85,7 @@ export function createTongueScreenshotBridge(options: {
cancel(model) cancel(model)
const bridge = options.getBridge() const bridge = options.getBridge()
if (!bridge?.analyzeTongueScreenshotModel) { if (!bridge?.analyzeTongueScreenshotModel) {
return Promise.reject(new TongueScreenshotError('当前客户端不支持千问 + GPT 双模型截图分析,请更新桌面客户端。', 'unavailable')) return Promise.reject(new TongueScreenshotError('当前客户端不支持多模型截图分析,请更新桌面客户端。', 'unavailable'))
} }
const context = options.getContext() const context = options.getContext()
if (!context?.key || !context.diagnosisId) { if (!context?.key || !context.diagnosisId) {
@@ -204,7 +204,7 @@ export function createTongueScreenshotPreview(options: {
const current = generation const current = generation
if (!image) { update(emptyTongueScreenshotPreview()); return } if (!image) { update(emptyTongueScreenshotPreview()); return }
if (!options.analyze) { if (!options.analyze) {
update({ image, phase: 'unavailable', message: '当前客户端不支持千问 + GPT 双模型截图分析,请更新桌面客户端。', result: null }) update({ image, phase: 'unavailable', message: '当前客户端不支持多模型截图分析,请更新桌面客户端。', result: null })
return return
} }
update({ image, phase: 'loading', message: '', result: null }) update({ image, phase: 'loading', message: '', result: null })
+24
View File
@@ -66,6 +66,30 @@ for (const action of ['summary', 'followup', 'reply']) {
}) })
} }
test('selected model rides only on new requests; qwen default keeps the original request shape', (t) => {
const h = harness(t)
h.request('summary')
assert.equal('model' in h.messages[0], false)
h.receive(h.result('success', '千问总结', { modelLabel: '千问' }))
h.setModel('doubao')
h.request('summary')
assert.equal(h.messages.length, 1, 'switching model never regenerates or replaces a cached tab')
h.regenerate('summary')
assert.equal(h.messages.at(-1).event, 'im-ai-request')
assert.equal(h.messages.at(-1).model, 'doubao')
h.cancel()
assert.equal(h.messages.at(-1).event, 'im-ai-cancel')
assert.equal('model' in h.messages.at(-1), false, 'cancel matches identity only')
h.setModel('unknown-provider')
h.regenerate('followup')
assert.equal(h.messages.at(-1).model, 'doubao', 'invalid model keys are ignored')
h.receive(h.result('success', '豆包追问'))
h.setModel('qwen')
h.regenerate('reply')
assert.equal('model' in h.messages.at(-1), false)
h.receive(h.result('success', '回复'))
})
test('capability defaults closed and requires actual true, version and session', () => { test('capability defaults closed and requires actual true, version and session', () => {
for (const value of [undefined, {}, { version: 1, enabled: true }, { version: 2, enabled: true, sessionId: 'x' }, { version: 1, enabled: 'true', sessionId: 'x' }]) { for (const value of [undefined, {}, { version: 1, enabled: true }, { version: 2, enabled: true, sessionId: 'x' }, { version: 1, enabled: 'true', sessionId: 'x' }]) {
assert.equal(normalizeImAiCapabilities(value).enabled, false) assert.equal(normalizeImAiCapabilities(value).enabled, false)
@@ -91,7 +91,7 @@ test('real App passes the same captured JPEG to preview, automatic AI and only e
h.captures[0].resolve(JPEG) h.captures[0].resolve(JPEG)
await pending; await flush() await pending; await flush()
assert.equal(all(h.root).find(element => element.type === 'img' && element.props.src === JPEG).props.src, JPEG) assert.equal(all(h.root).find(element => element.type === 'img' && element.props.src === JPEG).props.src, JPEG)
assert.deepEqual(h.analyzed, [{ image: JPEG, model: 'qwen' }, { image: JPEG, model: 'openai' }]) assert.deepEqual(h.analyzed, ['qwen', 'openai', 'doubao'].map(model => ({ image: JPEG, model })))
assert.deepEqual(h.saved, []) assert.deepEqual(h.saved, [])
await button(h.root, '确认并上传').props.onClick() await button(h.root, '确认并上传').props.onClick()
await flush() await flush()
@@ -133,6 +133,6 @@ test('real App clears open preview when a new call starts and cancels in-flight
h.unmount() h.unmount()
h.captures[1].resolve(JPEG) h.captures[1].resolve(JPEG)
await next; await flush() await next; await flush()
assert.deepEqual(h.analyzed, [{ image: JPEG, model: 'qwen' }, { image: JPEG, model: 'openai' }]) assert.deepEqual(h.analyzed, ['qwen', 'openai', 'doubao'].map(model => ({ image: JPEG, model })))
assert.deepEqual(h.saved, []) assert.deepEqual(h.saved, [])
}) })
@@ -249,10 +249,10 @@ function mount(t, analyze) {
test('captured preview immediately loads AI but confirm remains available and is the only save action', async (t) => { test('captured preview immediately loads AI but confirm remains available and is the only save action', async (t) => {
const h = mount(t) const h = mount(t)
assert.equal(h.requests.length, 2) assert.deepEqual(h.requests.map(({ image, model }) => ({ image, model })),
assert.equal(h.requests[0].image, JPEG) ['qwen', 'openai', 'doubao'].map(model => ({ image: JPEG, model })))
assert.match(textOf(h.root), /正在分析舌苔特征/) assert.match(textOf(h.root), /正在分析舌苔特征/)
assert.match(textOf(h.root), /自动发送至千问和 GPT.*只有点击.*才会保存到患者资料/) assert.match(textOf(h.root), /自动发送至千问、GPT、豆包进行.*只有点击.*才会保存到患者资料/)
assert.equal(h.events.includes('save'), false) assert.equal(h.events.includes('save'), false)
const confirm = button(h.root, '确认并上传') const confirm = button(h.root, '确认并上传')
assert.equal(confirm.props.disabled, false) assert.equal(confirm.props.disabled, false)
@@ -282,10 +282,10 @@ test('service failure offers retry for the same image, without saving or sending
assert.match(textOf(h.root), /本次分析未完成.*合成服务不可用/) assert.match(textOf(h.root), /本次分析未完成.*合成服务不可用/)
button(h.root, '重试此模型').props.onClick() button(h.root, '重试此模型').props.onClick()
await flush() await flush()
assert.equal(h.requests.length, 3) assert.equal(h.requests.length, 4)
assert.equal(h.requests[2].image, JPEG) assert.equal(h.requests[3].image, JPEG)
assert.equal(h.events.includes('save'), false) assert.equal(h.events.includes('save'), false)
h.requests[2].resolve(result('request-2')) h.requests[3].resolve(result('request-2'))
await flush() await flush()
}) })
@@ -316,8 +316,8 @@ test('closing and unmounting the real modal cancel and suppress outstanding comp
await flush() await flush()
const before = h.events.length const before = h.events.length
h.unmount() h.unmount()
assert.equal(h.events.length, before + 2) assert.equal(h.events.length, before + 3)
h.requests[2].resolve(result('request-2')) h.requests[3].resolve(result('request-2'))
await flush() await flush()
assert.equal(h.root.children.length, 0) assert.equal(h.root.children.length, 0)
}) })
@@ -443,7 +443,7 @@ test('real component shows first completed GPT immediately while qwen is loading
tab(h.root, 'openai').props.onClick() tab(h.root, 'openai').props.onClick()
await flush() await flush()
assert.match(textOf(h.root), /GPT synthetic ready/) assert.match(textOf(h.root), /GPT synthetic ready/)
assert.equal(h.requests.length, 2, 'switching never regenerates a request') assert.equal(h.requests.length, 3, 'switching never regenerates a request')
h.requests[0].resolve(result()) h.requests[0].resolve(result())
await flush() await flush()
assert.equal(tab(h.root, 'openai').props['aria-selected'], true, 'later completion never steals selected tab') assert.equal(tab(h.root, 'openai').props['aria-selected'], true, 'later completion never steals selected tab')
@@ -481,14 +481,14 @@ test('one model error and selected retry leave the completed peer cached', async
assert.match(textOf(h.root), /GPT 独立失败/) assert.match(textOf(h.root), /GPT 独立失败/)
button(h.root, '重试此模型').props.onClick() button(h.root, '重试此模型').props.onClick()
await flush() await flush()
assert.equal(h.requests.length, 3) assert.equal(h.requests.length, 4)
assert.equal(h.requests[2].model, 'openai') assert.equal(h.requests[3].model, 'openai')
assert.equal(h.requests[2].image, JPEG) assert.equal(h.requests[3].image, JPEG)
tab(h.root, 'qwen').props.onClick() tab(h.root, 'qwen').props.onClick()
await flush() await flush()
assert.match(textOf(h.root), /Qwen retained/) assert.match(textOf(h.root), /Qwen retained/)
assert.equal(tab(h.root, 'openai').props['data-phase'], 'loading') assert.equal(tab(h.root, 'openai').props['data-phase'], 'loading')
h.requests[2].resolve(result('gpt-retry', 21, 'usable', 'openai')) h.requests[3].resolve(result('gpt-retry', 21, 'usable', 'openai'))
await flush() await flush()
assert.equal(tab(h.root, 'qwen').props['aria-selected'], true) assert.equal(tab(h.root, 'qwen').props['aria-selected'], true)
assert.equal(h.events.includes('save'), false) assert.equal(h.events.includes('save'), false)
@@ -500,7 +500,8 @@ test('new image clears both caches and late earlier successes or failures cannot
await flush() await flush()
h.image.value = 'replacement-image' h.image.value = 'replacement-image'
await flush() await flush()
assert.deepEqual(h.requests.slice(2).map(({ image, model }) => ({ image, model })), [{ image: 'replacement-image', model: 'qwen' }, { image: 'replacement-image', model: 'openai' }]) assert.deepEqual(h.requests.slice(3).map(({ image, model }) => ({ image, model })),
['qwen', 'openai', 'doubao'].map(model => ({ image: 'replacement-image', model })))
assert.doesNotMatch(textOf(h.root), /Old cached qwen/) assert.doesNotMatch(textOf(h.root), /Old cached qwen/)
assert.equal(tab(h.root, 'qwen').props['data-phase'], 'loading') assert.equal(tab(h.root, 'qwen').props['data-phase'], 'loading')
assert.equal(tab(h.root, 'openai').props['data-phase'], 'loading') assert.equal(tab(h.root, 'openai').props['data-phase'], 'loading')
@@ -510,19 +511,19 @@ test('new image clears both caches and late earlier successes or failures cannot
assert.doesNotMatch(textOf(h.root), /obsolete/) assert.doesNotMatch(textOf(h.root), /obsolete/)
button(h.root, '取消').props.onClick() button(h.root, '取消').props.onClick()
await flush() await flush()
h.requests[2].resolve(result('late-qwen')) h.requests[3].resolve(result('late-qwen'))
h.requests[3].resolve(result('late-gpt', 21, 'usable', 'openai')) h.requests[4].resolve(result('late-gpt', 21, 'usable', 'openai'))
h.requests[5].resolve(result('late-doubao', 21, 'usable', 'doubao'))
await flush() await flush()
assert.equal(tab(h.root, 'qwen').props['data-phase'], 'idle') for (const model of ['qwen', 'openai', 'doubao']) assert.equal(tab(h.root, model).props['data-phase'], 'idle')
assert.equal(tab(h.root, 'openai').props['data-phase'], 'idle')
assert.doesNotMatch(textOf(h.root), /合成浅白色描述/) assert.doesNotMatch(textOf(h.root), /合成浅白色描述/)
assert.ok(h.events.includes('cancel-qwen') && h.events.includes('cancel-openai')) assert.ok(['qwen', 'openai', 'doubao'].every(model => h.events.includes(`cancel-${model}`)))
}) })
test('model tabs support arrow keys, Home and End with roving keyboard focus', async (t) => { test('model tabs support arrow keys, Home and End with roving keyboard focus', async (t) => {
const h = mount(t) const h = mount(t)
for (const [current, key, expected] of [['qwen', 'ArrowRight', 'openai'], ['openai', 'ArrowLeft', 'qwen'], ['qwen', 'End', 'openai'], ['openai', 'Home', 'qwen']]) { for (const [current, key, expected] of [['qwen', 'ArrowRight', 'openai'], ['openai', 'ArrowLeft', 'qwen'], ['qwen', 'End', 'doubao'], ['doubao', 'ArrowRight', 'qwen'], ['qwen', 'ArrowLeft', 'doubao'], ['doubao', 'Home', 'qwen']]) {
const tabs = ['qwen', 'openai'].map(model => tab(h.root, model)) const tabs = ['qwen', 'openai', 'doubao'].map(model => tab(h.root, model))
let prevented = false let prevented = false
tab(h.root, current).props.onKeydown({ key, preventDefault: () => { prevented = true }, currentTarget: { parentElement: { querySelectorAll: () => tabs } } }) tab(h.root, current).props.onKeydown({ key, preventDefault: () => { prevented = true }, currentTarget: { parentElement: { querySelectorAll: () => tabs } } })
await flush() await flush()
@@ -531,5 +532,5 @@ test('model tabs support arrow keys, Home and End with roving keyboard focus', a
assert.equal(tab(h.root, expected).props.tabindex, 0) assert.equal(tab(h.root, expected).props.tabindex, 0)
assert.equal(tab(h.root, expected).focused, true) assert.equal(tab(h.root, expected).focused, true)
} }
assert.equal(h.requests.length, 2) assert.equal(h.requests.length, 3)
}) })
@@ -0,0 +1,57 @@
{
"queried_at_beijing": "2026-11-23T13:40:09+08:00",
"source": {
"host": "127.0.0.1",
"database": "zyt",
"production_sync_verified": false
},
"wecom_login_endpoint": "/adminapi/login/workWechatLogin",
"wecom_login_operation_log_count": {
"records": 0,
"earliest_time": null,
"latest_time": null,
"earliest_time_beijing": "—",
"latest_time_beijing": "—"
},
"wecom_related_endpoint_counts": [
{
"endpoint": "https://cs.zhenyangtang.com.cn/adminapi/login/workwechatconfig",
"type": "GET",
"records": 8,
"earliest_time": 1781230466,
"latest_time": 1791674406,
"earliest_time_beijing": "2026-06-12 10:14:26",
"latest_time_beijing": "2026-10-11 07:20:06"
}
],
"doctor_current_binding_and_last_login": [
{
"id": 12,
"name": "霍桢毅",
"currently_bound_to_wecom": 1,
"login_time": 1794876786,
"login_ip": "123.14.166.7",
"login_time_beijing": "2026-11-17 08:53:06"
},
{
"id": 25,
"name": "穆睿",
"currently_bound_to_wecom": 1,
"login_time": 1794878314,
"login_ip": "123.14.166.7",
"login_time_beijing": "2026-11-17 09:18:34"
},
{
"id": 28,
"name": "赵俊霞",
"currently_bound_to_wecom": 1,
"login_time": 1794801538,
"login_ip": "123.163.21.212",
"login_time_beijing": "2026-11-16 11:58:58"
}
],
"interpretation": [
"workWechatConfig 为获取登录配置,不能视为扫码成功记录。",
"当前企微绑定状态及 login_time 不能确定某次登录使用企微扫码。"
]
}
@@ -0,0 +1,13 @@
START TRANSACTION READ ONLY;
SELECT id,name,login_time,login_ip FROM zyt_admin WHERE id IN (12,25,28) ORDER BY id;
SELECT id,admin_id,terminal,update_time,expire_time FROM zyt_admin_session WHERE admin_id IN (12,25,28) ORDER BY admin_id,update_time,id;
SELECT DISTINCT ol.id,ol.admin_id,ol.admin_name,a.id AS matched_doctor_id,a.name AS matched_doctor_name,ol.action,ol.type,SUBSTRING_INDEX(ol.url,'?',1) AS endpoint,ol.ip,ol.create_time,JSON_UNQUOTE(JSON_EXTRACT(IF(JSON_VALID(ol.result),ol.result,'{}'),'$.code')) AS response_code,JSON_UNQUOTE(JSON_EXTRACT(IF(JSON_VALID(ol.result),ol.result,'{}'),'$.msg')) AS response_message FROM zyt_operation_log ol JOIN zyt_admin a ON (a.id=ol.admin_id OR (a.account<>'' AND a.account=ol.account) OR (a.account<>'' AND a.account=JSON_UNQUOTE(JSON_EXTRACT(IF(JSON_VALID(ol.params),ol.params,'{}'),'$.account'))) OR a.id=JSON_UNQUOTE(JSON_EXTRACT(IF(JSON_VALID(ol.result),ol.result,'{}'),'$.data.id')) OR a.id=JSON_UNQUOTE(JSON_EXTRACT(IF(JSON_VALID(ol.result),ol.result,'{}'),'$.data.admin_id'))) WHERE a.id IN (12,25,28) AND (LOWER(ol.url) LIKE '%/login/%' OR LOWER(ol.url) LIKE '%/identity.session/%' OR ol.action LIKE '%登录%') ORDER BY ol.create_time,ol.id;
SELECT COUNT(*) AS total,MIN(create_time) AS earliest_time,MAX(create_time) AS latest_time FROM zyt_operation_log;
SELECT SUBSTRING_INDEX(url,'?',1) AS endpoint,COUNT(*) AS records,MIN(create_time) AS earliest_time,MAX(create_time) AS latest_time FROM zyt_operation_log WHERE LOWER(url) LIKE '%/login/%' OR LOWER(url) LIKE '%/identity.session/%' OR action LIKE '%登录%' GROUP BY SUBSTRING_INDEX(url,'?',1);
ROLLBACK;
@@ -0,0 +1,103 @@
{
"queried_at_beijing": "2026-11-23T12:15:47+08:00",
"source": {
"host": "127.0.0.1",
"database": "zyt",
"production_sync_verified": false
},
"doctor_last_login_snapshots": [
{
"id": 12,
"name": "霍桢毅",
"login_time": 1794876786,
"login_ip": "123.14.166.7",
"login_time_beijing": "2026-11-17 08:53:06"
},
{
"id": 25,
"name": "穆睿",
"login_time": 1794878314,
"login_ip": "123.14.166.7",
"login_time_beijing": "2026-11-17 09:18:34"
},
{
"id": 28,
"name": "赵俊霞",
"login_time": 1794801538,
"login_ip": "123.163.21.212",
"login_time_beijing": "2026-11-16 11:58:58"
}
],
"current_session_metadata": [
{
"id": 7,
"admin_id": 12,
"terminal": 1,
"update_time": 1794876786,
"expire_time": 1794905586,
"update_time_beijing": "2026-11-17 08:53:06",
"expire_time_beijing": "2026-11-17 16:53:06"
},
{
"id": 39,
"admin_id": 25,
"terminal": 1,
"update_time": 1794878314,
"expire_time": 1794907114,
"update_time_beijing": "2026-11-17 09:18:34",
"expire_time_beijing": "2026-11-17 17:18:34"
},
{
"id": 36,
"admin_id": 28,
"terminal": 1,
"update_time": 1794826739,
"expire_time": 1794855539,
"update_time_beijing": "2026-11-16 18:58:59",
"expire_time_beijing": "2026-11-17 02:58:59"
}
],
"matched_login_operation_logs": [],
"operation_log_coverage": {
"total": 179,
"earliest_time": 1781149993,
"latest_time": 1791674406,
"earliest_time_beijing": "2026-06-11 11:53:13",
"latest_time_beijing": "2026-10-11 07:20:06"
},
"login_endpoint_coverage": [
{
"endpoint": "https://cs.zhenyangtang.com.cn/adminapi/login/account",
"records": 1,
"earliest_time": 1781230467,
"latest_time": 1781230467,
"earliest_time_beijing": "2026-06-12 10:14:27",
"latest_time_beijing": "2026-06-12 10:14:27"
},
{
"endpoint": "https://cs.zhenyangtang.com.cn/adminapi/login/workWechatConfig",
"records": 8,
"earliest_time": 1781230466,
"latest_time": 1791674406,
"earliest_time_beijing": "2026-06-12 10:14:26",
"latest_time_beijing": "2026-10-11 07:20:06"
}
],
"notes": [
"admin.login_time/login_ip 是账号当前保存的最近登录快照,不是完整历史登录流水。",
"admin_session.update_time/expire_time 是当前会话状态字段,不能直接当作独立登录事件。",
"现有留存资料未检得四个处方创建当日的匹配登录记录,不代表医生当天没有登录。"
],
"additional_checks": {
"identity_service_audit": {
"file": "identity-admin/server/runtime/group.sqlite",
"table": "group_audit",
"record_count": 44,
"earliest_beijing": "2026-10-30 14:02:05",
"latest_beijing": "2026-11-04 10:10:49",
"covers_target_prescription_days": false
},
"local_iam_v2_audit": "项目配置未启用 IAM V2 远端审计入口",
"local_application_logs": "未检得目标四个处方创建日的医生登录流水;2026-10-23已有应用日志不含登录事件"
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.7 KiB

@@ -1,6 +1,13 @@
{ {
"处方订单及日志_原始字段.json": "b80563ad72a27cc9bb7779c669358e2e6f1a7fc5bad34c6d33f6fb793f1537eb", "处方订单及日志_原始字段.json": "4b5de8c7ae60316c05e8290e85e899b5d20f0aee7d8daaa8b2a818f4be76e544",
"处方订单及日志_完整明细.txt": "66d6cf807138681511e034cf35a8bbeda9fcc6cb10f2a8341c0930b72f556dec", "处方订单及日志_完整明细.txt": "28a1bba9fda6970c142ab81a6e8ab22adbd9a3224966d61acd7406c21ed00325",
"处方订单及日志_查看版.html": "1556be7f8109e2d1fefd3bed62ec96943c574a8049dfb2689df1cd872871a17e", "处方订单及日志_查看版.html": "f5a1f9b92a7beb7a1d3a0417ed42f2371c166eebd1bd2252af437fdbb69c992e",
"只读查询.sql": "5e925ce06a803ace2a13dadc825cf91be9746c105e81778c7cf45a11744fa262" "只读查询.sql": "5e925ce06a803ace2a13dadc825cf91be9746c105e81778c7cf45a11744fa262",
"医生签名补充_来源记录.json": "7b9319bd7584cc1c2af735adafce4528435e2d59b6f4458dcd4d206c61be2a86",
"医生签名补充_只读查询.sql": "af227caf038c9d8c3f02059231c181869875b1dc2df95e27e765f39eb34b360e",
"PO20260908142548426588_医生签名原图.png": "e0e1861d4646404401dbaa7a87ef00b7169cc58cac2360bd062759b4b53ca14f",
"PO20260924112640923356_医生签名原图.png": "cedebc2e48d3efc31f548f0cb4aabca1bea1df4b601e41b3329a6b008fbda4ad",
"PO20261024092136816172_医生签名原图.png": "1351f39f31cde87886251018aefe66996fb85fef2d72a23cc5eb66cc43876a9f",
"医生登录记录_来源字段.json": "04181775319c96efec309bee8efe842e1b7f39953288f2e35f037f78ab3e10c1",
"医生登录记录_只读查询.sql": "50a56f60a4d1c27703dd06e09233b50bf976fe3998c62914a5deca9d2ee6b615"
} }
@@ -0,0 +1,13 @@
START TRANSACTION READ ONLY;
SELECT id,name,login_time,login_ip FROM zyt_admin WHERE id IN (12,25,28) ORDER BY id;
SELECT id,admin_id,terminal,update_time,expire_time FROM zyt_admin_session WHERE admin_id IN (12,25,28) ORDER BY admin_id,update_time,id;
SELECT DISTINCT ol.id,ol.admin_id,ol.admin_name,a.id AS matched_doctor_id,a.name AS matched_doctor_name,ol.action,ol.type,SUBSTRING_INDEX(ol.url,'?',1) AS endpoint,ol.ip,ol.create_time,JSON_UNQUOTE(JSON_EXTRACT(IF(JSON_VALID(ol.result),ol.result,'{}'),'$.code')) AS response_code,JSON_UNQUOTE(JSON_EXTRACT(IF(JSON_VALID(ol.result),ol.result,'{}'),'$.msg')) AS response_message FROM zyt_operation_log ol JOIN zyt_admin a ON (a.id=ol.admin_id OR (a.account<>'' AND a.account=ol.account) OR (a.account<>'' AND a.account=JSON_UNQUOTE(JSON_EXTRACT(IF(JSON_VALID(ol.params),ol.params,'{}'),'$.account'))) OR a.id=JSON_UNQUOTE(JSON_EXTRACT(IF(JSON_VALID(ol.result),ol.result,'{}'),'$.data.id')) OR a.id=JSON_UNQUOTE(JSON_EXTRACT(IF(JSON_VALID(ol.result),ol.result,'{}'),'$.data.admin_id'))) WHERE a.id IN (12,25,28) AND (LOWER(ol.url) LIKE '%/login/%' OR LOWER(ol.url) LIKE '%/identity.session/%' OR ol.action LIKE '%登录%') ORDER BY ol.create_time,ol.id;
SELECT COUNT(*) AS total,MIN(create_time) AS earliest_time,MAX(create_time) AS latest_time FROM zyt_operation_log;
SELECT SUBSTRING_INDEX(url,'?',1) AS endpoint,COUNT(*) AS records,MIN(create_time) AS earliest_time,MAX(create_time) AS latest_time FROM zyt_operation_log WHERE LOWER(url) LIKE '%/login/%' OR LOWER(url) LIKE '%/identity.session/%' OR action LIKE '%登录%' GROUP BY SUBSTRING_INDEX(url,'?',1);
ROLLBACK;
@@ -0,0 +1,103 @@
{
"queried_at_beijing": "2026-11-23T12:15:47+08:00",
"source": {
"host": "127.0.0.1",
"database": "zyt",
"production_sync_verified": false
},
"doctor_last_login_snapshots": [
{
"record_kind": "账号最近登录快照",
"source_table": "zyt_admin",
"source_fields": [
"login_time",
"login_ip"
],
"admin_id": 12,
"doctor_name": "霍桢毅",
"login_time": 1794876786,
"login_time_beijing": "2026-11-17 08:53:06",
"login_ip": "123.14.166.7",
"related_order_numbers": [
"PO20261024092136816172"
],
"association_basis": "处方 creator_id = 医生 admin.id",
"is_prescription_session_verified": false
},
{
"record_kind": "账号最近登录快照",
"source_table": "zyt_admin",
"source_fields": [
"login_time",
"login_ip"
],
"admin_id": 28,
"doctor_name": "赵俊霞",
"login_time": 1794801538,
"login_time_beijing": "2026-11-16 11:58:58",
"login_ip": "123.163.21.212",
"related_order_numbers": [
"PO20260908142548426588",
"PO20260924112640923356"
],
"association_basis": "处方 creator_id = 医生 admin.id",
"is_prescription_session_verified": false
}
],
"matched_login_operation_logs": [],
"per_order_findings": [
{
"order_no": "PO20260908142548426588",
"prescription_id": 9787,
"doctor_id": 28,
"doctor_name": "赵俊霞",
"prescription_create_time": 1788774166,
"prescription_create_time_beijing": "2026-09-07 17:42:46",
"prescription_day_login_status": "现有留存资料未检得匹配记录",
"matching_historical_login_event_count": 0
},
{
"order_no": "PO20260924112640923356",
"prescription_id": 10615,
"doctor_id": 28,
"doctor_name": "赵俊霞",
"prescription_create_time": 1790156255,
"prescription_create_time_beijing": "2026-09-23 17:37:35",
"prescription_day_login_status": "现有留存资料未检得匹配记录",
"matching_historical_login_event_count": 0
},
{
"order_no": "PO20261024092136816172",
"prescription_id": 11945,
"doctor_id": 12,
"doctor_name": "霍桢毅",
"prescription_create_time": 1792748278,
"prescription_create_time_beijing": "2026-10-23 17:37:58",
"prescription_day_login_status": "现有留存资料未检得匹配记录",
"matching_historical_login_event_count": 0
}
],
"operation_log_coverage": {
"total": 179,
"earliest_time": 1781149993,
"latest_time": 1791674406,
"earliest_time_beijing": "2026-06-11 11:53:13",
"latest_time_beijing": "2026-10-11 07:20:06"
},
"additional_checks": {
"identity_service_audit": {
"file": "identity-admin/server/runtime/group.sqlite",
"table": "group_audit",
"record_count": 44,
"earliest_beijing": "2026-10-30 14:02:05",
"latest_beijing": "2026-11-04 10:10:49",
"covers_target_prescription_days": false
},
"local_iam_v2_audit": "项目配置未启用 IAM V2 远端审计入口",
"local_application_logs": "未检得目标四个处方创建日的医生登录流水;2026-10-23已有应用日志不含登录事件"
},
"notes": [
"以下为账号保存的最近登录记录;关联依据为处方医生账号。现有留存资料未检得开方当天的匹配登录流水,无法确认具体处方的登录会话。",
"最近登录记录单独列示,不计入处方订单原始操作日志或签名时间线。"
]
}
@@ -0,0 +1,5 @@
START TRANSACTION READ ONLY;
SELECT po.order_no,rx.id AS prescription_id,rx.sn,rx.doctor_name,rx.creator_id,rx.create_time,rx.esign_required,rx.esign_status,rx.doctor_signature FROM zyt_tcm_prescription rx JOIN zyt_tcm_prescription_order po ON po.prescription_id=rx.id WHERE po.order_no IN ('PO20261024092136816172','PO20260924112640923356','PO20260908142548426588');
ROLLBACK;
@@ -0,0 +1,76 @@
{
"extracted_at_beijing": "2026-11-23T11:53:25+08:00",
"source": {
"host": "127.0.0.1",
"database": "zyt",
"production_sync_verified": false
},
"signatures": [
{
"order_no": "PO20260908142548426588",
"prescription_id": 9787,
"sn": "RX202609078921",
"doctor_name": "赵俊霞",
"creator_id": 28,
"create_time": 1788774166,
"esign_required": 0,
"esign_status": "legacy",
"create_time_beijing": "2026-09-07 17:42:46",
"has_signature_image": true,
"image": {
"file": "PO20260908142548426588_医生签名原图.png",
"sha256": "e0e1861d4646404401dbaa7a87ef00b7169cc58cac2360bd062759b4b53ca14f",
"bytes": 21220,
"format": "PNG",
"width": 560,
"height": 168,
"source_field": "zyt_tcm_prescription.doctor_signature",
"embedded_text": {}
}
},
{
"order_no": "PO20260924112640923356",
"prescription_id": 10615,
"sn": "RX202609238774",
"doctor_name": "赵俊霞",
"creator_id": 28,
"create_time": 1790156255,
"esign_required": 0,
"esign_status": "legacy",
"create_time_beijing": "2026-09-23 17:37:35",
"has_signature_image": true,
"image": {
"file": "PO20260924112640923356_医生签名原图.png",
"sha256": "cedebc2e48d3efc31f548f0cb4aabca1bea1df4b601e41b3329a6b008fbda4ad",
"bytes": 28184,
"format": "PNG",
"width": 700,
"height": 210,
"source_field": "zyt_tcm_prescription.doctor_signature",
"embedded_text": {}
}
},
{
"order_no": "PO20261024092136816172",
"prescription_id": 11945,
"sn": "RX202610233553",
"doctor_name": "霍桢毅",
"creator_id": 12,
"create_time": 1792748278,
"esign_required": 0,
"esign_status": "legacy",
"create_time_beijing": "2026-10-23 17:37:58",
"has_signature_image": true,
"image": {
"file": "PO20261024092136816172_医生签名原图.png",
"sha256": "1351f39f31cde87886251018aefe66996fb85fef2d72a23cc5eb66cc43876a9f",
"bytes": 7835,
"format": "PNG",
"width": 560,
"height": 168,
"source_field": "zyt_tcm_prescription.doctor_signature",
"embedded_text": {}
}
}
]
}
@@ -20,7 +20,9 @@
"账号 116 当前名为“药房1”,账号 119 当前名为“药房”;当前角色为下单等。焦珂、李思佳为审核字段/历史日志署名,不据此认定实名登录人或执业资质。", "账号 116 当前名为“药房1”,账号 119 当前名为“药房”;当前角色为下单等。焦珂、李思佳为审核字段/历史日志署名,不据此认定实名登录人或执业资质。",
"当前代码 server/app/adminapi/event.php 的 HttpEnd 监听器为空,关闭了通用后台操作日志写入;这不能证明历史所有时段均关闭。", "当前代码 server/app/adminapi/event.php 的 HttpEnd 监听器为空,关闭了通用后台操作日志写入;这不能证明历史所有时段均关闭。",
"药房回调的日志时间为本系统落库时间;如载荷提供 occurred_at,则在回传明细中另列原值。", "药房回调的日志时间为本系统落库时间;如载荷提供 occurred_at,则在回传明细中另列原值。",
"未检索到关联这三个订单/处方的通用后台请求日志,不能提供完整的逐次开方、修改请求历史。" "未检索到关联这三个订单/处方的通用后台请求日志,不能提供完整的逐次开方、修改请求历史。",
"签名时间默认取处方创建时间。",
"以下为账号保存的最近登录记录;关联依据为处方医生账号。现有留存资料未检得开方当天的匹配登录流水,无法确认具体处方的登录会话。"
], ],
"orders": [ "orders": [
{ {
@@ -892,5 +894,864 @@
"source_freshness_indicator": { "source_freshness_indicator": {
"latest_order_create_time": 1794884824, "latest_order_create_time": 1794884824,
"latest_order_create_time_beijing": "2026-11-17 11:07:04" "latest_order_create_time_beijing": "2026-11-17 11:07:04"
},
"report_updated_at_beijing": "2026-11-23T12:18:20+08:00",
"signature_images_extracted_at_beijing": "2026-11-23T11:53:25+08:00",
"reporting_defaults": {
"PO20261024092136816172": {
"doctor_signature_time": {
"value": 1792748278,
"value_beijing": "2026-10-23 17:37:58",
"doctor_name": "霍桢毅",
"doctor_id": 12,
"is_default": true,
"source_field": "zyt_tcm_prescription.create_time",
"source_record_id": 11945,
"rule": "签名时间默认取处方创建时间。"
}
},
"PO20260924112640923356": {
"doctor_signature_time": {
"value": 1790156255,
"value_beijing": "2026-09-23 17:37:35",
"doctor_name": "赵俊霞",
"doctor_id": 28,
"is_default": true,
"source_field": "zyt_tcm_prescription.create_time",
"source_record_id": 10615,
"rule": "签名时间默认取处方创建时间。"
}
},
"PO20260908142548426588": {
"doctor_signature_time": {
"value": 1788774166,
"value_beijing": "2026-09-07 17:42:46",
"doctor_name": "赵俊霞",
"doctor_id": 28,
"is_default": true,
"source_field": "zyt_tcm_prescription.create_time",
"source_record_id": 9787,
"rule": "签名时间默认取处方创建时间。"
}
}
},
"doctor_signature_images": {
"PO20261024092136816172": {
"file": "PO20261024092136816172_医生签名原图.png",
"sha256": "1351f39f31cde87886251018aefe66996fb85fef2d72a23cc5eb66cc43876a9f",
"bytes": 7835,
"format": "PNG",
"width": 560,
"height": 168,
"source_field": "zyt_tcm_prescription.doctor_signature",
"embedded_text": {},
"prescription_id": 11945,
"doctor_name": "霍桢毅"
},
"PO20260924112640923356": {
"file": "PO20260924112640923356_医生签名原图.png",
"sha256": "cedebc2e48d3efc31f548f0cb4aabca1bea1df4b601e41b3329a6b008fbda4ad",
"bytes": 28184,
"format": "PNG",
"width": 700,
"height": 210,
"source_field": "zyt_tcm_prescription.doctor_signature",
"embedded_text": {},
"prescription_id": 10615,
"doctor_name": "赵俊霞"
},
"PO20260908142548426588": {
"file": "PO20260908142548426588_医生签名原图.png",
"sha256": "e0e1861d4646404401dbaa7a87ef00b7169cc58cac2360bd062759b4b53ca14f",
"bytes": 21220,
"format": "PNG",
"width": 560,
"height": 168,
"source_field": "zyt_tcm_prescription.doctor_signature",
"embedded_text": {},
"prescription_id": 9787,
"doctor_name": "赵俊霞"
}
},
"combined_timelines": {
"PO20261024092136816172": [
{
"record_kind": "处方创建记录",
"source_table": "zyt_tcm_prescription",
"source_id": 11945,
"create_time": 1792748278,
"time_beijing": "2026-10-23 17:37:58",
"display_name": "霍桢毅",
"admin_id": 12,
"action": "prescription_record_created",
"summary": "处方 RX202610233553 创建"
},
{
"record_kind": "医生签名(默认时间)",
"source_table": "zyt_tcm_prescription",
"source_id": 11945,
"source_field": "create_time",
"create_time": 1792748278,
"time_beijing": "2026-10-23 17:37:58",
"display_name": "霍桢毅",
"admin_id": 12,
"action": "signature_time_default",
"is_default": true,
"summary": "霍桢毅签名了",
"time_basis": "签名时间默认取处方创建时间。"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 64682,
"create_time": 1792804896,
"time_beijing": "2026-10-24 09:21:36",
"display_name": "晁婷婷",
"admin_id": 284,
"action": "create",
"summary": "创建业务订单"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 64957,
"create_time": 1792978377,
"time_beijing": "2026-10-26 09:32:57",
"display_name": "李思佳",
"admin_id": 119,
"action": "set_ship_mode",
"summary": "发货类型:甘草药房 → 洛阳药房"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 64975,
"create_time": 1792980124,
"time_beijing": "2026-10-26 10:02:04",
"display_name": "李思佳",
"admin_id": 119,
"action": "edit",
"summary": "编辑了业务订单及相关信息"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 64976,
"create_time": 1792980254,
"time_beijing": "2026-10-26 10:04:14",
"display_name": "药房",
"admin_id": 119,
"action": "audit_rx_approve",
"summary": "处方审核通过"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 64978,
"create_time": 1792980256,
"time_beijing": "2026-10-26 10:04:16",
"display_name": "李思佳",
"admin_id": 119,
"action": "audit_pay_approve",
"summary": "支付单审核通过"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 64979,
"create_time": 1792980258,
"time_beijing": "2026-10-26 10:04:18",
"display_name": "李思佳",
"admin_id": 119,
"action": "ej_pharmacy_submit",
"summary": "上传洛阳药房成功 EJ202610261004182FA855"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 64981,
"create_time": 1792980361,
"time_beijing": "2026-10-26 10:06:01",
"display_name": "洛阳药房ERP",
"admin_id": 0,
"action": "ej_pharmacy_callback",
"summary": "洛阳药房回传:订单已创建;远端状态:待审核;履约状态:待发货/发货与履约 → 待发货/发货与履约;(版本已处理,保留回传日志)"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 65003,
"create_time": 1792983095,
"time_beijing": "2026-10-26 10:51:35",
"display_name": "张卫霞",
"admin_id": 203,
"action": "ship",
"summary": "确认发货(药房直发),运单:JDVE19405836801(auto)"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 65616,
"create_time": 1793161807,
"time_beijing": "2026-10-28 12:30:07",
"display_name": "系统",
"admin_id": 0,
"action": "auto_sign",
"summary": "物流签收(运单:JDVE19405836801),订单状态自动更新为「已签收」"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 66872,
"create_time": 1793434806,
"time_beijing": "2026-10-31 16:20:06",
"display_name": "李思佳",
"admin_id": 119,
"action": "complete",
"summary": "订单完成,状态变更为「已完成」,实付金额更新为 ¥1800"
}
],
"PO20260924112640923356": [
{
"record_kind": "处方创建记录",
"source_table": "zyt_tcm_prescription",
"source_id": 10615,
"create_time": 1790156255,
"time_beijing": "2026-09-23 17:37:35",
"display_name": "赵俊霞",
"admin_id": 28,
"action": "prescription_record_created",
"summary": "处方 RX202609238774 创建"
},
{
"record_kind": "医生签名(默认时间)",
"source_table": "zyt_tcm_prescription",
"source_id": 10615,
"source_field": "create_time",
"create_time": 1790156255,
"time_beijing": "2026-09-23 17:37:35",
"display_name": "赵俊霞",
"admin_id": 28,
"action": "signature_time_default",
"is_default": true,
"summary": "赵俊霞签名了",
"time_basis": "签名时间默认取处方创建时间。"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 57681,
"create_time": 1790220400,
"time_beijing": "2026-09-24 11:26:40",
"display_name": "晁婷婷",
"admin_id": 284,
"action": "create",
"summary": "创建业务订单"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 57792,
"create_time": 1790237688,
"time_beijing": "2026-09-24 16:14:48",
"display_name": "焦珂",
"admin_id": 116,
"action": "set_ship_mode",
"summary": "发货类型:甘草药房 → 洛阳药房"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 57793,
"create_time": 1790237694,
"time_beijing": "2026-09-24 16:14:54",
"display_name": "焦珂",
"admin_id": 116,
"action": "set_ship_mode",
"summary": "发货类型:洛阳药房 → 甘草药房"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 57798,
"create_time": 1790237811,
"time_beijing": "2026-09-24 16:16:51",
"display_name": "焦珂",
"admin_id": 116,
"action": "edit",
"summary": "编辑了业务订单及相关信息"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 57799,
"create_time": 1790237815,
"time_beijing": "2026-09-24 16:16:55",
"display_name": "焦珂",
"admin_id": 116,
"action": "edit",
"summary": "编辑了业务订单及相关信息"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 57801,
"create_time": 1790237839,
"time_beijing": "2026-09-24 16:17:19",
"display_name": "药房",
"admin_id": 116,
"action": "audit_rx_approve",
"summary": "处方审核通过"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 57802,
"create_time": 1790237841,
"time_beijing": "2026-09-24 16:17:21",
"display_name": "焦珂",
"admin_id": 116,
"action": "audit_pay_approve",
"summary": "支付单审核通过"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 57803,
"create_time": 1790237844,
"time_beijing": "2026-09-24 16:17:24",
"display_name": "焦珂",
"admin_id": 116,
"action": "gancao_submit",
"summary": "上传甘草药房成功 G17902378442302734"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 57817,
"create_time": 1790238558,
"time_beijing": "2026-09-24 16:29:18",
"display_name": "甘草系统",
"admin_id": 0,
"action": "gancao_callback",
"summary": "甘草回调:系统审核通过"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 57818,
"create_time": 1790238558,
"time_beijing": "2026-09-24 16:29:18",
"display_name": "甘草系统",
"admin_id": 0,
"action": "gancao_callback",
"summary": "甘草回调:订单药房流转制作中 | 流程:派单 | 药房:G郑州调配中心"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 57829,
"create_time": 1790239757,
"time_beijing": "2026-09-24 16:49:17",
"display_name": "甘草系统",
"admin_id": 0,
"action": "gancao_callback",
"summary": "甘草回调:订单药房流转制作中 | 流程:打印快递 | 药房:G郑州调配中心"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 57830,
"create_time": 1790239757,
"time_beijing": "2026-09-24 16:49:17",
"display_name": "甘草系统",
"admin_id": 0,
"action": "gancao_callback",
"summary": "甘草回调:订单药房流转制作中 | 流程:审方 | 药房:G郑州调配中心"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 57831,
"create_time": 1790239757,
"time_beijing": "2026-09-24 16:49:17",
"display_name": "甘草系统",
"admin_id": 0,
"action": "gancao_callback",
"summary": "甘草回调:系统审核通过"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 57841,
"create_time": 1790240210,
"time_beijing": "2026-09-24 16:56:50",
"display_name": "甘草系统",
"admin_id": 0,
"action": "gancao_callback",
"summary": "甘草回调:订单药房流转制作中 | 流程:煎药调配 | 药房:G郑州调配中心"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 57850,
"create_time": 1790240369,
"time_beijing": "2026-09-24 16:59:29",
"display_name": "甘草系统",
"admin_id": 0,
"action": "gancao_callback",
"summary": "甘草回调:订单药房流转制作中 | 流程:打粉调配 | 药房:G郑州调配中心"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 57852,
"create_time": 1790240405,
"time_beijing": "2026-09-24 17:00:05",
"display_name": "甘草系统",
"admin_id": 0,
"action": "gancao_callback",
"summary": "甘草回调:订单药房流转制作中 | 流程:煎药复核 | 药房:G郑州调配中心"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 57855,
"create_time": 1790240470,
"time_beijing": "2026-09-24 17:01:10",
"display_name": "甘草系统",
"admin_id": 0,
"action": "gancao_callback",
"summary": "甘草回调:订单药房流转制作中 | 流程:打粉复核 | 药房:G郑州调配中心"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 57872,
"create_time": 1790240996,
"time_beijing": "2026-09-24 17:09:56",
"display_name": "甘草系统",
"admin_id": 0,
"action": "gancao_callback",
"summary": "甘草回调:订单药房流转制作中 | 流程:粗碎 | 药房:G郑州调配中心"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 57956,
"create_time": 1790242854,
"time_beijing": "2026-09-24 17:40:54",
"display_name": "甘草系统",
"admin_id": 0,
"action": "gancao_callback",
"summary": "甘草回调:订单药房流转制作中 | 流程:浸泡 | 药房:G郑州调配中心"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 57977,
"create_time": 1790244547,
"time_beijing": "2026-09-24 18:09:07",
"display_name": "甘草系统",
"admin_id": 0,
"action": "gancao_callback",
"summary": "甘草回调:订单药房流转制作中 | 流程:煎药开始 | 药房:G郑州调配中心"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 57995,
"create_time": 1790248163,
"time_beijing": "2026-09-24 19:09:23",
"display_name": "甘草系统",
"admin_id": 0,
"action": "gancao_callback",
"summary": "甘草回调:订单药房流转制作中 | 流程:煎药结束 | 药房:G郑州调配中心"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 58016,
"create_time": 1790296481,
"time_beijing": "2026-09-25 08:34:41",
"display_name": "甘草系统",
"admin_id": 0,
"action": "gancao_callback",
"summary": "甘草回调:订单药房流转制作中 | 流程:浓缩开始 | 药房:G郑州调配中心"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 58017,
"create_time": 1790296485,
"time_beijing": "2026-09-25 08:34:45",
"display_name": "甘草系统",
"admin_id": 0,
"action": "gancao_callback",
"summary": "甘草回调:订单药房流转制作中 | 流程:浓缩结束 | 药房:G郑州调配中心"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 58024,
"create_time": 1790300804,
"time_beijing": "2026-09-25 09:46:44",
"display_name": "甘草系统",
"admin_id": 0,
"action": "gancao_callback",
"summary": "甘草回调:订单药房流转制作中 | 流程:打粉 | 药房:G郑州调配中心"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 58030,
"create_time": 1790303162,
"time_beijing": "2026-09-25 10:26:02",
"display_name": "甘草系统",
"admin_id": 0,
"action": "gancao_callback",
"summary": "甘草回调:订单药房流转制作中 | 流程:拌粉开始 | 药房:G郑州调配中心"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 58034,
"create_time": 1790303789,
"time_beijing": "2026-09-25 10:36:29",
"display_name": "甘草系统",
"admin_id": 0,
"action": "gancao_callback",
"summary": "甘草回调:订单药房流转制作中 | 流程:拌粉 | 药房:G郑州调配中心"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 58035,
"create_time": 1790303810,
"time_beijing": "2026-09-25 10:36:50",
"display_name": "甘草系统",
"admin_id": 0,
"action": "gancao_callback",
"summary": "甘草回调:订单药房流转制作中 | 流程:制丸 | 药房:G郑州调配中心"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 58037,
"create_time": 1790304415,
"time_beijing": "2026-09-25 10:46:55",
"display_name": "甘草系统",
"admin_id": 0,
"action": "gancao_callback",
"summary": "甘草回调:订单药房流转制作中 | 流程:抛光 | 药房:G郑州调配中心"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 58074,
"create_time": 1790326640,
"time_beijing": "2026-09-25 16:57:20",
"display_name": "甘草系统",
"admin_id": 0,
"action": "gancao_callback",
"summary": "甘草回调:订单药房流转制作中 | 流程:烘干完成并过筛 | 药房:G郑州调配中心"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 58076,
"create_time": 1790328640,
"time_beijing": "2026-09-25 17:30:40",
"display_name": "甘草系统",
"admin_id": 0,
"action": "gancao_callback",
"summary": "甘草回调:订单药房流转制作中 | 流程:发货 | 药房:G郑州调配中心"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 58077,
"create_time": 1790328640,
"time_beijing": "2026-09-25 17:30:40",
"display_name": "甘草系统",
"admin_id": 0,
"action": "gancao_callback",
"summary": "甘草回调:订单药房流转制作中 | 流程:发货 | 药房:G郑州调配中心"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 58084,
"create_time": 1790337614,
"time_beijing": "2026-09-25 20:00:14",
"display_name": "甘草系统",
"admin_id": 0,
"action": "gancao_callback",
"summary": "甘草回调:物流中 | 药房:G郑州调配中心 | 物流:shunfeng | 单号:SF5155771371889"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 58085,
"create_time": 1790338204,
"time_beijing": "2026-09-25 20:10:04",
"display_name": "甘草系统",
"admin_id": 0,
"action": "gancao_callback",
"summary": "甘草回调:物流中 | 药房:G郑州调配中心 | 物流:shunfeng | 单号:SF5155771371889"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 58086,
"create_time": 1790338204,
"time_beijing": "2026-09-25 20:10:04",
"display_name": "甘草系统",
"admin_id": 0,
"action": "gancao_callback",
"summary": "甘草回调:物流中 | 药房:G郑州调配中心 | 物流:shunfeng | 单号:SF5155771371889"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 58087,
"create_time": 1790338204,
"time_beijing": "2026-09-25 20:10:04",
"display_name": "甘草系统",
"admin_id": 0,
"action": "gancao_callback",
"summary": "甘草回调:订单药房流转制作中 | 流程:寄出 | 药房:G郑州调配中心"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 58182,
"create_time": 1790468903,
"time_beijing": "2026-09-27 08:28:23",
"display_name": "甘草系统",
"admin_id": 0,
"action": "gancao_callback",
"summary": "甘草回调:完成 | 药房:G郑州调配中心 | 物流:shunfeng | 单号:SF5155771371889"
}
],
"PO20260908142548426588": [
{
"record_kind": "处方创建记录",
"source_table": "zyt_tcm_prescription",
"source_id": 9787,
"create_time": 1788774166,
"time_beijing": "2026-09-07 17:42:46",
"display_name": "赵俊霞",
"admin_id": 28,
"action": "prescription_record_created",
"summary": "处方 RX202609078921 创建"
},
{
"record_kind": "医生签名(默认时间)",
"source_table": "zyt_tcm_prescription",
"source_id": 9787,
"source_field": "create_time",
"create_time": 1788774166,
"time_beijing": "2026-09-07 17:42:46",
"display_name": "赵俊霞",
"admin_id": 28,
"action": "signature_time_default",
"is_default": true,
"summary": "赵俊霞签名了",
"time_basis": "签名时间默认取处方创建时间。"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 52702,
"create_time": 1788848748,
"time_beijing": "2026-09-08 14:25:48",
"display_name": "董肖妍",
"admin_id": 279,
"action": "create",
"summary": "创建业务订单"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 52953,
"create_time": 1788922716,
"time_beijing": "2026-09-09 10:58:36",
"display_name": "焦珂",
"admin_id": 116,
"action": "set_ship_mode",
"summary": "发货类型:甘草药房 → 洛阳药房"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 53013,
"create_time": 1788925616,
"time_beijing": "2026-09-09 11:46:56",
"display_name": "焦珂",
"admin_id": 116,
"action": "edit",
"summary": "编辑了业务订单及相关信息"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 53014,
"create_time": 1788925728,
"time_beijing": "2026-09-09 11:48:48",
"display_name": "药房",
"admin_id": 116,
"action": "audit_rx_approve",
"summary": "处方审核通过"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 53015,
"create_time": 1788925731,
"time_beijing": "2026-09-09 11:48:51",
"display_name": "焦珂",
"admin_id": 116,
"action": "audit_pay_approve",
"summary": "支付单审核通过"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 53255,
"create_time": 1789005730,
"time_beijing": "2026-09-10 10:02:10",
"display_name": "徐云云",
"admin_id": 204,
"action": "ship",
"summary": "确认发货(药房直发),运单:JDVE18948527288(auto)"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 54095,
"create_time": 1789183814,
"time_beijing": "2026-09-12 11:30:14",
"display_name": "系统",
"admin_id": 0,
"action": "auto_sign",
"summary": "物流签收(运单:JDVE18948527288),订单状态自动更新为「已签收」"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 58339,
"create_time": 1790492528,
"time_beijing": "2026-09-27 15:02:08",
"display_name": "焦珂",
"admin_id": 116,
"action": "complete",
"summary": "订单完成,状态变更为「已完成」,实付金额更新为 ¥1400"
}
]
},
"timeline_record_count": 60,
"doctor_login_records": {
"queried_at_beijing": "2026-11-23T12:15:47+08:00",
"source": {
"host": "127.0.0.1",
"database": "zyt",
"production_sync_verified": false
},
"doctor_last_login_snapshots": [
{
"record_kind": "账号最近登录快照",
"source_table": "zyt_admin",
"source_fields": [
"login_time",
"login_ip"
],
"admin_id": 12,
"doctor_name": "霍桢毅",
"login_time": 1794876786,
"login_time_beijing": "2026-11-17 08:53:06",
"login_ip": "123.14.166.7",
"related_order_numbers": [
"PO20261024092136816172"
],
"association_basis": "处方 creator_id = 医生 admin.id",
"is_prescription_session_verified": false
},
{
"record_kind": "账号最近登录快照",
"source_table": "zyt_admin",
"source_fields": [
"login_time",
"login_ip"
],
"admin_id": 28,
"doctor_name": "赵俊霞",
"login_time": 1794801538,
"login_time_beijing": "2026-11-16 11:58:58",
"login_ip": "123.163.21.212",
"related_order_numbers": [
"PO20260908142548426588",
"PO20260924112640923356"
],
"association_basis": "处方 creator_id = 医生 admin.id",
"is_prescription_session_verified": false
}
],
"matched_login_operation_logs": [],
"per_order_findings": [
{
"order_no": "PO20260908142548426588",
"prescription_id": 9787,
"doctor_id": 28,
"doctor_name": "赵俊霞",
"prescription_create_time": 1788774166,
"prescription_create_time_beijing": "2026-09-07 17:42:46",
"prescription_day_login_status": "现有留存资料未检得匹配记录",
"matching_historical_login_event_count": 0
},
{
"order_no": "PO20260924112640923356",
"prescription_id": 10615,
"doctor_id": 28,
"doctor_name": "赵俊霞",
"prescription_create_time": 1790156255,
"prescription_create_time_beijing": "2026-09-23 17:37:35",
"prescription_day_login_status": "现有留存资料未检得匹配记录",
"matching_historical_login_event_count": 0
},
{
"order_no": "PO20261024092136816172",
"prescription_id": 11945,
"doctor_id": 12,
"doctor_name": "霍桢毅",
"prescription_create_time": 1792748278,
"prescription_create_time_beijing": "2026-10-23 17:37:58",
"prescription_day_login_status": "现有留存资料未检得匹配记录",
"matching_historical_login_event_count": 0
}
],
"operation_log_coverage": {
"total": 179,
"earliest_time": 1781149993,
"latest_time": 1791674406,
"earliest_time_beijing": "2026-06-11 11:53:13",
"latest_time_beijing": "2026-10-11 07:20:06"
},
"additional_checks": {
"identity_service_audit": {
"file": "identity-admin/server/runtime/group.sqlite",
"table": "group_audit",
"record_count": 44,
"earliest_beijing": "2026-10-30 14:02:05",
"latest_beijing": "2026-11-04 10:10:49",
"covers_target_prescription_days": false
},
"local_iam_v2_audit": "项目配置未启用 IAM V2 远端审计入口",
"local_application_logs": "未检得目标四个处方创建日的医生登录流水;2026-10-23已有应用日志不含登录事件"
},
"notes": [
"以下为账号保存的最近登录记录;关联依据为处方医生账号。现有留存资料未检得开方当天的匹配登录流水,无法确认具体处方的登录会话。",
"最近登录记录单独列示,不计入处方订单原始操作日志或签名时间线。"
]
} }
} }
@@ -1,5 +1,7 @@
三个处方业务订单:开方记录与药房操作日志 三个处方业务订单:医生签名与操作日志
导出时间:2026-11-18T16:50:09+08:00 导出时间:2026-11-18T16:50:09+08:00
本次更新:2026-11-23T11:54:23+08:00
签名时间默认取处方创建时间。
来源:项目 server/.env 指向的本机 MySQL 数据库 zyt(127.0.0.1:3306)。未核实与生产库同步情况;本报告仅证明当前查询库中保存的记录。 来源:项目 server/.env 指向的本机 MySQL 数据库 zyt(127.0.0.1:3306)。未核实与生产库同步情况;本报告仅证明当前查询库中保存的记录。
所有展示时间均为北京时间 UTC+08:00;JSON 同时保留 Unix 原始时间戳。查询使用只读事务,未修改业务数据。 所有展示时间均为北京时间 UTC+08:00;JSON 同时保留 Unix 原始时间戳。查询使用只读事务,未修改业务数据。
@@ -13,11 +15,21 @@
当前库订单表最新创建时间:2026-11-17 11:07:04(仅供判断数据范围,不代表同步时间) 当前库订单表最新创建时间:2026-11-17 11:07:04(仅供判断数据范围,不代表同步时间)
订单操作日志共 54 条;匹配后台请求日志 0 条;AI 触发记录 2 条;洛阳药房原始回传 1 条。 订单操作日志共 54 条;匹配后台请求日志 0 条;AI 触发记录 2 条;洛阳药房原始回传 1 条。
医生最近登录记录
查询时间:2026-11-23T12:15:47+08:00
以下为账号保存的最近登录记录;关联依据为处方医生账号。现有留存资料未检得开方当天的匹配登录流水,无法确认具体处方的登录会话。
2026-11-17 08:53:06 | 霍桢毅 / 账号 12 | 登录 IP:123.14.166.7 | 账号最近登录快照 | 关联订单:PO20261024092136816172
2026-11-16 11:58:58 | 赵俊霞 / 账号 28 | 登录 IP:123.163.21.212 | 账号最近登录快照 | 关联订单:PO20260908142548426588、PO20260924112640923356
来源字段:zyt_admin.login_time / login_ip;不计入原始订单日志条数。
======================================================================================== ========================================================================================
PO20261024092136816172 PO20261024092136816172
患者:雷柏生;诊单 ID:12167;业务订单 ID:4583 患者:雷柏生;诊单 ID:12167;业务订单 ID:4583
处方:RX202610233553(ID 11945);类型:浓缩水丸;名称:系统代开 处方:RX202610233553(ID 11945);类型:浓缩水丸;名称:系统代开
处方记录医生:霍桢毅(creator_id=12);创建时间:2026-10-23 17:37:58;处方日期:2026-10-23 处方记录医生:霍桢毅(creator_id=12);创建时间:2026-10-23 17:37:58;处方日期:2026-10-23
医生签名时间(默认):2026-10-23 17:37:58
医生签名:霍桢毅签名了
签名原图:PO20261024092136816172_医生签名原图.png
业务订单创建人:晁婷婷(ID 284);创建时间:2026-10-24 09:21:36 业务订单创建人:晁婷婷(ID 284);创建时间:2026-10-24 09:21:36
金额:1800.00;已付:1800.00;状态:已完成 金额:1800.00;已付:1800.00;状态:已完成
处方审核字段:李思佳(账号 ID 119);2026-10-26 10:04:14;audit_status=1;业务订单处方审核通过 处方审核字段:李思佳(账号 ID 119);2026-10-26 10:04:14;audit_status=1;业务订单处方审核通过
@@ -26,7 +38,9 @@ PO20261024092136816172
审方/撤审/人工补记日志(1 条) 审方/撤审/人工补记日志(1 条)
2026-10-26 10:04:14 | 日志 64976 | 原始署名 药房 / 账号 119 | audit_rx_approve | 处方审核通过 2026-10-26 10:04:14 | 日志 64976 | 原始署名 药房 / 账号 119 | audit_rx_approve | 处方审核通过
完整订单操作流水(10 条,按时间、日志 ID 升序) 综合时间线(1 条处方创建记录 + 1 条默认签名记录 + 10 条订单日志)
2026-10-23 17:37:58 | 处方创建记录 | 霍桢毅 / 账号 12 | 处方 RX202610233553 创建
2026-10-23 17:37:58 | 医生签名(默认时间) | 霍桢毅 / 账号 12 | 霍桢毅签名了
2026-10-24 09:21:36 | 日志 64682 | 晁婷婷 / 账号 284 | create | 创建业务订单 2026-10-24 09:21:36 | 日志 64682 | 晁婷婷 / 账号 284 | create | 创建业务订单
2026-10-26 09:32:57 | 日志 64957 | 李思佳 / 账号 119 | set_ship_mode | 发货类型:甘草药房 → 洛阳药房 2026-10-26 09:32:57 | 日志 64957 | 李思佳 / 账号 119 | set_ship_mode | 发货类型:甘草药房 → 洛阳药房
2026-10-26 10:02:04 | 日志 64975 | 李思佳 / 账号 119 | edit | 编辑了业务订单及相关信息 2026-10-26 10:02:04 | 日志 64975 | 李思佳 / 账号 119 | edit | 编辑了业务订单及相关信息
@@ -43,6 +57,9 @@ PO20260924112640923356
患者:雷柏生;诊单 ID:12167;业务订单 ID:4087 患者:雷柏生;诊单 ID:12167;业务订单 ID:4087
处方:RX202609238774(ID 10615);类型:浓缩水丸;名称:系统代开 处方:RX202609238774(ID 10615);类型:浓缩水丸;名称:系统代开
处方记录医生:赵俊霞(creator_id=28);创建时间:2026-09-23 17:37:35;处方日期:2026-09-23 处方记录医生:赵俊霞(creator_id=28);创建时间:2026-09-23 17:37:35;处方日期:2026-09-23
医生签名时间(默认):2026-09-23 17:37:35
医生签名:赵俊霞签名了
签名原图:PO20260924112640923356_医生签名原图.png
业务订单创建人:晁婷婷(ID 284);创建时间:2026-09-24 11:26:40 业务订单创建人:晁婷婷(ID 284);创建时间:2026-09-24 11:26:40
金额:1800.00;已付:0.00;状态:已完成 金额:1800.00;已付:0.00;状态:已完成
处方审核字段:焦珂(账号 ID 116);2026-09-24 16:17:19;audit_status=1;业务订单处方审核通过 处方审核字段:焦珂(账号 ID 116);2026-09-24 16:17:19;audit_status=1;业务订单处方审核通过
@@ -51,7 +68,9 @@ PO20260924112640923356
审方/撤审/人工补记日志(1 条) 审方/撤审/人工补记日志(1 条)
2026-09-24 16:17:19 | 日志 57801 | 原始署名 药房 / 账号 116 | audit_rx_approve | 处方审核通过 2026-09-24 16:17:19 | 日志 57801 | 原始署名 药房 / 账号 116 | audit_rx_approve | 处方审核通过
完整订单操作流水(36 条,按时间、日志 ID 升序) 综合时间线(1 条处方创建记录 + 1 条默认签名记录 + 36 条订单日志)
2026-09-23 17:37:35 | 处方创建记录 | 赵俊霞 / 账号 28 | 处方 RX202609238774 创建
2026-09-23 17:37:35 | 医生签名(默认时间) | 赵俊霞 / 账号 28 | 赵俊霞签名了
2026-09-24 11:26:40 | 日志 57681 | 晁婷婷 / 账号 284 | create | 创建业务订单 2026-09-24 11:26:40 | 日志 57681 | 晁婷婷 / 账号 284 | create | 创建业务订单
2026-09-24 16:14:48 | 日志 57792 | 焦珂 / 账号 116 | set_ship_mode | 发货类型:甘草药房 → 洛阳药房 2026-09-24 16:14:48 | 日志 57792 | 焦珂 / 账号 116 | set_ship_mode | 发货类型:甘草药房 → 洛阳药房
2026-09-24 16:14:54 | 日志 57793 | 焦珂 / 账号 116 | set_ship_mode | 发货类型:洛阳药房 → 甘草药房 2026-09-24 16:14:54 | 日志 57793 | 焦珂 / 账号 116 | set_ship_mode | 发货类型:洛阳药房 → 甘草药房
@@ -94,6 +113,9 @@ PO20260908142548426588
患者:雷柏生;诊单 ID:12167;业务订单 ID:3751 患者:雷柏生;诊单 ID:12167;业务订单 ID:3751
处方:RX202609078921(ID 9787);类型:浓缩水丸;名称:系统代开 处方:RX202609078921(ID 9787);类型:浓缩水丸;名称:系统代开
处方记录医生:赵俊霞(creator_id=28);创建时间:2026-09-07 17:42:46;处方日期:2026-09-07 处方记录医生:赵俊霞(creator_id=28);创建时间:2026-09-07 17:42:46;处方日期:2026-09-07
医生签名时间(默认):2026-09-07 17:42:46
医生签名:赵俊霞签名了
签名原图:PO20260908142548426588_医生签名原图.png
业务订单创建人:董肖妍(ID 279);创建时间:2026-09-08 14:25:48 业务订单创建人:董肖妍(ID 279);创建时间:2026-09-08 14:25:48
金额:1400.00;已付:1400.00;状态:已完成 金额:1400.00;已付:1400.00;状态:已完成
处方审核字段:焦珂(账号 ID 116);2026-09-09 11:48:48;audit_status=1;业务订单处方审核通过 处方审核字段:焦珂(账号 ID 116);2026-09-09 11:48:48;audit_status=1;业务订单处方审核通过
@@ -102,7 +124,9 @@ PO20260908142548426588
审方/撤审/人工补记日志(1 条) 审方/撤审/人工补记日志(1 条)
2026-09-09 11:48:48 | 日志 53014 | 原始署名 药房 / 账号 116 | audit_rx_approve | 处方审核通过 2026-09-09 11:48:48 | 日志 53014 | 原始署名 药房 / 账号 116 | audit_rx_approve | 处方审核通过
完整订单操作流水(8 条,按时间、日志 ID 升序) 综合时间线(1 条处方创建记录 + 1 条默认签名记录 + 8 条订单日志)
2026-09-07 17:42:46 | 处方创建记录 | 赵俊霞 / 账号 28 | 处方 RX202609078921 创建
2026-09-07 17:42:46 | 医生签名(默认时间) | 赵俊霞 / 账号 28 | 赵俊霞签名了
2026-09-08 14:25:48 | 日志 52702 | 董肖妍 / 账号 279 | create | 创建业务订单 2026-09-08 14:25:48 | 日志 52702 | 董肖妍 / 账号 279 | create | 创建业务订单
2026-09-09 10:58:36 | 日志 52953 | 焦珂 / 账号 116 | set_ship_mode | 发货类型:甘草药房 → 洛阳药房 2026-09-09 10:58:36 | 日志 52953 | 焦珂 / 账号 116 | set_ship_mode | 发货类型:甘草药房 → 洛阳药房
2026-09-09 11:46:56 | 日志 53013 | 焦珂 / 账号 116 | edit | 编辑了业务订单及相关信息 2026-09-09 11:46:56 | 日志 53013 | 焦珂 / 账号 116 | edit | 编辑了业务订单及相关信息
File diff suppressed because one or more lines are too long
@@ -0,0 +1,14 @@
{
"操作日志_原始字段.json": "f116f7fc6bc6fbe6d1d8aaa724c2bb5b8e74b6ac0c0689c3231adb35e7030f87",
"操作日志_完整明细.txt": "779df489f8967f8d5d568c0c11aa0a70c9dd7c47e9fb90fac9b83c46a6228ed1",
"操作日志_查看版.html": "a278109b509d9efc62c55c27ea0498077df3d598bc613459feba6174e8ebe9cb",
"只读查询.sql": "2080777f6a31f52d696bd137bca80d65e9ec9d65b25db06defd11bac64f5c822",
"医生开方补充_来源记录.json": "eac6837c9240c4eb06524c40571624823cc754813cd62e3f19c642e9fe852da0",
"医生开方补充_只读查询.sql": "0136f80677a12eb8cc99268aec8e9fbb4d18790bc9634398d376cf6200de988f",
"医生签名核查_来源记录.json": "6acaf26e44cb2dd828781d26e6dfe22c35f5d05ecca016fb15cebcc3c6afb488",
"医生签名核查_只读查询.sql": "c9fd8c853a89645532a674758308e764eb37f9748b346e396c100d984cce8c5f",
"医生签名_数据库原图.png": "f287ccf1c983fb55291e8886a9d4663efa6691fc3e6711fd8d2b5cab2542b116",
"医生签名_原图信息.json": "03d5b8c21a7b29f4691bdff657a7d7a71a91de7295b4186c2ce1ac6a9d6479d1",
"医生登录记录_来源字段.json": "9bbc28d9eb5d9ebb9fe5711f4f071422efc10333917d1713853ad165924bcd55",
"医生登录记录_只读查询.sql": "50a56f60a4d1c27703dd06e09233b50bf976fe3998c62914a5deca9d2ee6b615"
}
@@ -0,0 +1,11 @@
START TRANSACTION READ ONLY;
SELECT rx.id,rx.sn,rx.diagnosis_id,rx.patient_name,rx.doctor_name,rx.creator_id,a.name AS creator_current_name,rx.assistant_id,rx.is_system_auto,rx.prescription_name,rx.prescription_type,rx.prescription_date,rx.create_time,rx.update_time,rx.audit_status,rx.audit_time,rx.audit_by,rx.audit_by_name,rx.audit_remark,rx.void_status,rx.delete_time FROM zyt_tcm_prescription rx LEFT JOIN zyt_admin a ON a.id=rx.creator_id JOIN zyt_tcm_prescription_order po ON po.prescription_id=rx.id WHERE po.order_no='PO20261112171739443432';
SELECT id,prescription_id,prescription_revision,doctor_id,actor_id,trigger_type,reason,status,validity,created_at,updated_at FROM zyt_prescription_ai_batch WHERE prescription_id=13019 ORDER BY created_at,id;
SELECT COUNT(*) AS total,MIN(create_time) AS earliest_time,MAX(create_time) AS latest_time FROM zyt_operation_log;
SELECT id,admin_id,admin_name,action,type,SUBSTRING_INDEX(url,'?',1) AS endpoint,JSON_UNQUOTE(JSON_EXTRACT(IF(JSON_VALID(params),params,'{}'),'$.id')) AS request_id,JSON_UNQUOTE(JSON_EXTRACT(IF(JSON_VALID(params),params,'{}'),'$.prescription_id')) AS request_prescription_id,JSON_UNQUOTE(JSON_EXTRACT(IF(JSON_VALID(params),params,'{}'),'$.diagnosis_id')) AS request_diagnosis_id,JSON_UNQUOTE(JSON_EXTRACT(IF(JSON_VALID(result),result,'{}'),'$.data.id')) AS response_id,JSON_UNQUOTE(JSON_EXTRACT(IF(JSON_VALID(result),result,'{}'),'$.code')) AS response_code,create_time FROM zyt_operation_log WHERE LOWER(url) LIKE '%tcm.prescription/%' AND type='POST' AND (JSON_UNQUOTE(JSON_EXTRACT(IF(JSON_VALID(params),params,'{}'),'$.id'))='13019' OR JSON_UNQUOTE(JSON_EXTRACT(IF(JSON_VALID(params),params,'{}'),'$.prescription_id'))='13019' OR JSON_UNQUOTE(JSON_EXTRACT(IF(JSON_VALID(result),result,'{}'),'$.data.id'))='13019' OR (admin_id=25 AND create_time BETWEEN 1794468830 AND 1794469430)) ORDER BY create_time,id;
ROLLBACK;
@@ -0,0 +1,60 @@
{
"queried_at_beijing": "2026-11-23T11:40:17+08:00",
"source": {
"host": "127.0.0.1",
"database": "zyt",
"production_sync_verified": false
},
"prescription_record": {
"id": 13019,
"sn": "RX202611121933",
"diagnosis_id": 14902,
"patient_name": "高安民",
"doctor_name": "穆睿",
"creator_id": 25,
"creator_current_name": "穆睿",
"assistant_id": 280,
"is_system_auto": 0,
"prescription_name": "系统代开",
"prescription_type": "浓缩水丸",
"prescription_date": "2026-11-12",
"create_time": 1794469130,
"update_time": 1794534557,
"audit_status": 1,
"audit_time": 1794534557,
"audit_by": 116,
"audit_by_name": "药房1",
"audit_remark": "业务订单处方审核通过",
"void_status": 0,
"delete_time": null,
"create_time_beijing": "2026-11-12 15:38:50",
"update_time_beijing": "2026-11-13 09:49:17",
"audit_time_beijing": "2026-11-13 09:49:17",
"delete_time_beijing": "—"
},
"prescription_operation_log_candidates": [],
"prescription_ai_events": [
{
"id": 7261,
"prescription_id": 13019,
"prescription_revision": 1,
"doctor_id": 25,
"actor_id": 25,
"trigger_type": "source_update",
"reason": "患者资料或问诊转写已更新",
"status": "running",
"validity": "current",
"created_at": 1794883991,
"updated_at": 1794883997,
"created_at_beijing": "2026-11-17 10:53:11",
"updated_at_beijing": "2026-11-17 10:53:17"
}
],
"operation_log_coverage": {
"total": 179,
"earliest_time": 1781149993,
"latest_time": 1791674406,
"earliest_time_beijing": "2026-06-11 11:53:13",
"latest_time_beijing": "2026-10-11 07:20:06"
}
}
@@ -0,0 +1,13 @@
START TRANSACTION READ ONLY;
SELECT id,name,login_time,login_ip FROM zyt_admin WHERE id IN (12,25,28) ORDER BY id;
SELECT id,admin_id,terminal,update_time,expire_time FROM zyt_admin_session WHERE admin_id IN (12,25,28) ORDER BY admin_id,update_time,id;
SELECT DISTINCT ol.id,ol.admin_id,ol.admin_name,a.id AS matched_doctor_id,a.name AS matched_doctor_name,ol.action,ol.type,SUBSTRING_INDEX(ol.url,'?',1) AS endpoint,ol.ip,ol.create_time,JSON_UNQUOTE(JSON_EXTRACT(IF(JSON_VALID(ol.result),ol.result,'{}'),'$.code')) AS response_code,JSON_UNQUOTE(JSON_EXTRACT(IF(JSON_VALID(ol.result),ol.result,'{}'),'$.msg')) AS response_message FROM zyt_operation_log ol JOIN zyt_admin a ON (a.id=ol.admin_id OR (a.account<>'' AND a.account=ol.account) OR (a.account<>'' AND a.account=JSON_UNQUOTE(JSON_EXTRACT(IF(JSON_VALID(ol.params),ol.params,'{}'),'$.account'))) OR a.id=JSON_UNQUOTE(JSON_EXTRACT(IF(JSON_VALID(ol.result),ol.result,'{}'),'$.data.id')) OR a.id=JSON_UNQUOTE(JSON_EXTRACT(IF(JSON_VALID(ol.result),ol.result,'{}'),'$.data.admin_id'))) WHERE a.id IN (12,25,28) AND (LOWER(ol.url) LIKE '%/login/%' OR LOWER(ol.url) LIKE '%/identity.session/%' OR ol.action LIKE '%登录%') ORDER BY ol.create_time,ol.id;
SELECT COUNT(*) AS total,MIN(create_time) AS earliest_time,MAX(create_time) AS latest_time FROM zyt_operation_log;
SELECT SUBSTRING_INDEX(url,'?',1) AS endpoint,COUNT(*) AS records,MIN(create_time) AS earliest_time,MAX(create_time) AS latest_time FROM zyt_operation_log WHERE LOWER(url) LIKE '%/login/%' OR LOWER(url) LIKE '%/identity.session/%' OR action LIKE '%登录%' GROUP BY SUBSTRING_INDEX(url,'?',1);
ROLLBACK;
@@ -0,0 +1,64 @@
{
"queried_at_beijing": "2026-11-23T12:15:47+08:00",
"source": {
"host": "127.0.0.1",
"database": "zyt",
"production_sync_verified": false
},
"doctor_last_login_snapshots": [
{
"record_kind": "账号最近登录快照",
"source_table": "zyt_admin",
"source_fields": [
"login_time",
"login_ip"
],
"admin_id": 25,
"doctor_name": "穆睿",
"login_time": 1794878314,
"login_time_beijing": "2026-11-17 09:18:34",
"login_ip": "123.14.166.7",
"related_order_numbers": [
"PO20261112171739443432"
],
"association_basis": "处方 creator_id = 医生 admin.id",
"is_prescription_session_verified": false
}
],
"matched_login_operation_logs": [],
"per_order_findings": [
{
"order_no": "PO20261112171739443432",
"prescription_id": 13019,
"doctor_id": 25,
"doctor_name": "穆睿",
"prescription_create_time": 1794469130,
"prescription_create_time_beijing": "2026-11-12 15:38:50",
"prescription_day_login_status": "现有留存资料未检得匹配记录",
"matching_historical_login_event_count": 0
}
],
"operation_log_coverage": {
"total": 179,
"earliest_time": 1781149993,
"latest_time": 1791674406,
"earliest_time_beijing": "2026-06-11 11:53:13",
"latest_time_beijing": "2026-10-11 07:20:06"
},
"additional_checks": {
"identity_service_audit": {
"file": "identity-admin/server/runtime/group.sqlite",
"table": "group_audit",
"record_count": 44,
"earliest_beijing": "2026-10-30 14:02:05",
"latest_beijing": "2026-11-04 10:10:49",
"covers_target_prescription_days": false
},
"local_iam_v2_audit": "项目配置未启用 IAM V2 远端审计入口",
"local_application_logs": "未检得目标四个处方创建日的医生登录流水;2026-10-23已有应用日志不含登录事件"
},
"notes": [
"以下为账号保存的最近登录记录;关联依据为处方医生账号。现有留存资料未检得开方当天的匹配登录流水,无法确认具体处方的登录会话。",
"最近登录记录单独列示,不计入处方订单原始操作日志或签名时间线。"
]
}
@@ -0,0 +1,18 @@
{
"order_no": "PO20261112171739443432",
"prescription_id": 13019,
"prescription_sn": "RX202611121933",
"doctor_name": "穆睿",
"source": "zyt_tcm_prescription.doctor_signature",
"extracted_at_beijing": "2026-11-23T11:46:37+08:00",
"file": "医生签名_数据库原图.png",
"image_format": "PNG",
"width": 1000,
"height": 300,
"bytes": 22630,
"sha256": "f287ccf1c983fb55291e8886a9d4663efa6691fc3e6711fd8d2b5cab2542b116",
"embedded_text": {},
"image_info_keys": [
"dpi"
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

@@ -0,0 +1,17 @@
START TRANSACTION READ ONLY;
SELECT TABLE_NAME,COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND (TABLE_NAME LIKE '%esign%' OR TABLE_NAME LIKE '%signature%') ORDER BY TABLE_NAME,ORDINAL_POSITION;
SELECT rx.id,rx.sn,rx.doctor_name,rx.creator_id,rx.esign_required,rx.esign_status,rx.create_time,rx.update_time,CASE WHEN COALESCE(TRIM(rx.doctor_signature),'')='' THEN 0 ELSE 1 END AS has_doctor_signature,OCTET_LENGTH(COALESCE(rx.doctor_signature,'')) AS signature_bytes,CASE WHEN rx.doctor_signature LIKE 'data:image/%' THEN 'image_data_uri' WHEN COALESCE(TRIM(rx.doctor_signature),'')='' THEN 'empty' ELSE 'other' END AS signature_storage_format FROM zyt_tcm_prescription rx JOIN zyt_tcm_prescription_order po ON po.prescription_id=rx.id WHERE po.order_no='PO20261112171739443432';
SELECT `prescription_id`,`doctor_id`,`signer_name`,`environment`,`started_at`,`issued_at`,`signed_at`,`signature_time`,`signature_time_source`,`create_time`,`update_time`,`error_message` FROM `zyt_prescription_esign` WHERE prescription_id=13019;
SELECT `prescription_id`,`signer_name`,`environment`,`state`,`reviewer_id`,`signature_time`,`update_time`,`error_message` FROM `zyt_prescription_review_esign` WHERE prescription_id=13019;
SELECT id,admin_id,admin_name,action,type,SUBSTRING_INDEX(url,'?',1) AS endpoint,create_time FROM zyt_operation_log WHERE LOWER(url) LIKE '%tcm.prescription/%' AND (JSON_UNQUOTE(JSON_EXTRACT(IF(JSON_VALID(params),params,'{}'),'$.id'))='13019' OR JSON_UNQUOTE(JSON_EXTRACT(IF(JSON_VALID(params),params,'{}'),'$.prescription_id'))='13019' OR JSON_UNQUOTE(JSON_EXTRACT(IF(JSON_VALID(result),result,'{}'),'$.data.id'))='13019') ORDER BY create_time,id;
SELECT id,admin_id,admin_name,action,summary,create_time FROM zyt_tcm_prescription_order_log WHERE prescription_order_id=4990 AND (action LIKE '%esign%' OR action LIKE '%signature%' OR summary LIKE '%签名%' OR summary LIKE '%签署%') ORDER BY create_time,id;
SELECT COUNT(*) AS total,MIN(create_time) AS earliest_time,MAX(create_time) AS latest_time FROM zyt_operation_log;
ROLLBACK;
@@ -0,0 +1,338 @@
{
"queried_at_beijing": "2026-11-23T11:44:17+08:00",
"source": {
"host": "127.0.0.1",
"database": "zyt",
"production_sync_verified": false
},
"prescription_signature_metadata": {
"id": 13019,
"sn": "RX202611121933",
"doctor_name": "穆睿",
"creator_id": 25,
"esign_required": 0,
"esign_status": "legacy",
"create_time": 1794469130,
"update_time": 1794534557,
"has_doctor_signature": 1,
"signature_bytes": 30198,
"signature_storage_format": "image_data_uri",
"create_time_beijing": "2026-11-12 15:38:50",
"update_time_beijing": "2026-11-13 09:49:17"
},
"prescription_esign_evidence": {
"zyt_prescription_esign": [],
"zyt_prescription_review_esign": []
},
"matched_operation_logs": [],
"matched_order_signature_logs": [],
"operation_log_coverage": {
"total": 179,
"earliest_time": 1781149993,
"latest_time": 1791674406,
"earliest_time_beijing": "2026-06-11 11:53:13",
"latest_time_beijing": "2026-10-11 07:20:06"
},
"signature_schema": [
{
"TABLE_NAME": "zyt_doctor_esign_account",
"COLUMN_NAME": "id"
},
{
"TABLE_NAME": "zyt_doctor_esign_account",
"COLUMN_NAME": "doctor_id"
},
{
"TABLE_NAME": "zyt_doctor_esign_account",
"COLUMN_NAME": "environment"
},
{
"TABLE_NAME": "zyt_doctor_esign_account",
"COLUMN_NAME": "app_id"
},
{
"TABLE_NAME": "zyt_doctor_esign_account",
"COLUMN_NAME": "account_id"
},
{
"TABLE_NAME": "zyt_doctor_esign_account",
"COLUMN_NAME": "doctor_name"
},
{
"TABLE_NAME": "zyt_doctor_esign_account",
"COLUMN_NAME": "create_time"
},
{
"TABLE_NAME": "zyt_doctor_esign_identity",
"COLUMN_NAME": "doctor_id"
},
{
"TABLE_NAME": "zyt_doctor_esign_identity",
"COLUMN_NAME": "environment"
},
{
"TABLE_NAME": "zyt_doctor_esign_identity",
"COLUMN_NAME": "app_id"
},
{
"TABLE_NAME": "zyt_doctor_esign_identity",
"COLUMN_NAME": "doctor_name"
},
{
"TABLE_NAME": "zyt_doctor_esign_identity",
"COLUMN_NAME": "account_id"
},
{
"TABLE_NAME": "zyt_doctor_esign_identity",
"COLUMN_NAME": "flow_id"
},
{
"TABLE_NAME": "zyt_doctor_esign_identity",
"COLUMN_NAME": "auth_url"
},
{
"TABLE_NAME": "zyt_doctor_esign_identity",
"COLUMN_NAME": "mobile_hash"
},
{
"TABLE_NAME": "zyt_doctor_esign_identity",
"COLUMN_NAME": "flow_started_at"
},
{
"TABLE_NAME": "zyt_doctor_esign_identity",
"COLUMN_NAME": "operation_token"
},
{
"TABLE_NAME": "zyt_doctor_esign_identity",
"COLUMN_NAME": "operation_expires_at"
},
{
"TABLE_NAME": "zyt_doctor_esign_quicksign",
"COLUMN_NAME": "doctor_id"
},
{
"TABLE_NAME": "zyt_doctor_esign_quicksign",
"COLUMN_NAME": "environment"
},
{
"TABLE_NAME": "zyt_doctor_esign_quicksign",
"COLUMN_NAME": "app_id"
},
{
"TABLE_NAME": "zyt_doctor_esign_quicksign",
"COLUMN_NAME": "doctor_name"
},
{
"TABLE_NAME": "zyt_doctor_esign_quicksign",
"COLUMN_NAME": "account_id"
},
{
"TABLE_NAME": "zyt_doctor_esign_quicksign",
"COLUMN_NAME": "flow_id"
},
{
"TABLE_NAME": "zyt_doctor_esign_quicksign",
"COLUMN_NAME": "auth_url"
},
{
"TABLE_NAME": "zyt_doctor_esign_quicksign",
"COLUMN_NAME": "flow_started_at"
},
{
"TABLE_NAME": "zyt_doctor_esign_quicksign",
"COLUMN_NAME": "expires_at"
},
{
"TABLE_NAME": "zyt_doctor_esign_quicksign",
"COLUMN_NAME": "operation_token"
},
{
"TABLE_NAME": "zyt_doctor_esign_quicksign",
"COLUMN_NAME": "operation_expires_at"
},
{
"TABLE_NAME": "zyt_prescription_esign",
"COLUMN_NAME": "prescription_id"
},
{
"TABLE_NAME": "zyt_prescription_esign",
"COLUMN_NAME": "doctor_id"
},
{
"TABLE_NAME": "zyt_prescription_esign",
"COLUMN_NAME": "environment"
},
{
"TABLE_NAME": "zyt_prescription_esign",
"COLUMN_NAME": "app_id"
},
{
"TABLE_NAME": "zyt_prescription_esign",
"COLUMN_NAME": "snapshot_hash"
},
{
"TABLE_NAME": "zyt_prescription_esign",
"COLUMN_NAME": "source_hash"
},
{
"TABLE_NAME": "zyt_prescription_esign",
"COLUMN_NAME": "source_path"
},
{
"TABLE_NAME": "zyt_prescription_esign",
"COLUMN_NAME": "signed_path"
},
{
"TABLE_NAME": "zyt_prescription_esign",
"COLUMN_NAME": "signed_hash"
},
{
"TABLE_NAME": "zyt_prescription_esign",
"COLUMN_NAME": "flow_id"
},
{
"TABLE_NAME": "zyt_prescription_esign",
"COLUMN_NAME": "auth_url"
},
{
"TABLE_NAME": "zyt_prescription_esign",
"COLUMN_NAME": "account_id"
},
{
"TABLE_NAME": "zyt_prescription_esign",
"COLUMN_NAME": "sign_service_id"
},
{
"TABLE_NAME": "zyt_prescription_esign",
"COLUMN_NAME": "operation_token"
},
{
"TABLE_NAME": "zyt_prescription_esign",
"COLUMN_NAME": "error_message"
},
{
"TABLE_NAME": "zyt_prescription_esign",
"COLUMN_NAME": "started_at"
},
{
"TABLE_NAME": "zyt_prescription_esign",
"COLUMN_NAME": "signed_at"
},
{
"TABLE_NAME": "zyt_prescription_esign",
"COLUMN_NAME": "create_time"
},
{
"TABLE_NAME": "zyt_prescription_esign",
"COLUMN_NAME": "update_time"
},
{
"TABLE_NAME": "zyt_prescription_esign",
"COLUMN_NAME": "signer_name"
},
{
"TABLE_NAME": "zyt_prescription_esign",
"COLUMN_NAME": "signature_time"
},
{
"TABLE_NAME": "zyt_prescription_esign",
"COLUMN_NAME": "signature_time_source"
},
{
"TABLE_NAME": "zyt_prescription_esign",
"COLUMN_NAME": "issued_at"
},
{
"TABLE_NAME": "zyt_prescription_esign",
"COLUMN_NAME": "auth_method"
},
{
"TABLE_NAME": "zyt_prescription_esign",
"COLUMN_NAME": "sms_sent_at"
},
{
"TABLE_NAME": "zyt_prescription_esign",
"COLUMN_NAME": "sms_verified_at"
},
{
"TABLE_NAME": "zyt_prescription_esign",
"COLUMN_NAME": "sms_attempts"
},
{
"TABLE_NAME": "zyt_prescription_esign",
"COLUMN_NAME": "doctor_setup_required"
},
{
"TABLE_NAME": "zyt_prescription_esign",
"COLUMN_NAME": "review_required"
},
{
"TABLE_NAME": "zyt_prescription_review_esign",
"COLUMN_NAME": "prescription_id"
},
{
"TABLE_NAME": "zyt_prescription_review_esign",
"COLUMN_NAME": "reviewer_id"
},
{
"TABLE_NAME": "zyt_prescription_review_esign",
"COLUMN_NAME": "signer_name"
},
{
"TABLE_NAME": "zyt_prescription_review_esign",
"COLUMN_NAME": "environment"
},
{
"TABLE_NAME": "zyt_prescription_review_esign",
"COLUMN_NAME": "app_id"
},
{
"TABLE_NAME": "zyt_prescription_review_esign",
"COLUMN_NAME": "account_id"
},
{
"TABLE_NAME": "zyt_prescription_review_esign",
"COLUMN_NAME": "reviewer_certificate"
},
{
"TABLE_NAME": "zyt_prescription_review_esign",
"COLUMN_NAME": "doctor_signature"
},
{
"TABLE_NAME": "zyt_prescription_review_esign",
"COLUMN_NAME": "doctor_pdf_hash"
},
{
"TABLE_NAME": "zyt_prescription_review_esign",
"COLUMN_NAME": "state"
},
{
"TABLE_NAME": "zyt_prescription_review_esign",
"COLUMN_NAME": "operation_token"
},
{
"TABLE_NAME": "zyt_prescription_review_esign",
"COLUMN_NAME": "confirmed_at"
},
{
"TABLE_NAME": "zyt_prescription_review_esign",
"COLUMN_NAME": "update_time"
},
{
"TABLE_NAME": "zyt_prescription_review_esign",
"COLUMN_NAME": "sign_service_id"
},
{
"TABLE_NAME": "zyt_prescription_review_esign",
"COLUMN_NAME": "signed_hash"
},
{
"TABLE_NAME": "zyt_prescription_review_esign",
"COLUMN_NAME": "signature_time"
},
{
"TABLE_NAME": "zyt_prescription_review_esign",
"COLUMN_NAME": "error_message"
}
]
}
@@ -0,0 +1,7 @@
START TRANSACTION READ ONLY;
SELECT po.id,po.order_no,po.prescription_id,po.diagnosis_id,po.creator_id,po.amount,po.paid,po.fulfillment_status,po.ship_mode,po.tracking_number,po.prescription_audit_status,po.prescription_audit_remark,po.payment_slip_audit_status,po.payment_slip_audit_remark,po.create_time,po.update_time,po.delete_time,rx.sn AS prescription_sn,rx.patient_name,rx.doctor_name,rx.audit_by,rx.audit_by_name,rx.audit_time FROM zyt_tcm_prescription_order po LEFT JOIN zyt_tcm_prescription rx ON rx.id=po.prescription_id WHERE po.order_no='PO20261112171739443432';
SELECT id,prescription_order_id,admin_id,admin_name,action,summary,create_time FROM zyt_tcm_prescription_order_log WHERE prescription_order_id=4990 ORDER BY create_time,id;
ROLLBACK;
@@ -0,0 +1,475 @@
{
"export_time_beijing": "2026-11-23T11:02:11+08:00",
"source": {
"config": "server/.env",
"host": "127.0.0.1",
"port": 3306,
"database": "zyt",
"production_sync_verified": false
},
"notes": [
"来源:server/.env 指向的本机 MySQL 数据库 zyt。未核实与生产库同步情况,以下为本次查询库中保存的全部该订单操作日志。",
"所有展示时间均为北京时间 UTC+08:00;JSON 保留原始 Unix 时间戳。日志按 create_time、id 升序排列。",
"日志原始 admin_name、admin_id、action、summary 均原样保留;自动回传代表系统事件,不代表人工操作。",
"本次使用只读事务,未修改业务数据。",
"综合时间线共 14 条记录:1 条处方创建记录、1 条签名时间默认值、12 条原始订单操作日志。",
"医生开方补充来源为 zyt_tcm_prescription 的 doctor_name、creator_id、create_time。关联医生为穆睿(ID 25),处方创建时间为 2026-11-12 15:38:50;未查到独立开方请求日志,不能据此确认医生实际点击保存或修改的时间。",
"处方名称原值为“系统代开”,is_system_auto 当前值为 0。两个当前字段不足以还原首次代开及后续手动编辑过程,均保留在原始字段中。",
"关联 AI 批次 7261 的 trigger_type 为 source_update(患者资料或问诊转写已更新),发生于 2026-11-17 10:53:11,不作为医生开方日志。",
"当前查询库的通用操作日志最晚记录时间为 2026-10-11 07:20:06,未覆盖本张处方创建日期。当前代码关闭该日志写入,不能据此判断历史每个时段的启用状态。",
"签名时间默认取处方创建时间。",
"以下为账号保存的最近登录记录;关联依据为处方医生账号。现有留存资料未检得开方当天的匹配登录流水,无法确认具体处方的登录会话。"
],
"order": {
"id": 4990,
"order_no": "PO20261112171739443432",
"prescription_id": 13019,
"diagnosis_id": 14902,
"creator_id": 280,
"amount": "1182.00",
"paid": "1182.00",
"fulfillment_status": 3,
"ship_mode": "direct",
"tracking_number": "JDVE19631919051",
"prescription_audit_status": 1,
"prescription_audit_remark": "",
"payment_slip_audit_status": 1,
"payment_slip_audit_remark": "",
"create_time": 1794475059,
"update_time": 1795402849,
"delete_time": null,
"prescription_sn": "RX202611121933",
"patient_name": "高安民",
"doctor_name": "穆睿",
"audit_by": 116,
"audit_by_name": "药房1",
"audit_time": 1794534557,
"create_time_beijing": "2026-11-12 17:17:39",
"update_time_beijing": "2026-11-23 11:00:49",
"delete_time_beijing": "—",
"audit_time_beijing": "2026-11-13 09:49:17"
},
"order_log_count": 12,
"order_logs": [
{
"id": 70346,
"prescription_order_id": 4990,
"admin_id": 280,
"admin_name": "许可",
"action": "create",
"summary": "创建业务订单",
"create_time": 1794475059,
"create_time_beijing": "2026-11-12 17:17:39"
},
{
"id": 70399,
"prescription_order_id": 4990,
"admin_id": 116,
"admin_name": "药房1",
"action": "set_ship_mode",
"summary": "发货类型:甘草药房 → 洛阳药房",
"create_time": 1794534084,
"create_time_beijing": "2026-11-13 09:41:24"
},
{
"id": 70400,
"prescription_order_id": 4990,
"admin_id": 116,
"admin_name": "药房1",
"action": "edit",
"summary": "编辑了业务订单及相关信息",
"create_time": 1794534122,
"create_time_beijing": "2026-11-13 09:42:02"
},
{
"id": 70401,
"prescription_order_id": 4990,
"admin_id": 116,
"admin_name": "药房1",
"action": "audit_rx_approve",
"summary": "处方审核通过",
"create_time": 1794534557,
"create_time_beijing": "2026-11-13 09:49:17"
},
{
"id": 70402,
"prescription_order_id": 4990,
"admin_id": 116,
"admin_name": "药房1",
"action": "audit_pay_approve",
"summary": "支付单审核通过",
"create_time": 1794534561,
"create_time_beijing": "2026-11-13 09:49:21"
},
{
"id": 70403,
"prescription_order_id": 4990,
"admin_id": 116,
"admin_name": "药房1",
"action": "ej_pharmacy_submit",
"summary": "上传洛阳药房成功 EJ2026111309492456EADB",
"create_time": 1794534564,
"create_time_beijing": "2026-11-13 09:49:24"
},
{
"id": 70404,
"prescription_order_id": 4990,
"admin_id": 0,
"admin_name": "洛阳药房ERP",
"action": "ej_pharmacy_callback",
"summary": "洛阳药房回传:订单已创建;远端状态:待审核;履约状态:待发货/发货与履约 → 待发货/发货与履约;(版本已处理,保留回传日志)",
"create_time": 1794534601,
"create_time_beijing": "2026-11-13 09:50:01"
},
{
"id": 70552,
"prescription_order_id": 4990,
"admin_id": 203,
"admin_name": "张卫霞",
"action": "ship",
"summary": "确认发货(药房直发),运单:JDVE19631919051(auto)",
"create_time": 1794549986,
"create_time_beijing": "2026-11-13 14:06:26"
},
{
"id": 71490,
"prescription_order_id": 4990,
"admin_id": 0,
"admin_name": "系统",
"action": "auto_sign",
"summary": "物流签收(运单:JDVE19631919051),订单状态自动更新为「已签收」",
"create_time": 1794825019,
"create_time_beijing": "2026-11-16 18:30:19"
},
{
"id": 71517,
"prescription_order_id": 4990,
"admin_id": 280,
"admin_name": "许可",
"action": "add_pay_order",
"summary": "新增支付单 #33791(¥850),类型:3,等待支付审核,并申请完成订单",
"create_time": 1794881042,
"create_time_beijing": "2026-11-17 10:04:02"
},
{
"id": 71549,
"prescription_order_id": 4990,
"admin_id": 1,
"admin_name": "admin",
"action": "auto_complete",
"summary": "支付审核通过,根据完单申请自动完成订单,实付金额更新为 ¥1182.00",
"create_time": 1795402849,
"create_time_beijing": "2026-11-23 11:00:49"
},
{
"id": 71550,
"prescription_order_id": 4990,
"admin_id": 1,
"admin_name": "admin",
"action": "audit_pay_approve",
"summary": "支付单审核通过",
"create_time": 1795402849,
"create_time_beijing": "2026-11-23 11:00:49"
}
],
"supplemented_at_beijing": "2026-11-23T11:40:17+08:00",
"prescription_record": {
"id": 13019,
"sn": "RX202611121933",
"diagnosis_id": 14902,
"patient_name": "高安民",
"doctor_name": "穆睿",
"creator_id": 25,
"creator_current_name": "穆睿",
"assistant_id": 280,
"is_system_auto": 0,
"prescription_name": "系统代开",
"prescription_type": "浓缩水丸",
"prescription_date": "2026-11-12",
"create_time": 1794469130,
"update_time": 1794534557,
"audit_status": 1,
"audit_time": 1794534557,
"audit_by": 116,
"audit_by_name": "药房1",
"audit_remark": "业务订单处方审核通过",
"void_status": 0,
"delete_time": null,
"create_time_beijing": "2026-11-12 15:38:50",
"update_time_beijing": "2026-11-13 09:49:17",
"audit_time_beijing": "2026-11-13 09:49:17",
"delete_time_beijing": "—"
},
"prescription_operation_log_candidates": [],
"prescription_ai_events": [
{
"id": 7261,
"prescription_id": 13019,
"prescription_revision": 1,
"doctor_id": 25,
"actor_id": 25,
"trigger_type": "source_update",
"reason": "患者资料或问诊转写已更新",
"status": "running",
"validity": "current",
"created_at": 1794883991,
"updated_at": 1794883997,
"created_at_beijing": "2026-11-17 10:53:11",
"updated_at_beijing": "2026-11-17 10:53:17"
}
],
"operation_log_coverage": {
"total": 179,
"earliest_time": 1781149993,
"latest_time": 1791674406,
"earliest_time_beijing": "2026-06-11 11:53:13",
"latest_time_beijing": "2026-10-11 07:20:06"
},
"timeline_record_count": 14,
"combined_timeline": [
{
"record_kind": "处方创建记录(补充)",
"source_table": "zyt_tcm_prescription",
"source_id": 13019,
"create_time": 1794469130,
"time_beijing": "2026-11-12 15:38:50",
"display_name": "穆睿",
"admin_id": 25,
"action": "prescription_record_created",
"summary": "处方 RX202611121933 创建;关联医生 穆睿。来自处方主记录,非独立开方请求日志。"
},
{
"record_kind": "医生签名(默认时间)",
"source_table": "zyt_tcm_prescription",
"source_id": 13019,
"source_field": "create_time",
"create_time": 1794469130,
"time_beijing": "2026-11-12 15:38:50",
"display_name": "穆睿",
"admin_id": 25,
"action": "signature_time_default",
"is_default": true,
"summary": "穆睿签名了",
"display_text": "穆睿签名了",
"time_basis": "签名时间默认取处方创建时间。"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 70346,
"create_time": 1794475059,
"time_beijing": "2026-11-12 17:17:39",
"display_name": "许可",
"admin_id": 280,
"action": "create",
"summary": "创建业务订单"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 70399,
"create_time": 1794534084,
"time_beijing": "2026-11-13 09:41:24",
"display_name": "药房1",
"admin_id": 116,
"action": "set_ship_mode",
"summary": "发货类型:甘草药房 → 洛阳药房"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 70400,
"create_time": 1794534122,
"time_beijing": "2026-11-13 09:42:02",
"display_name": "药房1",
"admin_id": 116,
"action": "edit",
"summary": "编辑了业务订单及相关信息"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 70401,
"create_time": 1794534557,
"time_beijing": "2026-11-13 09:49:17",
"display_name": "药房1",
"admin_id": 116,
"action": "audit_rx_approve",
"summary": "处方审核通过"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 70402,
"create_time": 1794534561,
"time_beijing": "2026-11-13 09:49:21",
"display_name": "药房1",
"admin_id": 116,
"action": "audit_pay_approve",
"summary": "支付单审核通过"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 70403,
"create_time": 1794534564,
"time_beijing": "2026-11-13 09:49:24",
"display_name": "药房1",
"admin_id": 116,
"action": "ej_pharmacy_submit",
"summary": "上传洛阳药房成功 EJ2026111309492456EADB"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 70404,
"create_time": 1794534601,
"time_beijing": "2026-11-13 09:50:01",
"display_name": "洛阳药房ERP",
"admin_id": 0,
"action": "ej_pharmacy_callback",
"summary": "洛阳药房回传:订单已创建;远端状态:待审核;履约状态:待发货/发货与履约 → 待发货/发货与履约;(版本已处理,保留回传日志)"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 70552,
"create_time": 1794549986,
"time_beijing": "2026-11-13 14:06:26",
"display_name": "张卫霞",
"admin_id": 203,
"action": "ship",
"summary": "确认发货(药房直发),运单:JDVE19631919051(auto)"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 71490,
"create_time": 1794825019,
"time_beijing": "2026-11-16 18:30:19",
"display_name": "系统",
"admin_id": 0,
"action": "auto_sign",
"summary": "物流签收(运单:JDVE19631919051),订单状态自动更新为「已签收」"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 71517,
"create_time": 1794881042,
"time_beijing": "2026-11-17 10:04:02",
"display_name": "许可",
"admin_id": 280,
"action": "add_pay_order",
"summary": "新增支付单 #33791(¥850),类型:3,等待支付审核,并申请完成订单"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 71549,
"create_time": 1795402849,
"time_beijing": "2026-11-23 11:00:49",
"display_name": "admin",
"admin_id": 1,
"action": "auto_complete",
"summary": "支付审核通过,根据完单申请自动完成订单,实付金额更新为 ¥1182.00"
},
{
"record_kind": "订单操作日志",
"source_table": "zyt_tcm_prescription_order_log",
"source_id": 71550,
"create_time": 1795402849,
"time_beijing": "2026-11-23 11:00:49",
"display_name": "admin",
"admin_id": 1,
"action": "audit_pay_approve",
"summary": "支付单审核通过"
}
],
"report_updated_at_beijing": "2026-11-23T12:18:20+08:00",
"reporting_defaults": {
"doctor_signature_time": {
"value": 1794469130,
"value_beijing": "2026-11-12 15:38:50",
"doctor_name": "穆睿",
"doctor_id": 25,
"is_default": true,
"source_field": "zyt_tcm_prescription.create_time",
"source_record_id": 13019,
"rule": "签名时间默认取处方创建时间。"
}
},
"doctor_signature_image": {
"file": "医生签名_数据库原图.png",
"source_field": "zyt_tcm_prescription.doctor_signature",
"prescription_id": 13019,
"doctor_name": "穆睿",
"sha256": "f287ccf1c983fb55291e8886a9d4663efa6691fc3e6711fd8d2b5cab2542b116",
"width": 1000,
"height": 300
},
"doctor_login_records": {
"queried_at_beijing": "2026-11-23T12:15:47+08:00",
"source": {
"host": "127.0.0.1",
"database": "zyt",
"production_sync_verified": false
},
"doctor_last_login_snapshots": [
{
"record_kind": "账号最近登录快照",
"source_table": "zyt_admin",
"source_fields": [
"login_time",
"login_ip"
],
"admin_id": 25,
"doctor_name": "穆睿",
"login_time": 1794878314,
"login_time_beijing": "2026-11-17 09:18:34",
"login_ip": "123.14.166.7",
"related_order_numbers": [
"PO20261112171739443432"
],
"association_basis": "处方 creator_id = 医生 admin.id",
"is_prescription_session_verified": false
}
],
"matched_login_operation_logs": [],
"per_order_findings": [
{
"order_no": "PO20261112171739443432",
"prescription_id": 13019,
"doctor_id": 25,
"doctor_name": "穆睿",
"prescription_create_time": 1794469130,
"prescription_create_time_beijing": "2026-11-12 15:38:50",
"prescription_day_login_status": "现有留存资料未检得匹配记录",
"matching_historical_login_event_count": 0
}
],
"operation_log_coverage": {
"total": 179,
"earliest_time": 1781149993,
"latest_time": 1791674406,
"earliest_time_beijing": "2026-06-11 11:53:13",
"latest_time_beijing": "2026-10-11 07:20:06"
},
"additional_checks": {
"identity_service_audit": {
"file": "identity-admin/server/runtime/group.sqlite",
"table": "group_audit",
"record_count": 44,
"earliest_beijing": "2026-10-30 14:02:05",
"latest_beijing": "2026-11-04 10:10:49",
"covers_target_prescription_days": false
},
"local_iam_v2_audit": "项目配置未启用 IAM V2 远端审计入口",
"local_application_logs": "未检得目标四个处方创建日的医生登录流水;2026-10-23已有应用日志不含登录事件"
},
"notes": [
"以下为账号保存的最近登录记录;关联依据为处方医生账号。现有留存资料未检得开方当天的匹配登录流水,无法确认具体处方的登录会话。",
"最近登录记录单独列示,不计入处方订单原始操作日志或签名时间线。"
]
}
}

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