更新
This commit is contained in:
+109
-3
@@ -376,6 +376,8 @@ export function getMsgAuditPermitUsers() {
|
||||
export interface PrescriptionEsignConfig {
|
||||
enabled: boolean
|
||||
environment: 'sandbox' | 'production'
|
||||
verification_method?: 'sms' | 'quick'
|
||||
review_enabled?: boolean
|
||||
}
|
||||
|
||||
export interface PrescriptionEsignStatus extends PrescriptionEsignConfig {
|
||||
@@ -384,7 +386,19 @@ export interface PrescriptionEsignStatus extends PrescriptionEsignConfig {
|
||||
status_label: string
|
||||
can_sign: boolean
|
||||
can_download: boolean
|
||||
can_resume_identity?: boolean
|
||||
doctor_identity_required?: boolean
|
||||
signing_authorization_required?: boolean
|
||||
signing_authorization_reason?: 'missing' | 'expired' | 'exhausted' | 'invalid'
|
||||
sms_sent?: boolean
|
||||
can_retry_verify?: boolean
|
||||
message: string
|
||||
issued_at?: number
|
||||
signature_time?: number
|
||||
signature_time_source?: 'tsa' | 'local' | ''
|
||||
review_signer_name?: string
|
||||
review_signature_time?: number
|
||||
signed_at?: number
|
||||
auth_url?: string
|
||||
}
|
||||
|
||||
@@ -394,6 +408,57 @@ export interface PrescriptionEsignFile {
|
||||
sha256: string
|
||||
}
|
||||
|
||||
export interface PrescriptionEsignReviewStatus {
|
||||
required: boolean
|
||||
state: 'pending' | 'signing' | 'verifying' | 'signed' | 'failed' | 'uncertain'
|
||||
can_confirm: boolean
|
||||
can_retry_verify: boolean
|
||||
can_approve: boolean
|
||||
can_setup: boolean
|
||||
actor_id: number
|
||||
actor_name: string
|
||||
signer_name: string
|
||||
signature_time: number
|
||||
message: string
|
||||
}
|
||||
|
||||
export interface PrescriptionEsignReviewTarget {
|
||||
id: number
|
||||
order_id?: number
|
||||
}
|
||||
|
||||
export function prescriptionEsignReviewStatus(params: PrescriptionEsignReviewTarget, signal?: AbortSignal): Promise<PrescriptionEsignReviewStatus> {
|
||||
return request.get({ url: '/tcm.prescription/esignReviewStatus', params, signal },
|
||||
{ isOpenRetry: false, retryCount: 0, ignoreCancelToken: true })
|
||||
}
|
||||
|
||||
export function prescriptionEsignReviewConfirm(
|
||||
params: PrescriptionEsignReviewTarget & { actor_id: number; verify_only: boolean }
|
||||
): Promise<PrescriptionEsignReviewStatus> {
|
||||
return request.post({ url: '/tcm.prescription/esignReviewConfirm', params, timeout: 360000 },
|
||||
{ isOpenRetry: false, retryCount: 0, ignoreCancelToken: true })
|
||||
}
|
||||
|
||||
export interface PrescriptionEsignIdentityStatus extends PrescriptionEsignStatus {
|
||||
identity_status: 'INIT' | 'ING' | 'SUCCESS' | 'FAIL' | 'EXPIRED' | 'UNAVAILABLE'
|
||||
can_complete: boolean
|
||||
identity_details_required?: boolean
|
||||
}
|
||||
|
||||
export interface PrescriptionEsignDoctorStatus {
|
||||
enabled: boolean
|
||||
status: 'unbound' | 'needs_mobile' | 'renewal_required' | 'authenticating' | 'binding_required' | 'ready'
|
||||
cert_expires_at: number
|
||||
identity_details_required?: boolean
|
||||
quicksign_enabled?: boolean
|
||||
quicksign_authorizing?: boolean
|
||||
quicksign_expires_at?: number
|
||||
quicksign_remaining_times?: number
|
||||
quicksign_unavailable_reason?: '' | 'missing' | 'expired' | 'exhausted' | 'invalid'
|
||||
auth_url?: string
|
||||
message?: string
|
||||
}
|
||||
|
||||
export function prescriptionEsignConfig(): Promise<PrescriptionEsignConfig> {
|
||||
return request.get({ url: '/tcm.prescription/esignConfig' })
|
||||
}
|
||||
@@ -402,16 +467,57 @@ export function prescriptionEsignStatus(params: { id: number }): Promise<Prescri
|
||||
return request.get({ url: '/tcm.prescription/esignStatus', params })
|
||||
}
|
||||
|
||||
export function prescriptionEsignStart(params: { id: number }): Promise<PrescriptionEsignStatus> {
|
||||
/** Read-only identity readiness; this endpoint never submits a signature. */
|
||||
export function prescriptionEsignIdentityStatus(params: { id: number }, signal?: AbortSignal): Promise<PrescriptionEsignIdentityStatus> {
|
||||
return request.get(
|
||||
{ url: '/tcm.prescription/esignIdentityStatus', params, signal, timeout: 15000 },
|
||||
{ isOpenRetry: false, retryCount: 0, ignoreCancelToken: true }
|
||||
)
|
||||
}
|
||||
|
||||
export function prescriptionEsignStart(params: { id: number; restart_identity?: true }): Promise<PrescriptionEsignStatus> {
|
||||
return request.post(
|
||||
{ url: '/tcm.prescription/esignStart', params, timeout: 180000 },
|
||||
{ isOpenRetry: false, retryCount: 0, ignoreCancelToken: true }
|
||||
)
|
||||
}
|
||||
|
||||
export function prescriptionEsignComplete(params: { id: number }): Promise<PrescriptionEsignStatus> {
|
||||
export function prescriptionEsignVerifyWillingness(params: { id: number; auth_code: string }): Promise<PrescriptionEsignIdentityStatus> {
|
||||
return request.post(
|
||||
{ url: '/tcm.prescription/esignComplete', params, timeout: 180000 },
|
||||
{ url: '/tcm.prescription/esignVerifyWillingness', params, timeout: 60000 },
|
||||
{ isOpenRetry: false, retryCount: 0, ignoreCancelToken: true }
|
||||
)
|
||||
}
|
||||
|
||||
export function prescriptionEsignDoctorStatus(signal?: AbortSignal): Promise<PrescriptionEsignDoctorStatus> {
|
||||
return request.get(
|
||||
{ url: '/tcm.prescription/esignDoctorStatus', signal, timeout: 15000 },
|
||||
{ isOpenRetry: false, retryCount: 0, ignoreCancelToken: true }
|
||||
)
|
||||
}
|
||||
|
||||
export function prescriptionEsignDoctorStart(params: { mobile?: string }): Promise<PrescriptionEsignDoctorStatus> {
|
||||
return request.post(
|
||||
{ url: '/tcm.prescription/esignDoctorStart', params, timeout: 180000 },
|
||||
{ isOpenRetry: false, retryCount: 0, ignoreCancelToken: true }
|
||||
)
|
||||
}
|
||||
|
||||
export function prescriptionEsignDoctorComplete(params: { identity_number?: string }): Promise<PrescriptionEsignDoctorStatus> {
|
||||
return request.post(
|
||||
{ url: '/tcm.prescription/esignDoctorComplete', params, timeout: 180000 },
|
||||
{ isOpenRetry: false, retryCount: 0, ignoreCancelToken: true }
|
||||
)
|
||||
}
|
||||
|
||||
export function prescriptionEsignComplete(params: { id: number } & (
|
||||
{ verify_only: true; identity_number?: never } | { verify_only?: never; identity_number?: string }
|
||||
)): Promise<PrescriptionEsignStatus> {
|
||||
const payload = { id: params.id }
|
||||
if (params.verify_only) Object.assign(payload, { verify_only: true })
|
||||
else if (params.identity_number !== undefined) Object.assign(payload, { identity_number: params.identity_number })
|
||||
return request.post(
|
||||
{ url: '/tcm.prescription/esignComplete', params: payload, timeout: 180000 },
|
||||
{ isOpenRetry: false, retryCount: 0, ignoreCancelToken: true }
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,406 @@
|
||||
<template>
|
||||
<el-dialog
|
||||
:model-value="true"
|
||||
:title="reviewer ? '审核签署身份' : '医生电子签署身份'"
|
||||
:width="frameUrl ? 'min(760px, 94vw)' : 'min(520px, 94vw)'"
|
||||
top="5vh"
|
||||
append-to-body
|
||||
:close-on-click-modal="false"
|
||||
:before-close="dismiss"
|
||||
>
|
||||
<p class="doctor-esign__message" role="status">{{ guidance }}</p>
|
||||
<dl v-if="state?.enabled && state.status === 'ready'" class="doctor-esign__expiry">
|
||||
<template v-if="state.cert_expires_at">
|
||||
<dt>签署证书有效期至</dt>
|
||||
<dd>{{ formatExpiry(state.cert_expires_at) }}</dd>
|
||||
</template>
|
||||
<template v-if="grantActive">
|
||||
<dt>快捷签授权有效期至</dt>
|
||||
<dd>{{ formatExpiry(state.quicksign_expires_at) }}</dd>
|
||||
<dt>快捷签剩余次数</dt>
|
||||
<dd>{{ state.quicksign_remaining_times }}</dd>
|
||||
</template>
|
||||
</dl>
|
||||
<p v-if="error" class="doctor-esign__error" role="alert">{{ error }}</p>
|
||||
<label v-if="needsMobile" class="doctor-esign__field">
|
||||
本人手机号码
|
||||
<el-input
|
||||
v-model="mobile"
|
||||
:disabled="!!pending"
|
||||
type="tel"
|
||||
inputmode="numeric"
|
||||
maxlength="11"
|
||||
autocomplete="off"
|
||||
placeholder="请输入 11 位大陆手机号码"
|
||||
/>
|
||||
</label>
|
||||
<label v-if="needsIdentityNumber" class="doctor-esign__field">
|
||||
本次认证使用的身份证号码
|
||||
<el-input
|
||||
v-model="identityNumber"
|
||||
:disabled="!!pending"
|
||||
type="password"
|
||||
maxlength="18"
|
||||
autocomplete="off"
|
||||
:spellcheck="false"
|
||||
placeholder="请输入 15 或 18 位大陆居民身份证号码"
|
||||
/>
|
||||
</label>
|
||||
<iframe
|
||||
v-if="frameUrl"
|
||||
:src="frameUrl"
|
||||
class="doctor-esign__frame"
|
||||
title="e签宝本人身份核验"
|
||||
sandbox="allow-forms allow-scripts allow-same-origin"
|
||||
referrerpolicy="no-referrer"
|
||||
@error="authenticationUnavailable"
|
||||
/>
|
||||
<template #footer>
|
||||
<div class="doctor-esign__actions">
|
||||
<el-button v-if="needsMobile || canAuthorizeQuick" type="primary" :disabled="!!pending" @click="start">
|
||||
{{ startLabel }}
|
||||
</el-button>
|
||||
<el-button v-if="canResume" type="primary" :disabled="!!pending" @click="openAuthentication">
|
||||
{{ state?.quicksign_authorizing ? '继续快捷签授权' : '继续人脸认证' }}
|
||||
</el-button>
|
||||
<el-button v-if="canComplete" type="primary" :disabled="!!pending" @click="complete">
|
||||
{{ state?.quicksign_authorizing ? '确认快捷签授权' : '确认绑定签署身份' }}
|
||||
</el-button>
|
||||
<el-button
|
||||
v-if="canResume && !state?.quicksign_authorizing"
|
||||
:disabled="!!pending"
|
||||
@click="enterMobile"
|
||||
>重新输入手机号</el-button>
|
||||
<el-button :disabled="!!pending" @click="refresh">检查状态</el-button>
|
||||
<el-button v-if="frameUrl" link @click="authenticationUnavailable">验证页面不可用</el-button>
|
||||
<el-button @click="dismiss">关闭</el-button>
|
||||
</div>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
|
||||
|
||||
import {
|
||||
prescriptionEsignDoctorComplete,
|
||||
prescriptionEsignDoctorStart,
|
||||
prescriptionEsignDoctorStatus,
|
||||
type PrescriptionEsignDoctorStatus
|
||||
} from '@/api/tcm'
|
||||
import { safeEsignAuthUrl } from '@/utils/prescription-esign'
|
||||
|
||||
const props = defineProps<{ serverTimeOffsetMs: number; reviewer?: boolean }>()
|
||||
const emit = defineEmits<{ (event: 'close'): void }>()
|
||||
type DoctorRequest = 'status' | 'start' | 'complete'
|
||||
|
||||
const enrollmentStatuses = ['unbound', 'needs_mobile', 'renewal_required']
|
||||
const statuses = [...enrollmentStatuses, 'authenticating', 'binding_required', 'ready']
|
||||
const pollInterval = 5000
|
||||
const authenticationTimeout = 10 * 60 * 1000
|
||||
const expiryFormatter = new Intl.DateTimeFormat('zh-CN', {
|
||||
timeZone: 'Asia/Shanghai',
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
hourCycle: 'h23'
|
||||
})
|
||||
|
||||
const state = ref<ReturnType<typeof validateStatus> | null>(null)
|
||||
const pending = ref<DoctorRequest | null>(null)
|
||||
const frameUrl = ref('')
|
||||
const mobile = ref('')
|
||||
const identityNumber = ref('')
|
||||
const editingMobile = ref(false)
|
||||
const error = ref('')
|
||||
const now = ref(Date.now() + props.serverTimeOffsetMs)
|
||||
|
||||
const authUrl = computed(() => state.value?.auth_url ?? '')
|
||||
const authenticating = computed(() => state.value?.enabled === true && state.value.status === 'authenticating')
|
||||
const canResume = computed(() => authenticating.value && !!authUrl.value && !frameUrl.value && !editingMobile.value)
|
||||
const canComplete = computed(() => state.value?.enabled === true && state.value.status === 'binding_required')
|
||||
const needsIdentityNumber = computed(() => canComplete.value && !state.value?.quicksign_authorizing
|
||||
&& state.value?.identity_details_required === true)
|
||||
const needsMobile = computed(() => state.value?.enabled === true
|
||||
&& (enrollmentStatuses.includes(state.value.status) || editingMobile.value))
|
||||
const quickReady = computed(() => state.value?.enabled === true && state.value.status === 'ready'
|
||||
&& state.value.quicksign_enabled === true)
|
||||
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)
|
||||
const canAuthorizeQuick = computed(() => quickReady.value && !grantActive.value)
|
||||
const startLabel = computed(() => {
|
||||
if (canAuthorizeQuick.value) return '授权快捷签'
|
||||
if (state.value?.status === 'renewal_required') return '开始续期认证'
|
||||
return '开始人脸认证'
|
||||
})
|
||||
const guidance = computed(() => {
|
||||
const current = state.value
|
||||
if (!current) return pending.value === 'status' ? '正在查询医生签署身份…' : ''
|
||||
if (!current.enabled) return '当前环境未启用医生电子签署身份。'
|
||||
switch (current.status) {
|
||||
case 'unbound':
|
||||
return '首次电子签署前,请验证本人身份并绑定签署证书。'
|
||||
case 'needs_mobile':
|
||||
return '请使用本人手机号码完成签署身份验证。'
|
||||
case 'renewal_required':
|
||||
return '签署证书需要续期,请使用本人手机号码完成人脸认证。'
|
||||
case 'authenticating':
|
||||
if (editingMobile.value) return '请使用本人手机号码完成人脸认证。'
|
||||
if (current.authUrlUnavailable) return '验证链接不可用,请检查状态后重试。'
|
||||
if (!authUrl.value) return '认证请求处理中,请稍后检查状态。'
|
||||
if (!frameUrl.value) return current.quicksign_authorizing ? '请继续完成快捷签授权。' : '请继续完成本人人脸认证。'
|
||||
return current.quicksign_authorizing
|
||||
? '请使用手机支付宝扫码刷脸,并按 e签宝页面提示确认授权。'
|
||||
: '请使用手机支付宝扫描 e签宝页面中的二维码并完成人脸识别。'
|
||||
case 'binding_required':
|
||||
if (current.quicksign_authorizing) return '人脸认证已通过,请确认启用本人的快捷签。'
|
||||
if (needsIdentityNumber.value) return '人脸认证已通过。首次绑定证书需要补充与本次认证一致的身份证号码。'
|
||||
return '人脸认证已通过,请确认完成本人的签署身份认证。'
|
||||
case 'ready': {
|
||||
if (!quickReady.value) return '医生签署身份已就绪。'
|
||||
if (grantActive.value) return props.reviewer ? '快捷签授权有效。每张处方由审核人本人确认签名。'
|
||||
: '快捷签授权有效。每张处方仍需开方医生本人确认签名。'
|
||||
const reason = current.quicksign_unavailable_reason
|
||||
if (reason === 'expired' || (current.quicksign_expires_at > 0 && current.quicksign_expires_at * 1000 <= now.value)) {
|
||||
return '快捷签授权已过期,请重新授权。'
|
||||
}
|
||||
if (reason === 'exhausted') return '快捷签授权次数已用完,请重新授权。'
|
||||
if (reason === 'invalid') return '快捷签授权已失效,请重新授权。'
|
||||
return '签署身份已就绪。请授权使用本人的快捷签,每张处方仍需本人确认签名。'
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
let closed = false
|
||||
let generation = 0
|
||||
let statusRequest: AbortController | undefined
|
||||
let pollTimer: ReturnType<typeof setTimeout> | undefined
|
||||
let deadlineTimer: ReturnType<typeof setTimeout> | undefined
|
||||
let grantExpiryTimer: ReturnType<typeof setTimeout> | undefined
|
||||
|
||||
function formatExpiry(timestamp: number) {
|
||||
return `${expiryFormatter.format(timestamp * 1000)}(北京时间)`
|
||||
}
|
||||
|
||||
function validTime(value: number) {
|
||||
return Number.isSafeInteger(value) && value >= 0 && value <= 253402300799
|
||||
}
|
||||
|
||||
function validateStatus(result: PrescriptionEsignDoctorStatus) {
|
||||
const {
|
||||
enabled, status, cert_expires_at,
|
||||
identity_details_required = false, quicksign_enabled = false, quicksign_authorizing = false,
|
||||
quicksign_expires_at = 0, quicksign_remaining_times = 0, quicksign_unavailable_reason = ''
|
||||
} = result
|
||||
if (!statuses.includes(status) || typeof enabled !== 'boolean'
|
||||
|| typeof quicksign_enabled !== 'boolean' || typeof quicksign_authorizing !== 'boolean'
|
||||
|| !validTime(cert_expires_at) || !validTime(quicksign_expires_at)
|
||||
|| typeof identity_details_required !== 'boolean'
|
||||
|| (identity_details_required && (!enabled || status !== 'binding_required' || quicksign_authorizing))
|
||||
|| (quicksign_authorizing && (!enabled || !quicksign_enabled || !['authenticating', 'binding_required'].includes(status)))
|
||||
|| !Number.isSafeInteger(quicksign_remaining_times) || quicksign_remaining_times < 0
|
||||
|| !['', 'missing', 'expired', 'exhausted', 'invalid'].includes(quicksign_unavailable_reason)) {
|
||||
throw new Error('医生签署状态无效')
|
||||
}
|
||||
const providerUrl = enabled && status === 'authenticating' ? result.auth_url : undefined
|
||||
const auth_url = safeEsignAuthUrl(providerUrl)
|
||||
return {
|
||||
enabled, status, cert_expires_at, identity_details_required, quicksign_enabled, quicksign_authorizing,
|
||||
quicksign_expires_at, quicksign_remaining_times, quicksign_unavailable_reason, auth_url,
|
||||
authUrlUnavailable: Boolean(providerUrl && !auth_url)
|
||||
}
|
||||
}
|
||||
|
||||
function clearInputs() {
|
||||
mobile.value = ''
|
||||
identityNumber.value = ''
|
||||
}
|
||||
|
||||
function stopAuthentication() {
|
||||
clearTimeout(pollTimer)
|
||||
clearTimeout(deadlineTimer)
|
||||
frameUrl.value = ''
|
||||
}
|
||||
|
||||
function cancelWork() {
|
||||
generation++
|
||||
statusRequest?.abort()
|
||||
statusRequest = undefined
|
||||
pending.value = null
|
||||
clearInputs()
|
||||
stopAuthentication()
|
||||
}
|
||||
|
||||
function clearStatus() {
|
||||
cancelWork()
|
||||
clearTimeout(grantExpiryTimer)
|
||||
state.value = null
|
||||
editingMobile.value = false
|
||||
error.value = ''
|
||||
}
|
||||
|
||||
function dismiss() {
|
||||
closed = true
|
||||
clearStatus()
|
||||
emit('close')
|
||||
}
|
||||
|
||||
function canAct() {
|
||||
return !closed && document.visibilityState === 'visible'
|
||||
}
|
||||
|
||||
function accept(result: ReturnType<typeof validateStatus>) {
|
||||
clearTimeout(grantExpiryTimer)
|
||||
now.value = Date.now() + props.serverTimeOffsetMs
|
||||
editingMobile.value = false
|
||||
state.value = result
|
||||
if (!authenticating.value || (frameUrl.value && frameUrl.value !== authUrl.value)) stopAuthentication()
|
||||
if (grantActive.value) {
|
||||
const expiresIn = result.quicksign_expires_at * 1000 - now.value
|
||||
if (expiresIn <= 2147483647) {
|
||||
grantExpiryTimer = setTimeout(() => { now.value = Date.now() + props.serverTimeOffsetMs }, expiresIn)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function schedulePoll() {
|
||||
if (frameUrl.value) pollTimer = setTimeout(() => void refresh(), pollInterval)
|
||||
}
|
||||
|
||||
function openAuthentication() {
|
||||
if (!canAct() || pending.value || !canResume.value) return
|
||||
frameUrl.value = authUrl.value
|
||||
error.value = ''
|
||||
deadlineTimer = setTimeout(() => {
|
||||
cancelWork()
|
||||
error.value = '自动检查已结束,请检查状态后继续。'
|
||||
}, authenticationTimeout)
|
||||
schedulePoll()
|
||||
}
|
||||
|
||||
function authenticationUnavailable() {
|
||||
if (!frameUrl.value) return
|
||||
cancelWork()
|
||||
error.value = '无法加载 e签宝认证页面,请检查状态后重试。'
|
||||
}
|
||||
|
||||
function enterMobile() {
|
||||
if (!canAct() || pending.value || !canResume.value || state.value?.quicksign_authorizing) return
|
||||
editingMobile.value = true
|
||||
error.value = ''
|
||||
}
|
||||
|
||||
async function submit(
|
||||
kind: DoctorRequest,
|
||||
request: () => Promise<PrescriptionEsignDoctorStatus>
|
||||
) {
|
||||
if (!canAct() || pending.value) return
|
||||
const current = generation
|
||||
clearInputs()
|
||||
clearTimeout(pollTimer)
|
||||
error.value = ''
|
||||
pending.value = kind
|
||||
try {
|
||||
const result = validateStatus(await request())
|
||||
if (current !== generation || !canAct()) return
|
||||
accept(result)
|
||||
} catch {
|
||||
if (current !== generation || !canAct()) return
|
||||
clearStatus()
|
||||
error.value = '医生签署身份状态待确认,请检查状态后继续。'
|
||||
return
|
||||
} finally {
|
||||
if (current === generation) pending.value = null
|
||||
}
|
||||
if (kind === 'start') openAuthentication()
|
||||
else schedulePoll()
|
||||
}
|
||||
|
||||
async function refresh() {
|
||||
if (!canAct() || pending.value) return
|
||||
const controller = new AbortController()
|
||||
statusRequest = controller
|
||||
try {
|
||||
await submit('status', () => prescriptionEsignDoctorStatus(controller.signal))
|
||||
} finally {
|
||||
if (statusRequest === controller) statusRequest = undefined
|
||||
}
|
||||
}
|
||||
|
||||
async function start() {
|
||||
if (!canAct() || pending.value) return
|
||||
if (canAuthorizeQuick.value) {
|
||||
await submit('start', () => prescriptionEsignDoctorStart({}))
|
||||
} else if (needsMobile.value) {
|
||||
const number = mobile.value.trim()
|
||||
clearInputs()
|
||||
if (!/^1[3-9]\d{9}$/.test(number)) {
|
||||
error.value = '请输入有效的大陆手机号码。'
|
||||
return
|
||||
}
|
||||
await submit('start', () => prescriptionEsignDoctorStart({ mobile: number }))
|
||||
}
|
||||
}
|
||||
|
||||
async function complete() {
|
||||
if (!canAct() || pending.value || !canComplete.value) return
|
||||
if (needsIdentityNumber.value) {
|
||||
const number = identityNumber.value.trim().toUpperCase()
|
||||
clearInputs()
|
||||
if (!/^(?:\d{15}|\d{17}[\dX])$/.test(number)) {
|
||||
error.value = '请输入本次认证使用的 15 或 18 位大陆居民身份证号码。'
|
||||
return
|
||||
}
|
||||
await submit('complete', () => prescriptionEsignDoctorComplete({ identity_number: number }))
|
||||
} else {
|
||||
await submit('complete', () => prescriptionEsignDoctorComplete({}))
|
||||
}
|
||||
}
|
||||
|
||||
function onVisibilityChange() {
|
||||
if (document.visibilityState === 'visible') void refresh()
|
||||
else clearStatus()
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
document.addEventListener('visibilitychange', onVisibilityChange)
|
||||
void refresh()
|
||||
})
|
||||
onBeforeUnmount(() => {
|
||||
closed = true
|
||||
clearStatus()
|
||||
document.removeEventListener('visibilitychange', onVisibilityChange)
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.doctor-esign__message, .doctor-esign__error {
|
||||
margin: 0 0 12px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
.doctor-esign__message:empty { display: none; }
|
||||
.doctor-esign__error { color: var(--el-color-danger); }
|
||||
.doctor-esign__expiry {
|
||||
display: grid;
|
||||
grid-template-columns: auto minmax(0, 1fr);
|
||||
gap: 8px 16px;
|
||||
margin: 0 0 12px;
|
||||
padding-top: 12px;
|
||||
border-top: 1px solid var(--el-border-color-light);
|
||||
}
|
||||
.doctor-esign__expiry dt { color: var(--el-text-color-secondary); }
|
||||
.doctor-esign__expiry dd { margin: 0; }
|
||||
.doctor-esign__field { display: grid; gap: 6px; max-width: 350px; }
|
||||
.doctor-esign__frame {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: min(60vh, 620px);
|
||||
border: 1px solid var(--el-border-color-light);
|
||||
border-radius: 4px;
|
||||
background: white;
|
||||
}
|
||||
.doctor-esign__actions { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 8px; }
|
||||
.doctor-esign__actions .el-button + .el-button { margin-left: 0; }
|
||||
</style>
|
||||
@@ -1,59 +1,137 @@
|
||||
<template>
|
||||
<section class="esign-panel" aria-label="处方电子签署" v-loading="busy">
|
||||
<section v-show="showControls || signingTime || reviewState?.required" class="esign-panel" aria-label="处方电子签署" v-loading="busy">
|
||||
<div class="esign-panel__heading">
|
||||
<strong>医师电子签署</strong>
|
||||
<el-tag v-if="state && confirmed" :type="state.status === 'signed' ? 'success' : 'info'" size="small">
|
||||
{{ state.status_label }}
|
||||
</el-tag>
|
||||
<el-tag v-if="state?.environment === 'sandbox' && state?.status !== 'legacy'" type="warning" size="small">
|
||||
<el-tag v-if="confirmed && state?.environment === 'sandbox' && state.status !== 'legacy'" type="warning" size="small">
|
||||
沙箱测试
|
||||
</el-tag>
|
||||
</div>
|
||||
<p v-if="state?.message" class="esign-panel__message">{{ state.message }}</p>
|
||||
<p v-if="state?.environment === 'sandbox' && state?.status !== 'legacy'" class="esign-panel__message">
|
||||
当前为沙箱测试签署,仅用于接入验证。
|
||||
</p>
|
||||
<p v-if="error" class="esign-panel__error" role="alert">{{ error }}</p>
|
||||
<div class="esign-panel__actions">
|
||||
<el-button
|
||||
v-if="state?.can_sign"
|
||||
type="primary"
|
||||
size="small"
|
||||
:disabled="busy || !confirmed"
|
||||
@click="start"
|
||||
>{{ state.status === 'failed' ? '重试核身签署' : authUrl ? '重新获取核身链接' : '发起核身签署' }}</el-button>
|
||||
<el-link v-if="authUrl && state?.can_sign && confirmed" :href="authUrl" target="_blank" rel="noopener noreferrer" type="primary">
|
||||
打开核身页面
|
||||
</el-link>
|
||||
<el-button
|
||||
v-if="state?.can_sign && (state.status === 'authenticating' || authUrl)"
|
||||
size="small"
|
||||
:disabled="busy || !confirmed"
|
||||
@click="complete"
|
||||
>已完成核身,继续签署</el-button>
|
||||
<el-button size="small" :disabled="busy" @click="refresh">刷新签署状态</el-button>
|
||||
<el-button v-if="state?.can_download" size="small" :disabled="busy || !confirmed" @click="download">
|
||||
下载已签原始 PDF
|
||||
</el-button>
|
||||
<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>
|
||||
<el-step title="处方草稿已保存" />
|
||||
<el-step :title="verificationMethod === 'quick' ? '核对快捷签授权' : verificationMethod === 'sms' ? '校验短信验证码' : '验证医生身份'" />
|
||||
<el-step title="签名并完成" />
|
||||
</el-steps>
|
||||
<p v-if="message" class="esign-panel__message" aria-live="polite">{{ message }}</p>
|
||||
<div v-if="signingTime" class="esign-panel__message" aria-live="polite">
|
||||
<div v-if="signingTime.issuedTime">开具时间:{{ signingTime.issuedTime }}(北京时间)</div>
|
||||
<div v-if="signingTime.signatureTime">
|
||||
医生签署时间:{{ signingTime.signatureTime }}(北京时间 · {{ signingTime.source }})
|
||||
</div>
|
||||
<template v-else>
|
||||
<div>签署时间待核实</div>
|
||||
<div v-if="signingTime.verifiedTime">系统验签完成时间:{{ signingTime.verifiedTime }}(北京时间)</div>
|
||||
</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>
|
||||
<p v-if="authUrl && state?.can_sign" class="esign-panel__message">
|
||||
请在新页面完成核身,然后返回继续签署;关闭页面后可从处方详情继续。
|
||||
</p>
|
||||
<p v-if="error" class="esign-panel__error" role="alert">{{ error }}</p>
|
||||
<label v-if="identityDetailsRequired" class="esign-panel__identity">
|
||||
本次验证使用的身份证号
|
||||
<el-input
|
||||
v-model="identityNumber"
|
||||
type="password"
|
||||
maxlength="18"
|
||||
autocomplete="off"
|
||||
:spellcheck="false"
|
||||
placeholder="输入18位大陆居民身份证号"
|
||||
/>
|
||||
</label>
|
||||
<label v-if="smsCodeEntry" class="esign-panel__identity">
|
||||
短信验证码
|
||||
<el-input
|
||||
v-model="smsCode"
|
||||
type="password"
|
||||
inputmode="numeric"
|
||||
maxlength="6"
|
||||
autocomplete="off"
|
||||
:spellcheck="false"
|
||||
:disabled="busy"
|
||||
placeholder="输入6位短信验证码"
|
||||
/>
|
||||
</label>
|
||||
<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">
|
||||
{{ action.label }}
|
||||
</el-button>
|
||||
<el-button v-if="smsCodeEntry" size="small" :disabled="busy || smsSendCoolingDown" @click="sendSms">
|
||||
{{ smsSendCoolingDown ? '请稍后重新发送' : '重新发送验证码' }}
|
||||
</el-button>
|
||||
<el-button v-if="readiness" size="small" :disabled="busy" @click="closeAuthentication">取消</el-button>
|
||||
</div>
|
||||
<EsignReviewPanel
|
||||
v-if="audit && confirmed && state"
|
||||
:prescription-id="prescriptionId"
|
||||
:order-id="reviewOrderId"
|
||||
:doctor-signed="state.status === 'signed'"
|
||||
@change="updateReview"
|
||||
/>
|
||||
<el-dialog
|
||||
:model-value="dialogVisible"
|
||||
title="验证医生身份"
|
||||
width="min(720px, 94vw)"
|
||||
top="5vh"
|
||||
append-to-body
|
||||
destroy-on-close
|
||||
:before-close="closeAuthentication"
|
||||
:close-on-click-modal="false"
|
||||
>
|
||||
<p class="esign-panel__message">请在下方完成本人身份验证。</p>
|
||||
<iframe
|
||||
v-if="authUrl && dialogVisible"
|
||||
:src="authUrl"
|
||||
class="esign-panel__frame"
|
||||
title="e签宝本人身份核验"
|
||||
sandbox="allow-forms allow-scripts allow-same-origin"
|
||||
referrerpolicy="no-referrer"
|
||||
@error="authenticationUnavailable"
|
||||
/>
|
||||
<template #footer>
|
||||
<el-button link @click="authenticationUnavailable">验证页面不可用</el-button>
|
||||
<el-button @click="closeAuthentication">关闭</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { computed, onBeforeUnmount, onDeactivated, onMounted, ref, toRaw, watch } from 'vue'
|
||||
import {
|
||||
prescriptionEsignComplete,
|
||||
prescriptionEsignDoctorStatus,
|
||||
prescriptionEsignIdentityStatus,
|
||||
prescriptionEsignStart,
|
||||
prescriptionEsignStatus,
|
||||
prescriptionEsignVerifyWillingness,
|
||||
type PrescriptionEsignIdentityStatus,
|
||||
type PrescriptionEsignReviewStatus,
|
||||
type PrescriptionEsignStatus
|
||||
} from '@/api/tcm'
|
||||
import { downloadPrescriptionPdfIfRequired, safeEsignAuthUrl, validateEsignStatus } from '@/utils/prescription-esign'
|
||||
import {
|
||||
canApprovePrescriptionEsign,
|
||||
canCheckEsignIdentity,
|
||||
downloadOriginalEsignPdf,
|
||||
formatSigningTime,
|
||||
prescriptionEsignTiming,
|
||||
safeEsignAuthUrl,
|
||||
validateEsignIdentityStatus,
|
||||
validateEsignStatus
|
||||
} from '@/utils/prescription-esign'
|
||||
import EsignReviewPanel from '@/components/EsignReviewPanel.vue'
|
||||
|
||||
const props = defineProps<{ prescriptionId: number; initialState?: PrescriptionEsignStatus; audit?: boolean; reviewOrderId?: number }>()
|
||||
const emit = defineEmits<{
|
||||
(e: 'status-change', state: PrescriptionEsignStatus): void
|
||||
(e: 'review-change', state: PrescriptionEsignReviewStatus | null): void
|
||||
}>()
|
||||
|
||||
const reviewState = ref<PrescriptionEsignReviewStatus | null>(null)
|
||||
function updateReview(result: PrescriptionEsignReviewStatus | null) {
|
||||
reviewState.value = result
|
||||
emit('review-change', result)
|
||||
}
|
||||
|
||||
const props = defineProps<{ prescriptionId: number; initialState?: PrescriptionEsignStatus }>()
|
||||
const emit = defineEmits<{ (e: 'status-change', state: PrescriptionEsignStatus): void }>()
|
||||
function initialStatus(): PrescriptionEsignStatus | null {
|
||||
try {
|
||||
return validateEsignStatus(props.initialState)
|
||||
@@ -61,80 +139,556 @@ function initialStatus(): PrescriptionEsignStatus | null {
|
||||
return null
|
||||
}
|
||||
}
|
||||
const state = ref<PrescriptionEsignStatus | null>(initialStatus())
|
||||
const busy = ref(false)
|
||||
const confirmed = ref(false)
|
||||
const error = ref('')
|
||||
const authUrl = computed(() => safeEsignAuthUrl(state.value?.auth_url))
|
||||
let generation = 0
|
||||
|
||||
async function run(action: 'refresh' | 'start' | 'complete') {
|
||||
if (busy.value || !props.prescriptionId) return
|
||||
if (action !== 'refresh' && (!confirmed.value || state.value?.can_sign !== true)) return
|
||||
const id = props.prescriptionId
|
||||
const current = generation
|
||||
busy.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const api = action === 'start' ? prescriptionEsignStart : action === 'complete' ? prescriptionEsignComplete : prescriptionEsignStatus
|
||||
const result = validateEsignStatus(await api({ id }))
|
||||
if (id !== props.prescriptionId || current !== generation) return
|
||||
state.value = result
|
||||
confirmed.value = true
|
||||
emit('status-change', result)
|
||||
// A browser visit is never evidence of authentication or signing.
|
||||
if (result.auth_url && !safeEsignAuthUrl(result.auth_url)) {
|
||||
error.value = '核身链接无效,请重新获取或联系管理员'
|
||||
const state = ref<PrescriptionEsignStatus | null>(initialStatus())
|
||||
const work = ref<'status' | 'start' | 'identity' | 'send-sms' | 'verify-sms' | 'sign' | 'verify' | 'download' | null>(null)
|
||||
const busy = computed(() => work.value !== null)
|
||||
const confirmed = ref(false)
|
||||
const showControls = computed(() => !props.audit || !confirmed.value || !canApprovePrescriptionEsign(state.value))
|
||||
const signingTime = computed(() => prescriptionEsignTiming(state.value))
|
||||
const error = ref('')
|
||||
const dialogVisible = ref(false)
|
||||
const readiness = ref<'ready' | 'details' | null>(null)
|
||||
const restartRequired = ref(false)
|
||||
const identityNumber = ref('')
|
||||
const smsCode = ref('')
|
||||
const smsCodeState = ref<'entry' | 'expired' | null>(null)
|
||||
const smsSendCoolingDown = ref(false)
|
||||
const smsProfileReady = ref(false)
|
||||
const identityDetailsRequired = computed(() => readiness.value === 'details')
|
||||
const authUrl = computed(() => safeEsignAuthUrl(state.value?.auth_url))
|
||||
type VerificationMethod = NonNullable<PrescriptionEsignStatus['verification_method']>
|
||||
const verificationMethod = computed(() => state.value?.verification_method)
|
||||
const accountSetupMessage = computed(() => {
|
||||
const current = state.value
|
||||
if (!current?.can_sign || !verificationMethod.value) return ''
|
||||
const settings = '请返回页面右上角账号菜单,在「医生电子签署身份」中处理。完成后回到处方查询签署状态。'
|
||||
if (current.doctor_identity_required && !(verificationMethod.value === 'sms' && smsProfileReady.value)) {
|
||||
return `${current.message || '请先完成医生签署身份认证。'} ${settings}`
|
||||
}
|
||||
if (!current.signing_authorization_required) return ''
|
||||
const reason = current.signing_authorization_reason
|
||||
const authorization = reason === 'exhausted' ? '快捷签授权次数已用完。' : reason === 'expired' ? '快捷签授权已到期。'
|
||||
: reason === 'invalid' ? '快捷签授权已失效。' : '快捷签授权待完成。'
|
||||
return `${authorization}${settings}`
|
||||
})
|
||||
const smsCodeEntry = computed(() => confirmed.value && smsCodeState.value === 'entry'
|
||||
&& canUseMethod(state.value, 'sms') && state.value?.sms_sent === true && !accountSetupMessage.value && !readiness.value)
|
||||
const identityResumable = computed(() => !verificationMethod.value && canCheckEsignIdentity(state.value)
|
||||
&& (state.value?.can_resume_identity === true || Boolean(authUrl.value)))
|
||||
const activeStep = computed(() => {
|
||||
if (state.value?.status === 'signed') return 3
|
||||
if (readiness.value || work.value === 'sign' || work.value === 'verify'
|
||||
|| state.value?.status === 'signing' || state.value?.status === 'uncertain') return 2
|
||||
return 1
|
||||
})
|
||||
const message = computed(() => {
|
||||
if (props.prescriptionId <= 0) return '缺少关联处方,无法核对签署状态。'
|
||||
if (props.audit && work.value === 'status') return '正在查询签署状态…'
|
||||
if (work.value === 'identity' && verificationMethod.value === 'quick') return '正在核对快捷签授权…'
|
||||
if (work.value === 'identity' && verificationMethod.value === 'sms') return '正在查询短信验证状态…'
|
||||
if (work.value === 'send-sms') return '正在向医生绑定的手机号发送验证码…'
|
||||
if (work.value === 'verify-sms') return '正在校验短信验证码…'
|
||||
if (work.value === 'sign') return '正在签署处方…'
|
||||
if (work.value === 'verify') return '正在校验已签文件…'
|
||||
if (!confirmed.value || error.value) return ''
|
||||
if (readiness.value) {
|
||||
if (verificationMethod.value === 'quick') return '快捷签授权已核对。请核对处方内容后确认签名。'
|
||||
if (verificationMethod.value === 'sms') return '短信验证码已通过。请核对处方内容后确认签名。'
|
||||
return '医生身份已验证。'
|
||||
}
|
||||
const current = state.value
|
||||
if (!current) return ''
|
||||
if (current.status === 'legacy' && !current.enabled) return current.message || '此处方使用手写签名。'
|
||||
if (current.status === 'signed') return current.can_download ? '处方已签署。' : '处方已签署,原件暂不可用。'
|
||||
if (current.required && ['pending', 'authenticating', 'failed'].includes(current.status)) {
|
||||
if (accountSetupMessage.value) return accountSetupMessage.value
|
||||
if (canUseMethod(current, 'quick')) {
|
||||
return current.message || '请查询签署状态,核对快捷签授权。'
|
||||
}
|
||||
} catch (e: any) {
|
||||
if (id === props.prescriptionId && current === generation) {
|
||||
confirmed.value = false
|
||||
error.value = e?.msg || e?.message || '签署服务暂时不可用,请刷新状态后重试'
|
||||
if (canUseMethod(current, 'sms')) {
|
||||
if (smsCodeEntry.value) return '请输入医生绑定的手机号收到的验证码。'
|
||||
if (smsCodeState.value === 'expired') return '本次短信验证码已失效,请重新发送。'
|
||||
if (smsProfileReady.value) return '医生签署身份已就绪,请发送本张处方的验证码。'
|
||||
if (current.message) return current.message
|
||||
return current.sms_sent ? '请查询短信验证状态。' : '请将本张处方的验证码发送到医生绑定的手机号。'
|
||||
}
|
||||
} finally {
|
||||
if (current === generation) busy.value = false
|
||||
if (current.message) return current.message
|
||||
if (!current.enabled) return '电子签署暂不可用,请联系管理员。'
|
||||
if (props.audit && !current.can_sign) {
|
||||
return '请等待开方医生完成电子签署后,再审核通过。'
|
||||
}
|
||||
if (props.audit) return '请完成核身及电子签署后,再审核通过。'
|
||||
}
|
||||
return current.message || (current.can_sign ? '' : current.status_label)
|
||||
})
|
||||
const action = computed(() => {
|
||||
if (!confirmed.value) return { label: '查询签署状态', run: refresh }
|
||||
if (state.value?.can_download && (state.value.status === 'signed' || state.value.status === 'voided')) {
|
||||
return { label: '下载已签 PDF', run: download }
|
||||
}
|
||||
if (state.value?.status === 'uncertain' && state.value.can_retry_verify) {
|
||||
return { label: '重试校验已签文件', run: retryVerification }
|
||||
}
|
||||
if (state.value?.can_sign && ['pending', 'authenticating', 'failed'].includes(state.value.status)) {
|
||||
if (accountSetupMessage.value) return { label: '查询签署状态', run: refresh }
|
||||
if (readiness.value) return { label: '确认签名', run: confirmSign }
|
||||
if (verificationMethod.value === 'quick') return { label: '查询签署状态', run: refresh }
|
||||
if (verificationMethod.value === 'sms') {
|
||||
if (smsCodeEntry.value) return { label: '校验验证码', run: verifySms }
|
||||
if (state.value.sms_sent && smsCodeState.value !== 'expired') return { label: '查询签署状态', run: refresh }
|
||||
const label = smsSendCoolingDown.value ? '请稍后重新发送' : state.value.sms_sent ? '重新发送验证码' : '发送验证码'
|
||||
return { label, run: sendSms }
|
||||
}
|
||||
if (restartRequired.value) return { label: '重新验证医生身份', run: () => start(true) }
|
||||
if (identityResumable.value) return { label: '检查身份验证', run: recheckIdentity }
|
||||
return { label: state.value.status === 'failed' ? '重新验证医生身份' : '验证医生身份', run: () => start() }
|
||||
}
|
||||
return { label: '查询签署状态', run: refresh }
|
||||
})
|
||||
|
||||
const pollInterval = 5000
|
||||
const authenticationTimeout = 10 * 60 * 1000
|
||||
const smsSendCooldown = 60 * 1000
|
||||
let operation = 0
|
||||
let disposed = false
|
||||
let pollTimer: ReturnType<typeof setTimeout> | undefined
|
||||
let deadlineTimer: ReturnType<typeof setTimeout> | undefined
|
||||
let identityRequest: AbortController | undefined
|
||||
let resendTimer: ReturnType<typeof setTimeout> | undefined
|
||||
let expiresAt = 0
|
||||
|
||||
function canAct() {
|
||||
return !disposed && !busy.value && props.prescriptionId > 0 && document.visibilityState === 'visible'
|
||||
}
|
||||
|
||||
function isCurrent(current: number, id: number) {
|
||||
return !disposed && current === operation && id === props.prescriptionId && document.visibilityState === 'visible'
|
||||
}
|
||||
|
||||
function canUseMethod(result: PrescriptionEsignStatus | null, method: VerificationMethod): boolean {
|
||||
return result?.verification_method === method && result.enabled && result.required && result.can_sign
|
||||
&& ['pending', 'authenticating', 'failed'].includes(result.status)
|
||||
}
|
||||
|
||||
function accept(result: PrescriptionEsignStatus) {
|
||||
state.value = result
|
||||
confirmed.value = true
|
||||
if (!result.can_sign || !['authenticating', 'failed'].includes(result.status)) restartRequired.value = false
|
||||
emit('status-change', result)
|
||||
}
|
||||
|
||||
function clearVerification() {
|
||||
clearTimeout(pollTimer)
|
||||
clearTimeout(deadlineTimer)
|
||||
pollTimer = undefined
|
||||
deadlineTimer = undefined
|
||||
identityRequest?.abort()
|
||||
identityRequest = undefined
|
||||
dialogVisible.value = false
|
||||
readiness.value = null
|
||||
identityNumber.value = ''
|
||||
smsCode.value = ''
|
||||
smsCodeState.value = null
|
||||
}
|
||||
|
||||
function cancelWork() {
|
||||
operation++
|
||||
work.value = null
|
||||
clearVerification()
|
||||
smsProfileReady.value = false
|
||||
}
|
||||
|
||||
function closeAuthentication() {
|
||||
if (dialogVisible.value || readiness.value) cancelWork()
|
||||
}
|
||||
|
||||
function stopVerification(message: string) {
|
||||
clearVerification()
|
||||
error.value = message
|
||||
}
|
||||
|
||||
function authenticationUnavailable() {
|
||||
if (!dialogVisible.value) return
|
||||
cancelWork()
|
||||
error.value = '验证页面无法加载,请重试或联系管理员。'
|
||||
}
|
||||
|
||||
function beginVerification(current: number, id: number) {
|
||||
expiresAt = Date.now() + authenticationTimeout
|
||||
deadlineTimer = setTimeout(() => {
|
||||
if (!isCurrent(current, id)) return
|
||||
cancelWork()
|
||||
error.value = '等待验证超时,请检查身份验证。'
|
||||
}, authenticationTimeout)
|
||||
}
|
||||
|
||||
function schedulePoll(current: number, id: number) {
|
||||
if (dialogVisible.value && isCurrent(current, id)) {
|
||||
pollTimer = setTimeout(() => void checkIdentity(current, id), pollInterval)
|
||||
}
|
||||
}
|
||||
|
||||
const refresh = () => run('refresh')
|
||||
const start = () => run('start')
|
||||
const complete = () => run('complete')
|
||||
async function requestIdentity<T>(request: (signal: AbortSignal) => Promise<T>): Promise<T> {
|
||||
const controller = new AbortController()
|
||||
identityRequest = controller
|
||||
try {
|
||||
return await request(controller.signal)
|
||||
} finally {
|
||||
if (identityRequest === controller) identityRequest = undefined
|
||||
}
|
||||
}
|
||||
|
||||
async function queryIdentity(id: number) {
|
||||
return validateEsignIdentityStatus(await requestIdentity((signal) => prescriptionEsignIdentityStatus({ id }, signal)))
|
||||
}
|
||||
|
||||
async function checkIdentity(current: number, id: number) {
|
||||
if (!isCurrent(current, id) || identityRequest || (!dialogVisible.value && work.value !== 'identity')) return
|
||||
try {
|
||||
const result = await queryIdentity(id)
|
||||
if (!isCurrent(current, id)) return
|
||||
if (Date.now() >= expiresAt) {
|
||||
stopVerification('等待验证超时,请检查身份验证。')
|
||||
return
|
||||
}
|
||||
accept(result)
|
||||
// Only this read-only server response can unlock the explicit confirmation button.
|
||||
if (result.verification_method) {
|
||||
stopVerification('签署方式已变化,请查询签署状态。')
|
||||
} else if (result.identity_status === 'FAIL' || result.identity_status === 'EXPIRED') {
|
||||
restartRequired.value = result.can_sign && ['authenticating', 'failed'].includes(result.status)
|
||||
stopVerification(result.identity_status === 'EXPIRED' ? '本次身份验证已过期。' : '本次身份验证未通过。')
|
||||
} else if (result.status === 'signed') {
|
||||
clearVerification()
|
||||
} else if (!canCheckEsignIdentity(result) || result.identity_status === 'UNAVAILABLE') {
|
||||
stopVerification(result.message || '暂时无法核对身份验证,请重试。')
|
||||
} else if (result.identity_details_required || result.can_complete) {
|
||||
dialogVisible.value = false
|
||||
readiness.value = result.identity_details_required ? 'details' : 'ready'
|
||||
} else if (authUrl.value) {
|
||||
dialogVisible.value = true
|
||||
} else {
|
||||
stopVerification('验证链接不可用,请重试或联系管理员。')
|
||||
}
|
||||
} catch {
|
||||
if (isCurrent(current, id)) {
|
||||
confirmed.value = false
|
||||
stopVerification('身份验证查询失败,请查询签署状态后重试。')
|
||||
}
|
||||
}
|
||||
schedulePoll(current, id)
|
||||
}
|
||||
|
||||
async function recheckIdentity() {
|
||||
if (!canAct() || !confirmed.value || !identityResumable.value || dialogVisible.value || readiness.value || restartRequired.value) return
|
||||
const id = props.prescriptionId
|
||||
const current = ++operation
|
||||
work.value = 'identity'
|
||||
error.value = ''
|
||||
beginVerification(current, id)
|
||||
try {
|
||||
await checkIdentity(current, id)
|
||||
} finally {
|
||||
if (isCurrent(current, id)) work.value = null
|
||||
}
|
||||
}
|
||||
|
||||
async function start(restart = false) {
|
||||
if (!canAct() || !confirmed.value || !state.value?.can_sign || verificationMethod.value || dialogVisible.value || readiness.value
|
||||
|| !['pending', 'authenticating', 'failed'].includes(state.value.status)
|
||||
|| restart !== restartRequired.value || (!restart && identityResumable.value)) return
|
||||
const id = props.prescriptionId
|
||||
const current = ++operation
|
||||
work.value = 'start'
|
||||
confirmed.value = false
|
||||
error.value = ''
|
||||
try {
|
||||
const result = validateEsignStatus(await prescriptionEsignStart(restart ? { id, restart_identity: true } : { id }))
|
||||
if (!isCurrent(current, id)) return
|
||||
accept(result)
|
||||
restartRequired.value = false
|
||||
if (result.status === 'authenticating' && result.can_sign) {
|
||||
if (!authUrl.value) {
|
||||
error.value = '验证链接无效,请重试或联系管理员。'
|
||||
return
|
||||
}
|
||||
dialogVisible.value = true
|
||||
beginVerification(current, id)
|
||||
schedulePoll(current, id)
|
||||
}
|
||||
} catch {
|
||||
if (isCurrent(current, id)) error.value = '验证请求结果待确认,请查询签署状态。'
|
||||
} finally {
|
||||
if (isCurrent(current, id)) work.value = null
|
||||
}
|
||||
}
|
||||
|
||||
function applyMethodIdentity(result: PrescriptionEsignIdentityStatus, method: VerificationMethod, current: number, id: number) {
|
||||
if (result.can_sign && !canUseMethod(result, method)) throw new Error('签署方式已变化')
|
||||
accept(result)
|
||||
if (!canUseMethod(result, method) || accountSetupMessage.value) return
|
||||
if (result.can_complete) {
|
||||
beginVerification(current, id)
|
||||
readiness.value = 'ready'
|
||||
} else if (method === 'sms') {
|
||||
if (result.sms_sent && result.identity_status === 'ING') smsCodeState.value = 'entry'
|
||||
if (result.identity_status === 'EXPIRED' || result.identity_status === 'FAIL') smsCodeState.value = 'expired'
|
||||
}
|
||||
}
|
||||
|
||||
async function readMethodIdentity(current: number, id: number, method: VerificationMethod) {
|
||||
const result = await queryIdentity(id)
|
||||
if (!isCurrent(current, id)) return
|
||||
applyMethodIdentity(result, method, current, id)
|
||||
return result
|
||||
}
|
||||
|
||||
async function prepareQuick(result: PrescriptionEsignStatus, current: number, id: number) {
|
||||
work.value = 'identity'
|
||||
const retained = result.can_resume_identity === true
|
||||
if (retained) {
|
||||
const identity = await readMethodIdentity(current, id, 'quick')
|
||||
if (!identity || identity.identity_status !== 'EXPIRED' || !canUseMethod(identity, 'quick') || accountSetupMessage.value) return
|
||||
}
|
||||
if (!isCurrent(current, id)) return
|
||||
const prepared = validateEsignStatus(await prescriptionEsignStart(retained ? { id, restart_identity: true } : { id }))
|
||||
if (!isCurrent(current, id)) return
|
||||
accept(prepared)
|
||||
if (canUseMethod(prepared, 'quick') && prepared.can_resume_identity && !accountSetupMessage.value) {
|
||||
await readMethodIdentity(current, id, 'quick')
|
||||
}
|
||||
}
|
||||
|
||||
function startSmsCooldown() {
|
||||
clearTimeout(resendTimer)
|
||||
smsSendCoolingDown.value = true
|
||||
resendTimer = setTimeout(() => { smsSendCoolingDown.value = false }, smsSendCooldown)
|
||||
}
|
||||
|
||||
async function sendSms() {
|
||||
if (!canAct() || !confirmed.value || !canUseMethod(state.value, 'sms') || accountSetupMessage.value || readiness.value
|
||||
|| smsSendCoolingDown.value || (state.value?.sms_sent && !smsCodeEntry.value && smsCodeState.value !== 'expired')) return
|
||||
const id = props.prescriptionId
|
||||
const current = ++operation
|
||||
const restart = state.value?.sms_sent === true || state.value?.can_resume_identity === true
|
||||
clearVerification()
|
||||
smsProfileReady.value = false
|
||||
confirmed.value = false
|
||||
work.value = 'send-sms'
|
||||
error.value = ''
|
||||
startSmsCooldown()
|
||||
try {
|
||||
const result = validateEsignStatus(await prescriptionEsignStart(restart ? { id, restart_identity: true } : { id }))
|
||||
if (!isCurrent(current, id)) return
|
||||
accept(result)
|
||||
if (canUseMethod(result, 'sms') && result.sms_sent && result.can_resume_identity && !accountSetupMessage.value) {
|
||||
startSmsCooldown()
|
||||
work.value = 'identity'
|
||||
await readMethodIdentity(current, id, 'sms')
|
||||
}
|
||||
} catch {
|
||||
if (isCurrent(current, id)) {
|
||||
confirmed.value = false
|
||||
error.value = '短信发送状态待确认,请查询签署状态。'
|
||||
}
|
||||
} finally {
|
||||
if (isCurrent(current, id)) work.value = null
|
||||
}
|
||||
}
|
||||
|
||||
async function verifySms() {
|
||||
const code = smsCode.value.trim()
|
||||
smsCode.value = ''
|
||||
if (!canAct() || !smsCodeEntry.value) return
|
||||
if (!/^\d{6}$/.test(code)) {
|
||||
error.value = '请输入6位短信验证码。'
|
||||
return
|
||||
}
|
||||
const id = props.prescriptionId
|
||||
const current = ++operation
|
||||
clearVerification()
|
||||
confirmed.value = false
|
||||
work.value = 'verify-sms'
|
||||
error.value = ''
|
||||
try {
|
||||
const result = validateEsignIdentityStatus(await prescriptionEsignVerifyWillingness({ id, auth_code: code }))
|
||||
if (!isCurrent(current, id)) return
|
||||
applyMethodIdentity(result, 'sms', current, id)
|
||||
if (smsCodeEntry.value) error.value = '验证码未通过,请检查后重试。'
|
||||
} catch {
|
||||
if (isCurrent(current, id)) error.value = '短信校验结果待确认,请查询签署状态。'
|
||||
} finally {
|
||||
if (isCurrent(current, id)) work.value = null
|
||||
}
|
||||
}
|
||||
|
||||
async function confirmSign() {
|
||||
const number = identityNumber.value.trim().toUpperCase()
|
||||
identityNumber.value = ''
|
||||
if (!canAct() || !confirmed.value || !readiness.value || !canCheckEsignIdentity(state.value)) return
|
||||
if (verificationMethod.value && (!canUseMethod(state.value, verificationMethod.value) || accountSetupMessage.value)) return
|
||||
if (Date.now() >= expiresAt) {
|
||||
stopVerification('等待验证超时,请检查身份验证。')
|
||||
return
|
||||
}
|
||||
if (identityDetailsRequired.value && !/^[1-9]\d{16}[\dX]$/.test(number)) {
|
||||
error.value = '请输入本次验证使用的18位大陆居民身份证号。'
|
||||
return
|
||||
}
|
||||
const id = props.prescriptionId
|
||||
await submitCompletion('sign', identityDetailsRequired.value ? { id, identity_number: number } : { id })
|
||||
}
|
||||
|
||||
async function retryVerification() {
|
||||
if (!canAct() || !confirmed.value || state.value?.status !== 'uncertain' || state.value.can_retry_verify !== true) return
|
||||
await submitCompletion('verify', { id: props.prescriptionId, verify_only: true })
|
||||
}
|
||||
|
||||
async function submitCompletion(kind: 'sign' | 'verify', params: Parameters<typeof prescriptionEsignComplete>[0]) {
|
||||
const current = ++operation
|
||||
const { id } = params
|
||||
// Consume readiness before dispatch. Neither an error nor a late reply replays the POST.
|
||||
clearVerification()
|
||||
confirmed.value = false
|
||||
work.value = kind
|
||||
error.value = ''
|
||||
try {
|
||||
const result = validateEsignStatus(await prescriptionEsignComplete(params))
|
||||
if (isCurrent(current, id)) accept(result)
|
||||
} catch {
|
||||
if (isCurrent(current, id)) {
|
||||
error.value = kind === 'sign' ? '签署结果待确认,请查询签署状态。' : '校验结果待确认,请查询签署状态。'
|
||||
}
|
||||
} finally {
|
||||
if (isCurrent(current, id)) work.value = null
|
||||
}
|
||||
}
|
||||
|
||||
async function refresh() {
|
||||
if (!canAct()) return
|
||||
const id = props.prescriptionId
|
||||
const current = ++operation
|
||||
clearVerification()
|
||||
smsProfileReady.value = false
|
||||
work.value = 'status'
|
||||
confirmed.value = false
|
||||
error.value = ''
|
||||
try {
|
||||
const result = validateEsignStatus(await prescriptionEsignStatus({ id }))
|
||||
if (!isCurrent(current, id)) return
|
||||
accept(result)
|
||||
// A previous SMS failure can retain the setup flag after the doctor fixes the profile.
|
||||
if (canUseMethod(result, 'sms') && result.doctor_identity_required) {
|
||||
work.value = 'identity'
|
||||
const profile = await requestIdentity(prescriptionEsignDoctorStatus)
|
||||
if (!isCurrent(current, id)) return
|
||||
smsProfileReady.value = profile?.enabled === true && profile.status === 'ready'
|
||||
}
|
||||
if (accountSetupMessage.value) return
|
||||
if (canUseMethod(result, 'quick')) {
|
||||
await prepareQuick(result, current, id)
|
||||
} else if (canUseMethod(result, 'sms') && result.sms_sent && result.can_resume_identity) {
|
||||
work.value = 'identity'
|
||||
await readMethodIdentity(current, id, 'sms')
|
||||
}
|
||||
} catch {
|
||||
if (isCurrent(current, id)) {
|
||||
confirmed.value = false
|
||||
error.value = work.value === 'identity' ? '暂时无法核对签署条件,请查询签署状态后重试。' : '签署状态查询失败,请重试。'
|
||||
}
|
||||
} finally {
|
||||
if (isCurrent(current, id)) work.value = null
|
||||
}
|
||||
}
|
||||
|
||||
async function download() {
|
||||
if (busy.value || !confirmed.value || state.value?.can_download !== true) return
|
||||
busy.value = true
|
||||
if (!canAct() || !confirmed.value || !state.value?.can_download
|
||||
|| (state.value.status !== 'signed' && state.value.status !== 'voided')) return
|
||||
const id = props.prescriptionId
|
||||
const current = ++operation
|
||||
work.value = 'download'
|
||||
error.value = ''
|
||||
try {
|
||||
await downloadPrescriptionPdfIfRequired(props.prescriptionId)
|
||||
} catch (e: any) {
|
||||
confirmed.value = false
|
||||
error.value = e?.msg || e?.message || '下载签署文件失败,请重试'
|
||||
const result = validateEsignStatus(await prescriptionEsignStatus({ id }))
|
||||
if (!isCurrent(current, id)) return
|
||||
accept(result)
|
||||
if (result.can_download && (result.status === 'signed' || result.status === 'voided')) {
|
||||
await downloadOriginalEsignPdf(id, () => isCurrent(current, id))
|
||||
} else {
|
||||
error.value = '已签 PDF 暂不可下载。'
|
||||
}
|
||||
} catch {
|
||||
if (isCurrent(current, id)) error.value = '下载已签 PDF 失败,请重试。'
|
||||
} finally {
|
||||
busy.value = false
|
||||
if (isCurrent(current, id)) work.value = null
|
||||
}
|
||||
}
|
||||
|
||||
watch(() => props.prescriptionId, () => {
|
||||
generation++
|
||||
busy.value = false
|
||||
function onVisibilityChange() {
|
||||
if (document.visibilityState === 'visible') return
|
||||
if (work.value === 'sign') error.value = '签署结果待确认,请查询签署状态。'
|
||||
if (work.value === 'verify') error.value = '校验结果待确认,请查询签署状态。'
|
||||
if (work.value === 'send-sms') error.value = '短信发送状态待确认,请查询签署状态。'
|
||||
if (work.value === 'verify-sms') error.value = '短信校验结果待确认,请查询签署状态。'
|
||||
cancelWork()
|
||||
}
|
||||
|
||||
function resetStatus() {
|
||||
cancelWork()
|
||||
restartRequired.value = false
|
||||
confirmed.value = false
|
||||
error.value = ''
|
||||
state.value = initialStatus()
|
||||
void refresh()
|
||||
}, { immediate: true })
|
||||
}
|
||||
|
||||
watch(() => props.prescriptionId, resetStatus, { immediate: true })
|
||||
watch(() => props.initialState, (value) => {
|
||||
if (value) {
|
||||
state.value = initialStatus()
|
||||
if (!state.value) confirmed.value = false
|
||||
}
|
||||
// An emitted state echoed by the parent preserves this interaction.
|
||||
if (toRaw(value) !== toRaw(state.value)) resetStatus()
|
||||
})
|
||||
|
||||
onMounted(() => document.addEventListener('visibilitychange', onVisibilityChange))
|
||||
onDeactivated(cancelWork)
|
||||
onBeforeUnmount(() => {
|
||||
disposed = true
|
||||
cancelWork()
|
||||
clearTimeout(resendTimer)
|
||||
document.removeEventListener('visibilitychange', onVisibilityChange)
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.esign-panel { margin: 12px 0; padding: 14px 16px; border: 1px solid var(--el-border-color-light); border-radius: 6px; background: var(--el-fill-color-light); }
|
||||
.esign-panel__heading, .esign-panel__actions { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
|
||||
.esign-panel__message { margin: 8px 0; color: var(--el-text-color-secondary); font-size: 13px; }
|
||||
.esign-panel__error { color: var(--el-color-danger); font-size: 13px; }
|
||||
.esign-panel {
|
||||
margin: 12px 0;
|
||||
padding: 14px 16px;
|
||||
border: 1px solid var(--el-border-color-light);
|
||||
border-radius: 6px;
|
||||
background: var(--el-bg-color);
|
||||
}
|
||||
.esign-panel__heading, .esign-panel__actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
.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__actions { margin-top: 10px; }
|
||||
.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 { color: var(--el-text-color-secondary); }
|
||||
.esign-panel__error { color: var(--el-color-danger); }
|
||||
.esign-panel__identity { display: grid; gap: 6px; max-width: 320px; margin: 10px 0; font-size: 13px; }
|
||||
.esign-panel__frame {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: min(62vh, 620px);
|
||||
min-height: 300px;
|
||||
border: 1px solid var(--el-border-color-light);
|
||||
border-radius: 4px;
|
||||
background: white;
|
||||
}
|
||||
@media print { .esign-panel { display: none; } }
|
||||
</style>
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
<template>
|
||||
<div v-if="state?.required || error" class="esign-review" v-loading="busy" aria-label="处方审核电子签署">
|
||||
<strong>审核电子签署</strong>
|
||||
<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="error" class="text-danger" role="alert">{{ error }}</p>
|
||||
<div class="esign-review__actions">
|
||||
<el-button v-if="state?.can_confirm" type="primary" size="small" :disabled="busy" @click="confirm(false)">
|
||||
确认签名
|
||||
</el-button>
|
||||
<el-button v-if="state?.can_retry_verify" type="primary" size="small" :disabled="busy" @click="confirm(true)">
|
||||
重试验签
|
||||
</el-button>
|
||||
<el-button v-if="state?.required && doctorSigned" size="small" :disabled="busy" @click="download">
|
||||
{{ state.state === 'signed' ? '下载双签 PDF' : '下载医生已签 PDF' }}
|
||||
</el-button>
|
||||
<el-button
|
||||
v-if="state?.can_setup && state.state !== 'signed'"
|
||||
size="small"
|
||||
:disabled="busy"
|
||||
@click="identityOpen = true"
|
||||
>
|
||||
审核签署身份
|
||||
</el-button>
|
||||
<el-button v-if="state?.required && !state.can_approve" size="small" :disabled="busy" @click="switchReviewer">
|
||||
切换审核账号
|
||||
</el-button>
|
||||
<el-button v-if="error || state?.state !== 'signed'" size="small" :disabled="busy" @click="refresh">
|
||||
刷新签署状态
|
||||
</el-button>
|
||||
</div>
|
||||
<EsignDoctorDialog
|
||||
v-if="identityOpen"
|
||||
reviewer
|
||||
:server-time-offset-ms="userStore.serverTimeOffsetMs"
|
||||
@close="closeIdentity"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { onBeforeUnmount, ref, watch } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
|
||||
import {
|
||||
prescriptionEsignReviewConfirm,
|
||||
prescriptionEsignReviewStatus,
|
||||
type PrescriptionEsignReviewStatus
|
||||
} from '@/api/tcm'
|
||||
import EsignDoctorDialog from '@/components/EsignDoctorDialog.vue'
|
||||
import useUserStore from '@/stores/modules/user'
|
||||
import feedback from '@/utils/feedback'
|
||||
import { downloadOriginalEsignPdf, formatSigningTime } from '@/utils/prescription-esign'
|
||||
|
||||
const props = defineProps<{ prescriptionId: number; orderId?: number; doctorSigned: boolean }>()
|
||||
const emit = defineEmits<{ (e: 'change', value: PrescriptionEsignReviewStatus | null): void }>()
|
||||
const state = ref<PrescriptionEsignReviewStatus | null>(null)
|
||||
const identityOpen = ref(false)
|
||||
const busy = ref(false)
|
||||
const error = ref('')
|
||||
const userStore = useUserStore()
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
let generation = 0
|
||||
let statusRequest: AbortController | undefined
|
||||
|
||||
function errorMessage(cause: unknown, fallback: string): string {
|
||||
if (typeof cause === 'object' && cause !== null && 'msg' in cause && typeof cause.msg === 'string') {
|
||||
return cause.msg
|
||||
}
|
||||
return cause instanceof Error ? cause.message : fallback
|
||||
}
|
||||
|
||||
function accept(result: PrescriptionEsignReviewStatus) {
|
||||
if (!result || ['required', 'can_confirm', 'can_approve', 'can_retry_verify'].some((field) => typeof (result as any)[field] !== 'boolean')
|
||||
|| result.actor_id !== Number(userStore.userInfo.id)) {
|
||||
throw new Error('登录账号或审核状态已变化,请刷新页面')
|
||||
}
|
||||
state.value = result
|
||||
emit('change', result)
|
||||
}
|
||||
|
||||
function target() {
|
||||
return { id: props.prescriptionId, ...(props.orderId ? { order_id: props.orderId } : {}) }
|
||||
}
|
||||
|
||||
async function refresh() {
|
||||
const ticket = ++generation
|
||||
statusRequest?.abort()
|
||||
statusRequest = new AbortController()
|
||||
busy.value = true
|
||||
error.value = ''
|
||||
emit('change', null)
|
||||
try {
|
||||
const result = await prescriptionEsignReviewStatus(target(), statusRequest.signal)
|
||||
if (ticket === generation) accept(result)
|
||||
} catch (cause) {
|
||||
if (ticket === generation) error.value = errorMessage(cause, '无法查询审核签署状态')
|
||||
} finally {
|
||||
if (ticket === generation) busy.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function confirm(verifyOnly: boolean) {
|
||||
const actorId = state.value?.actor_id
|
||||
if (busy.value || !actorId || !(verifyOnly ? state.value?.can_retry_verify : state.value?.can_confirm)) return
|
||||
const ticket = ++generation
|
||||
busy.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const result = await prescriptionEsignReviewConfirm({ ...target(), actor_id: actorId, verify_only: verifyOnly })
|
||||
if (ticket === generation) accept(result)
|
||||
} catch (cause) {
|
||||
if (ticket === generation) {
|
||||
await refresh()
|
||||
if (generation === ticket + 1) {
|
||||
error.value = errorMessage(cause, '请刷新状态或续期本人的快捷签授权后重试')
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
if (ticket === generation) busy.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function switchReviewer() {
|
||||
try {
|
||||
await feedback.confirm('当前账号将退出。请所选审核人本人登录。')
|
||||
if (busy.value) return
|
||||
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() {
|
||||
if (busy.value || !props.doctorSigned) return
|
||||
const ticket = generation
|
||||
const actor = userStore.userInfo.id
|
||||
busy.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
await downloadOriginalEsignPdf(props.prescriptionId,
|
||||
() => generation === ticket && userStore.userInfo.id === actor)
|
||||
} catch (cause) {
|
||||
if (generation === ticket) error.value = errorMessage(cause, '下载签署原件失败,请重试')
|
||||
} finally {
|
||||
if (generation === ticket) busy.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function closeIdentity() {
|
||||
identityOpen.value = false
|
||||
void refresh()
|
||||
}
|
||||
|
||||
watch(() => [props.prescriptionId, props.orderId, props.doctorSigned, userStore.userInfo.id],
|
||||
() => { if (props.prescriptionId > 0) void refresh() }, { immediate: true })
|
||||
onBeforeUnmount(() => {
|
||||
generation++
|
||||
statusRequest?.abort()
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.esign-review {
|
||||
display: grid;
|
||||
gap: 8px;
|
||||
border-top: 1px solid var(--el-border-color-light);
|
||||
margin-top: 12px;
|
||||
padding-top: 12px;
|
||||
}
|
||||
|
||||
.esign-review p {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.esign-review__actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.esign-review__actions :deep(.el-button + .el-button) {
|
||||
margin-left: 0;
|
||||
}
|
||||
</style>
|
||||
@@ -514,7 +514,7 @@
|
||||
{{ esignError }} <el-button link type="primary" @click="loadEsignConfig">重试</el-button>
|
||||
</el-alert>
|
||||
<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>
|
||||
<div class="signature-pad-wrap">
|
||||
<canvas
|
||||
@@ -540,6 +540,7 @@
|
||||
|
||||
<div v-else class="rx-wrap">
|
||||
<EsignPrescriptionPanel
|
||||
v-if="visible"
|
||||
:key="savedPrescription.id"
|
||||
:prescription-id="Number(savedPrescription.id)"
|
||||
:initial-state="savedPrescription.esign"
|
||||
@@ -726,7 +727,7 @@
|
||||
<div class="flex justify-end gap-2">
|
||||
<el-button @click="handleClose">取消</el-button>
|
||||
<el-button type="primary" @click="handleSave" :loading="saving || esignLoading" :disabled="!esignReady">
|
||||
{{ esignEnabled ? '保存后核身签署' : '保存处方' }}
|
||||
{{ esignEnabled ? '保存处方草稿' : '保存处方' }}
|
||||
</el-button>
|
||||
</div>
|
||||
</template>
|
||||
@@ -2133,11 +2134,16 @@ const handleSave = async () => {
|
||||
if (id) {
|
||||
// Keep the saved id even if the follow-up detail request fails; retrying must not add twice.
|
||||
savedPrescription.value = { ...formData, id, audit_status: 0, esign: res.esign }
|
||||
feedback.msgSuccess(res.esign?.required ? '处方已保存,请继续完成核身签署' : '处方已保存')
|
||||
feedback.msgSuccess(res.esign?.required ? '处方草稿已保存' : '处方已保存')
|
||||
try {
|
||||
savedPrescription.value = await prescriptionDetail({ id })
|
||||
const detail = await prescriptionDetail({ id })
|
||||
if (savedPrescription.value?.id === id) {
|
||||
savedPrescription.value = { ...detail, esign: savedPrescription.value.esign ?? detail.esign }
|
||||
}
|
||||
} catch {
|
||||
feedback.msgWarning('处方已保存,详情暂未加载,可从已开处方继续签署')
|
||||
if (savedPrescription.value?.id === id) {
|
||||
feedback.msgWarning(res.esign?.required ? '处方详情暂未加载,可继续操作' : '处方已保存,详情暂未加载,可从已开处方继续签署')
|
||||
}
|
||||
}
|
||||
emit('success')
|
||||
} else {
|
||||
|
||||
@@ -11,24 +11,85 @@
|
||||
<router-link to="/user/setting">
|
||||
<el-dropdown-item>个人设置</el-dropdown-item>
|
||||
</router-link>
|
||||
<el-dropdown-item v-if="canManageDoctorEsign" command="doctor-esign">
|
||||
医生电子签署身份
|
||||
</el-dropdown-item>
|
||||
<el-dropdown-item v-if="canManageReviewEsign" command="review-esign">
|
||||
审核签署身份
|
||||
</el-dropdown-item>
|
||||
<el-dropdown-item command="switch-account">切换账号</el-dropdown-item>
|
||||
<el-dropdown-item command="cache">清除缓存</el-dropdown-item>
|
||||
<el-dropdown-item command="logout">退出登录</el-dropdown-item>
|
||||
</el-dropdown-menu>
|
||||
</template>
|
||||
</el-dropdown>
|
||||
<esign-doctor-dialog
|
||||
v-if="(canManageDoctorEsign && doctorEsignOpen) || (canManageReviewEsign && reviewEsignOpen)"
|
||||
:reviewer="reviewEsignOpen"
|
||||
:server-time-offset-ms="userStore.serverTimeOffsetMs"
|
||||
@close="closeEsign"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
|
||||
import { systemCacheClear } from '@/api/setting/system'
|
||||
import { prescriptionEsignConfig } from '@/api/tcm'
|
||||
import EsignDoctorDialog from '@/components/EsignDoctorDialog.vue'
|
||||
import useUserStore from '@/stores/modules/user'
|
||||
import feedback from '@/utils/feedback'
|
||||
import { hasPermission } from '@/utils/perm'
|
||||
|
||||
const userStore = useUserStore()
|
||||
const route = useRoute()
|
||||
|
||||
const userInfo = computed(() => userStore.userInfo)
|
||||
const doctorEsignOpen = ref(false)
|
||||
const reviewEsignOpen = ref(false)
|
||||
const reviewEnabled = ref(false)
|
||||
// These are the write grants accepted by the doctor eSign endpoints.
|
||||
const prescriptionWritePermissions = [
|
||||
'tcm.prescription/add', 'tcm.prescription/edit', 'cf.prescription/add', 'cf.prescription/edit',
|
||||
'tcm.diagnosis/chufang', 'tcm.diagnosis/kaifang'
|
||||
]
|
||||
const canManageDoctorEsign = computed(() => {
|
||||
const { role_ids, root } = userInfo.value
|
||||
return Boolean(userStore.token) && Array.isArray(role_ids) && role_ids.some((id) => Number(id) === 1)
|
||||
&& (Number(root) === 1 || prescriptionWritePermissions.some((permission) => hasPermission([permission])))
|
||||
})
|
||||
const canManageReviewEsign = computed(() => Boolean(userStore.token) && reviewEnabled.value
|
||||
&& [ 'tcm.prescriptionOrder/auditPrescription', 'tcm.prescription/audit', 'cf.prescription/audit' ]
|
||||
.some((permission) => hasPermission([permission])))
|
||||
|
||||
function closeEsign() {
|
||||
doctorEsignOpen.value = false
|
||||
reviewEsignOpen.value = false
|
||||
}
|
||||
|
||||
watch([() => userStore.token, () => userInfo.value.id, canManageDoctorEsign, canManageReviewEsign], closeEsign, { flush: 'sync' })
|
||||
onMounted(async () => {
|
||||
try {
|
||||
const config = await prescriptionEsignConfig()
|
||||
reviewEnabled.value = config.enabled && config.review_enabled === true && config.verification_method === 'quick'
|
||||
} catch {
|
||||
reviewEnabled.value = false
|
||||
}
|
||||
})
|
||||
|
||||
const handleCommand = async (command: string) => {
|
||||
switch (command) {
|
||||
case 'doctor-esign':
|
||||
if (canManageDoctorEsign.value) doctorEsignOpen.value = true
|
||||
break
|
||||
case 'review-esign':
|
||||
if (canManageReviewEsign.value) reviewEsignOpen.value = true
|
||||
break
|
||||
case 'switch-account':
|
||||
await feedback.confirm('当前账号将退出。请使用另一个账号登录。')
|
||||
await userStore.logout(route.fullPath)
|
||||
break
|
||||
case 'logout':
|
||||
await feedback.confirm('确定退出登录吗?')
|
||||
userStore.logout()
|
||||
|
||||
@@ -58,13 +58,17 @@ const useUserStore = defineStore({
|
||||
})
|
||||
})
|
||||
},
|
||||
logout() {
|
||||
logout(returnTo?: string) {
|
||||
return new Promise((resolve, reject) => {
|
||||
logout()
|
||||
.then(async (data) => {
|
||||
this.token = ''
|
||||
await router.push(PageEnum.LOGIN)
|
||||
clearAuthInfo()
|
||||
if (returnTo) {
|
||||
window.location.assign(router.resolve({ path: PageEnum.LOGIN, query: { redirect: returnTo, switch_account: '1' } }).href)
|
||||
} else {
|
||||
await router.push(PageEnum.LOGIN)
|
||||
}
|
||||
resolve(data)
|
||||
})
|
||||
.catch((error) => {
|
||||
|
||||
@@ -2,9 +2,39 @@ import {
|
||||
prescriptionEsignDownload,
|
||||
prescriptionEsignStatus,
|
||||
type PrescriptionEsignFile,
|
||||
type PrescriptionEsignIdentityStatus,
|
||||
type PrescriptionEsignStatus
|
||||
} from '@/api/tcm'
|
||||
|
||||
const signingTimeFormatter = new Intl.DateTimeFormat('zh-CN', {
|
||||
timeZone: 'Asia/Shanghai',
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
second: '2-digit',
|
||||
hourCycle: 'h23'
|
||||
})
|
||||
|
||||
export function formatSigningTime(seconds: number | undefined): string {
|
||||
if (typeof seconds !== 'number' || !Number.isInteger(seconds) || seconds <= 0 || seconds > 253402300799) return ''
|
||||
return signingTimeFormatter.format(seconds * 1000)
|
||||
}
|
||||
|
||||
export function prescriptionEsignTiming(state?: PrescriptionEsignStatus | null) {
|
||||
if (!state || (state.status !== 'signed' && state.status !== 'voided')) return null
|
||||
|
||||
const source = state.signature_time_source === 'tsa' ? '可信时间戳'
|
||||
: state.signature_time_source === 'local' ? '签名记录时间' : ''
|
||||
const signatureTime = source ? formatSigningTime(state.signature_time) : ''
|
||||
const verifiedTime = formatSigningTime(state.signed_at)
|
||||
const issuedTime = formatSigningTime(state.issued_at)
|
||||
if (state.status === 'voided' && !state.can_download && !signatureTime && !verifiedTime && !issuedTime) return null
|
||||
|
||||
return { issuedTime, signatureTime, source, verifiedTime }
|
||||
}
|
||||
|
||||
export function safeEsignAuthUrl(value: unknown): string {
|
||||
if (typeof value !== 'string' || !value.trim() || /[\u0000-\u001f\\]/.test(value)) return ''
|
||||
try {
|
||||
@@ -22,12 +52,38 @@ export function validateEsignStatus(value: unknown): PrescriptionEsignStatus {
|
||||
const statuses = ['pending', 'authenticating', 'signing', 'signed', 'failed', 'uncertain', 'voided', 'legacy']
|
||||
if (!state || typeof state !== 'object' || !statuses.includes(state.status)
|
||||
|| !['sandbox', 'production'].includes(state.environment)
|
||||
|| ['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.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')) {
|
||||
throw new Error('无法核对处方签署状态,请刷新后重试')
|
||||
}
|
||||
return state
|
||||
}
|
||||
|
||||
export function canCheckEsignIdentity(state: PrescriptionEsignStatus | null): boolean {
|
||||
return state?.can_sign === true && (state.status === 'authenticating'
|
||||
|| (state.status === 'failed' && state.can_resume_identity === true))
|
||||
}
|
||||
|
||||
export function validateEsignIdentityStatus(value: unknown): PrescriptionEsignIdentityStatus {
|
||||
const state = validateEsignStatus(value) as PrescriptionEsignIdentityStatus
|
||||
const detailsRequired = state.identity_details_required ?? false
|
||||
const accountBased = state.verification_method === 'quick' || state.verification_method === 'sms'
|
||||
if (!['INIT', 'ING', 'SUCCESS', 'FAIL', 'EXPIRED', 'UNAVAILABLE'].includes(state.identity_status)
|
||||
|| typeof state.can_complete !== 'boolean'
|
||||
|| (state.identity_details_required !== undefined && typeof state.identity_details_required !== 'boolean')
|
||||
|| (state.can_complete && detailsRequired)
|
||||
|| (accountBased && (detailsRequired || (state.can_complete && (state.can_resume_identity !== true
|
||||
|| state.doctor_identity_required === true || state.signing_authorization_required === true
|
||||
|| (state.verification_method === 'sms' && state.sms_sent !== true)))))
|
||||
|| ((state.can_complete || detailsRequired)
|
||||
&& (state.identity_status !== 'SUCCESS' || !canCheckEsignIdentity(state)))) {
|
||||
throw new Error('无法核对身份验证结果,请刷新状态后重试')
|
||||
}
|
||||
return { ...state, identity_details_required: detailsRequired }
|
||||
}
|
||||
|
||||
export function requiresOriginalEsignPdf(status?: PrescriptionEsignStatus | null): boolean {
|
||||
try {
|
||||
const value = validateEsignStatus(status)
|
||||
@@ -37,6 +93,17 @@ export function requiresOriginalEsignPdf(status?: PrescriptionEsignStatus | null
|
||||
}
|
||||
}
|
||||
|
||||
export function canApprovePrescriptionEsign(status: unknown): boolean {
|
||||
try {
|
||||
const state = validateEsignStatus(status)
|
||||
return state.required
|
||||
? state.status === 'signed' && state.can_download
|
||||
: state.status === 'legacy' && !state.can_download
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/** Verify the received bytes before creating a download; never render or alter the signed PDF. */
|
||||
export async function verifyEsignPdf(file: PrescriptionEsignFile): Promise<Uint8Array> {
|
||||
if (!/^[a-f\d]{64}$/i.test(file.sha256 || '')) throw new Error('签署文件缺少有效校验信息')
|
||||
@@ -56,9 +123,11 @@ export async function verifyEsignPdf(file: PrescriptionEsignFile): Promise<Uint8
|
||||
return bytes
|
||||
}
|
||||
|
||||
export async function downloadOriginalEsignPdf(id: number): Promise<void> {
|
||||
export async function downloadOriginalEsignPdf(id: number, isCurrent = () => true): Promise<void> {
|
||||
const file = await prescriptionEsignDownload({ id })
|
||||
if (!isCurrent()) return
|
||||
const bytes = await verifyEsignPdf(file)
|
||||
if (!isCurrent()) return
|
||||
const url = URL.createObjectURL(new Blob([bytes], { type: 'application/pdf' }))
|
||||
const link = document.createElement('a')
|
||||
link.href = url
|
||||
|
||||
@@ -39,6 +39,22 @@
|
||||
<template #prepend>
|
||||
<icon name="el-icon-User" size="16" />
|
||||
</template>
|
||||
<template v-if="rememberedAccounts.length" #append>
|
||||
<el-dropdown trigger="click" @command="selectRememberedAccount">
|
||||
<el-button>选择账号</el-button>
|
||||
<template #dropdown>
|
||||
<el-dropdown-menu>
|
||||
<el-dropdown-item
|
||||
v-for="account in rememberedAccounts"
|
||||
:key="account"
|
||||
:command="account"
|
||||
>
|
||||
{{ account }}
|
||||
</el-dropdown-item>
|
||||
</el-dropdown-menu>
|
||||
</template>
|
||||
</el-dropdown>
|
||||
</template>
|
||||
</el-input>
|
||||
</el-form-item>
|
||||
<el-form-item prop="password">
|
||||
@@ -122,6 +138,8 @@ const userStore = useUserStore()
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const remAccount = ref(false)
|
||||
const rememberedAccounts = ref<string[]>([])
|
||||
const switchingAccount = computed(() => route.query.switch_account === '1')
|
||||
const config = computed(() => appStore.config)
|
||||
const formData = reactive({
|
||||
account: '',
|
||||
@@ -214,11 +232,15 @@ const handleEnter = () => {
|
||||
|
||||
const handleLogin = async () => {
|
||||
await formRef.value?.validate()
|
||||
const result: any = await userStore.login(formData)
|
||||
const account = formData.account.trim()
|
||||
const others = rememberedAccounts.value.filter((saved) => saved !== account)
|
||||
rememberedAccounts.value = (remAccount.value ? [account, ...others] : others).slice(0, 15)
|
||||
cache.set(ACCOUNT_KEY, {
|
||||
remember: remAccount.value,
|
||||
account: remAccount.value ? formData.account : ''
|
||||
account: remAccount.value ? account : '',
|
||||
accounts: rememberedAccounts.value
|
||||
})
|
||||
const result: any = await userStore.login(formData)
|
||||
|
||||
// 检查是否需要修改密码
|
||||
if (result.is_paw === 0) {
|
||||
@@ -307,11 +329,21 @@ watch(loginMode, (val) => {
|
||||
}
|
||||
})
|
||||
|
||||
function selectRememberedAccount(account: string) {
|
||||
formData.account = account
|
||||
formData.password = ''
|
||||
remAccount.value = true
|
||||
passwordRef.value?.focus()
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
// 恢复记住账号
|
||||
const value = cache.get(ACCOUNT_KEY)
|
||||
if (value?.remember) {
|
||||
remAccount.value = value.remember
|
||||
const saved: unknown[] = Array.isArray(value?.accounts) ? value.accounts : value?.remember ? [value.account] : []
|
||||
rememberedAccounts.value = [...new Set(saved.filter((account): account is string =>
|
||||
typeof account === 'string' && account.trim().length > 0))].slice(0, 15)
|
||||
if (!switchingAccount.value && value?.remember && rememberedAccounts.value.includes(value.account)) {
|
||||
remAccount.value = true
|
||||
formData.account = value.account
|
||||
}
|
||||
|
||||
@@ -342,7 +374,7 @@ onMounted(async () => {
|
||||
wxWorkConfig.value = { corp_id: res.corp_id, agent_id: res.agent_id }
|
||||
|
||||
// 在企业微信内:自动跳转 OAuth 授权
|
||||
if (isInWxWork() && !hasIamCallback) {
|
||||
if (isInWxWork() && !hasIamCallback && !switchingAccount.value) {
|
||||
const redirectUri = encodeURIComponent(getRedirectUri())
|
||||
const authUrl =
|
||||
`https://open.weixin.qq.com/connect/oauth2/authorize` +
|
||||
|
||||
@@ -169,6 +169,9 @@
|
||||
<el-tag :type="listAuditStatusTagType(row)">
|
||||
{{ listAuditStatusLabel(row) }}
|
||||
</el-tag>
|
||||
<el-tag v-if="pendingEsignAudit(row)" type="warning" size="small" effect="plain">
|
||||
{{ row.esign.status_label }}
|
||||
</el-tag>
|
||||
<span
|
||||
v-if="Number(row.business_prescription_audit_rejected) === 1"
|
||||
class="text-xs text-gray-500"
|
||||
@@ -244,11 +247,11 @@
|
||||
编辑
|
||||
</el-button>
|
||||
<el-button
|
||||
v-if="row.audit_status === 0 && row.void_status !== 1"
|
||||
v-if="isPendingPrescriptionAudit(row)"
|
||||
type="warning"
|
||||
link
|
||||
v-perms="['cf.prescription/audit']"
|
||||
@click="openAuditDialog(row)"
|
||||
@click="openAuditDialog(Number(row.id))"
|
||||
>
|
||||
审核
|
||||
</el-button>
|
||||
@@ -279,12 +282,13 @@
|
||||
class="cf-prescription-drawer"
|
||||
:close-on-click-modal="false"
|
||||
destroy-on-close
|
||||
@close="showEdit = false"
|
||||
@closed="onEditDialogClosed"
|
||||
>
|
||||
<!-- 查看:A4 处方笺(药房联样式) -->
|
||||
<div v-if="editMode === 'view'" v-loading="viewDetailLoading" class="rx-wrap">
|
||||
<EsignPrescriptionPanel
|
||||
v-if="slipView?.id && !viewDetailLoading"
|
||||
v-if="showEdit && slipView?.id && !viewDetailLoading"
|
||||
:key="slipView.id"
|
||||
:prescription-id="Number(slipView.id)"
|
||||
:initial-state="slipView.esign"
|
||||
@@ -315,7 +319,17 @@
|
||||
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">
|
||||
{{ slipView.esign.status_label }}
|
||||
</el-tag>
|
||||
<div class="flex-1" />
|
||||
<el-button
|
||||
v-if="slipView && !viewDetailLoading && isPendingPrescriptionAudit(slipView)"
|
||||
v-perms="['cf.prescription/audit']"
|
||||
type="warning"
|
||||
size="small"
|
||||
@click="openAuditDialog(Number(slipView.id))"
|
||||
>审核</el-button>
|
||||
<el-button v-if="!requiresOriginalEsignPdf(slipView?.esign)" :icon="Printer" size="small" @click="handlePrintSlip">打印</el-button>
|
||||
<el-button
|
||||
type="primary"
|
||||
@@ -996,7 +1010,7 @@
|
||||
{{ esignError }} <el-button link type="primary" @click="loadEsignConfig">重试</el-button>
|
||||
</el-alert>
|
||||
<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>
|
||||
<div class="signature-pad-wrap">
|
||||
<canvas
|
||||
@@ -1023,7 +1037,7 @@
|
||||
<template v-else>
|
||||
<el-button @click="showEdit = false">取消</el-button>
|
||||
<el-button type="primary" @click="handleSubmit" :loading="submitLoading || esignLoading" :disabled="!esignReady">
|
||||
{{ esignEnabled ? '保存后核身签署' : '确定' }}
|
||||
{{ esignEnabled ? '保存处方草稿' : '确定' }}
|
||||
</el-button>
|
||||
</template>
|
||||
</template>
|
||||
@@ -1544,6 +1558,15 @@
|
||||
</el-dialog>
|
||||
|
||||
<el-dialog v-model="auditDialogVisible" title="处方审核" width="480px" destroy-on-close @closed="auditRemark = ''">
|
||||
<EsignPrescriptionPanel
|
||||
v-if="auditDialogVisible"
|
||||
:key="auditTargetId"
|
||||
:prescription-id="auditTargetId"
|
||||
audit
|
||||
@review-change="auditReview = $event"
|
||||
class="mb-3"
|
||||
@status-change="onAuditEsignStatusChange"
|
||||
/>
|
||||
<p class="text-sm text-gray-600 mb-3">
|
||||
通过:处方保持有效。驳回:将同时作废此处方(与诊间「驳回/作废处方」一致)。
|
||||
</p>
|
||||
@@ -1561,7 +1584,7 @@
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<el-button @click="auditDialogVisible = false">取消</el-button>
|
||||
<el-button type="primary" :loading="auditLoading" @click="submitAudit('approve')">审核通过</el-button>
|
||||
<el-button type="primary" :loading="auditLoading" :disabled="!canApproveAudit" @click="submitAudit('approve')">审核通过</el-button>
|
||||
<el-button type="danger" :loading="auditLoading" @click="submitAudit('reject')">驳回处方</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
@@ -1599,11 +1622,11 @@ import MedicineNameSelect from '@/components/medicine-name-select/index.vue'
|
||||
import PrescriptionSlip from '@/components/prescription-slip/index.vue'
|
||||
import EsignPrescriptionPanel from '@/components/EsignPrescriptionPanel.vue'
|
||||
import { usePrescriptionEsignConfig } from '@/hooks/usePrescriptionEsignConfig'
|
||||
import { downloadPrescriptionPdfIfRequired, requiresOriginalEsignPdf } from '@/utils/prescription-esign'
|
||||
import { canApprovePrescriptionEsign, downloadPrescriptionPdfIfRequired, requiresOriginalEsignPdf } from '@/utils/prescription-esign'
|
||||
import type { PrescriptionEsignStatus } from '@/api/tcm'
|
||||
import { Search, Download, Printer, EditPen } from '@element-plus/icons-vue'
|
||||
import { computed, onMounted, onActivated, onDeactivated, reactive, ref, watch, nextTick, defineAsyncComponent } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import html2canvas from 'html2canvas'
|
||||
import jsPDF from 'jspdf'
|
||||
|
||||
@@ -1743,6 +1766,7 @@ const SLIP_ADDRESS_LINE = '地址:四川省成都市双流区黄甲街道黄
|
||||
|
||||
const userStore = useUserStore()
|
||||
const router = useRouter()
|
||||
const route = useRoute()
|
||||
|
||||
function goBusinessOrderList() {
|
||||
const hit = router.getRoutes().find((r) => r.meta?.perms === 'tcm.prescriptionOrder/lists')
|
||||
@@ -1799,6 +1823,11 @@ const auditDialogVisible = ref(false)
|
||||
const auditTargetId = ref(0)
|
||||
const auditRemark = ref('')
|
||||
const auditLoading = ref(false)
|
||||
const auditEsign = ref<PrescriptionEsignStatus | null>(null)
|
||||
const auditReview = ref<import('@/api/tcm').PrescriptionEsignReviewStatus | null>(null)
|
||||
const canApproveAudit = computed(() => (
|
||||
canApprovePrescriptionEsign(auditEsign.value) && auditReview.value?.can_approve === true
|
||||
))
|
||||
|
||||
/** 修正处方笺显示用姓名 / 手机号 */
|
||||
const patchPatientVisible = ref(false)
|
||||
@@ -3094,6 +3123,14 @@ function isApprovedActivePrescription(row: { audit_status?: number; void_status?
|
||||
return Number(row.audit_status) === 1 && Number(row.void_status) !== 1
|
||||
}
|
||||
|
||||
function isPendingPrescriptionAudit(row: { audit_status?: number | string; void_status?: number | string }) {
|
||||
return (row.audit_status === 0 || row.audit_status === '0') && Number(row.void_status) !== 1
|
||||
}
|
||||
|
||||
function pendingEsignAudit(row: { audit_status?: number | string; void_status?: number | string; esign?: PrescriptionEsignStatus }) {
|
||||
return isPendingPrescriptionAudit(row) && row.esign?.required === true && !canApprovePrescriptionEsign(row.esign)
|
||||
}
|
||||
|
||||
function formatAuditTime(ts: number | null | undefined) {
|
||||
if (!ts) return ''
|
||||
const d = new Date(ts * 1000)
|
||||
@@ -3302,13 +3339,27 @@ function normalizeVisibleRoleIds(row: any): number[] {
|
||||
return []
|
||||
}
|
||||
|
||||
function openAuditDialog(row: any) {
|
||||
auditTargetId.value = row.id
|
||||
function openAuditDialog(id: number) {
|
||||
if (auditLoading.value) return
|
||||
auditTargetId.value = id
|
||||
auditEsign.value = null
|
||||
auditReview.value = null
|
||||
auditRemark.value = ''
|
||||
auditDialogVisible.value = true
|
||||
}
|
||||
|
||||
function onAuditEsignStatusChange(state: PrescriptionEsignStatus) {
|
||||
const justSigned = auditEsign.value && !canApproveAudit.value && state.status === 'signed'
|
||||
&& canApprovePrescriptionEsign(state)
|
||||
auditEsign.value = state
|
||||
if (justSigned) {
|
||||
if (Number(slipView.value?.id) === auditTargetId.value && slipView.value) slipView.value.esign = state
|
||||
else void getLists()
|
||||
}
|
||||
}
|
||||
|
||||
async function submitAudit(action: 'approve' | 'reject') {
|
||||
if (auditLoading.value || (action === 'approve' && !canApproveAudit.value)) return
|
||||
if (action === 'reject' && !auditRemark.value.trim()) {
|
||||
feedback.msgError('驳回时请填写审核意见')
|
||||
return
|
||||
@@ -3325,6 +3376,7 @@ async function submitAudit(action: 'approve' | 'reject') {
|
||||
feedback.msgWarning(auditData.wecom_notify_hint)
|
||||
}
|
||||
auditDialogVisible.value = false
|
||||
if (showEdit.value && Number(slipView.value?.id) === auditTargetId.value) showEdit.value = false
|
||||
getLists()
|
||||
} catch {
|
||||
/* 拦截器已提示 */
|
||||
@@ -3903,7 +3955,7 @@ const handleSubmit = async () => {
|
||||
}
|
||||
if (esignEnabled.value || requiresOriginalEsignPdf(result?.esign)) {
|
||||
const id = Number(result?.id || editForm.id)
|
||||
feedback.msgSuccess(result?.esign?.required ? '处方已保存,请继续完成核身签署' : '处方已保存,请核对电子签署状态')
|
||||
feedback.msgSuccess(result?.esign?.required ? '处方草稿已保存' : '处方已保存,请核对电子签署状态')
|
||||
await handleView({ ...editForm, id, audit_status: 0, esign: result?.esign })
|
||||
} else {
|
||||
feedback.msgSuccess('保存成功,处方已进入待审核')
|
||||
@@ -3955,6 +4007,8 @@ onMounted(async () => {
|
||||
/* 已登录页仍可无用户信息,保持默认筛选 */
|
||||
}
|
||||
getLists()
|
||||
const reviewId = Number(route.query.review_prescription)
|
||||
if (Number.isSafeInteger(reviewId) && reviewId > 0) openAuditDialog(reviewId)
|
||||
})
|
||||
</script>
|
||||
|
||||
|
||||
@@ -1297,11 +1297,21 @@
|
||||
</div>
|
||||
</template>
|
||||
</el-alert>
|
||||
<EsignPrescriptionPanel
|
||||
v-if="auditVisible && auditKind === 'prescription'"
|
||||
:key="auditTargetId"
|
||||
:prescription-id="Number(auditRowData?.prescription_id) || 0"
|
||||
audit
|
||||
:review-order-id="Number(auditTargetId)"
|
||||
@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="在此输入审核意见..." />
|
||||
<template #footer>
|
||||
<el-button @click="auditVisible = false">取消</el-button>
|
||||
<el-button type="primary" :loading="auditSubmitting" @click="submitAudit('approve')">同意通过</el-button>
|
||||
<el-button type="primary" :loading="auditSubmitting" :disabled="!canApproveAudit" @click="submitAudit('approve')">同意通过</el-button>
|
||||
<el-button type="danger" :loading="auditSubmitting" @click="submitAudit('reject')">驳回阻止</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
@@ -1778,6 +1788,7 @@
|
||||
v-model="prescriptionViewVisible"
|
||||
size="920px"
|
||||
:close-on-click-modal="false"
|
||||
@close="prescriptionViewVisible = false"
|
||||
>
|
||||
<template #header>
|
||||
<div class="flex items-center justify-between w-full pr-2 gap-3">
|
||||
@@ -1863,7 +1874,7 @@
|
||||
</div>
|
||||
|
||||
<EsignPrescriptionPanel
|
||||
v-if="prescriptionViewData && !prescriptionViewLoading"
|
||||
v-if="prescriptionViewVisible && prescriptionViewData && !prescriptionViewLoading"
|
||||
:key="prescriptionViewData.id"
|
||||
:prescription-id="Number(prescriptionViewData.id)"
|
||||
:initial-state="prescriptionViewData.esign"
|
||||
@@ -2138,7 +2149,8 @@ import {
|
||||
} from '@/api/tcm'
|
||||
import PrescriptionSlip from '@/components/prescription-slip/index.vue'
|
||||
import EsignPrescriptionPanel from '@/components/EsignPrescriptionPanel.vue'
|
||||
import { downloadPrescriptionPdfIfRequired, requiresOriginalEsignPdf } from '@/utils/prescription-esign'
|
||||
import type { PrescriptionEsignStatus } from '@/api/tcm'
|
||||
import { canApprovePrescriptionEsign, downloadPrescriptionPdfIfRequired, requiresOriginalEsignPdf } from '@/utils/prescription-esign'
|
||||
import html2canvas from 'html2canvas'
|
||||
import { jsPDF } from 'jspdf'
|
||||
import { getDictData } from '@/api/app'
|
||||
@@ -3705,20 +3717,29 @@ const auditTargetId = ref(0)
|
||||
const auditRowData = ref<any>(null)
|
||||
const auditRemark = ref('')
|
||||
const auditSubmitting = ref(false)
|
||||
const auditEsign = ref<PrescriptionEsignStatus | null>(null)
|
||||
const auditReview = ref<import('@/api/tcm').PrescriptionEsignReviewStatus | null>(null)
|
||||
const canApproveAudit = computed(() => auditKind.value === 'payment' || (
|
||||
canApprovePrescriptionEsign(auditEsign.value) && auditReview.value?.can_approve === true
|
||||
))
|
||||
|
||||
const auditTitle = computed(() =>
|
||||
auditKind.value === 'prescription' ? '处方业务审核' : '关联支付单审核'
|
||||
)
|
||||
|
||||
function openAudit(row: { id: number }, kind: 'prescription' | 'payment') {
|
||||
function openAudit(row: Record<string, any>, kind: 'prescription' | 'payment') {
|
||||
if (auditSubmitting.value) return
|
||||
auditKind.value = kind
|
||||
auditTargetId.value = row.id
|
||||
auditTargetId.value = Number(row.id)
|
||||
auditRowData.value = row
|
||||
auditEsign.value = null
|
||||
auditReview.value = null
|
||||
auditRemark.value = ''
|
||||
auditVisible.value = true
|
||||
}
|
||||
|
||||
async function submitAudit(action: 'approve' | 'reject') {
|
||||
if (auditSubmitting.value || (action === 'approve' && !canApproveAudit.value)) return
|
||||
if (action === 'reject' && !auditRemark.value.trim()) {
|
||||
feedback.msgError('驳回或阻止时必须填写明确的审核意见')
|
||||
return
|
||||
@@ -3939,6 +3960,8 @@ onMounted(async () => {
|
||||
applyRouteQueryToPrescriptionOrderList()
|
||||
await nextTick()
|
||||
getLists()
|
||||
const reviewOrderId = Number(route.query.review_order)
|
||||
if (Number.isSafeInteger(reviewOrderId) && reviewOrderId > 0) await openDetail(reviewOrderId)
|
||||
})
|
||||
|
||||
// ─── 快捷填写快递单号 ────────────────────────────────────────────
|
||||
|
||||
@@ -1865,11 +1865,21 @@
|
||||
</div>
|
||||
</template>
|
||||
</el-alert>
|
||||
<EsignPrescriptionPanel
|
||||
v-if="auditVisible && auditKind === 'prescription'"
|
||||
:key="auditTargetId"
|
||||
:prescription-id="Number(auditRowData?.prescription_id) || 0"
|
||||
audit
|
||||
:review-order-id="Number(auditTargetId)"
|
||||
@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="在此输入审核意见..." />
|
||||
<template #footer>
|
||||
<el-button @click="auditVisible = false">取消</el-button>
|
||||
<el-button type="primary" :loading="auditSubmitting" @click="submitAudit('approve')">同意通过</el-button>
|
||||
<el-button type="primary" :loading="auditSubmitting" :disabled="!canApproveAudit" @click="submitAudit('approve')">同意通过</el-button>
|
||||
<el-button type="danger" :loading="auditSubmitting" @click="submitAudit('reject')">驳回阻止</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
@@ -2378,6 +2388,7 @@
|
||||
direction="btt"
|
||||
class="po-h5-drawer"
|
||||
:close-on-click-modal="false"
|
||||
@close="prescriptionViewVisible = false"
|
||||
>
|
||||
<template #header>
|
||||
<div class="flex items-center justify-between w-full pr-2 gap-3">
|
||||
@@ -2463,7 +2474,7 @@
|
||||
</div>
|
||||
|
||||
<EsignPrescriptionPanel
|
||||
v-if="prescriptionViewData && !prescriptionViewLoading"
|
||||
v-if="prescriptionViewVisible && prescriptionViewData && !prescriptionViewLoading"
|
||||
:key="prescriptionViewData.id"
|
||||
:prescription-id="Number(prescriptionViewData.id)"
|
||||
:initial-state="prescriptionViewData.esign"
|
||||
@@ -2642,6 +2653,7 @@
|
||||
|
||||
<script lang="ts" setup name="prescriptionOrderListH5">
|
||||
import { computed, onMounted, reactive, ref, nextTick, watch, defineAsyncComponent } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
import {
|
||||
Refresh,
|
||||
Loading,
|
||||
@@ -2701,7 +2713,8 @@ import {
|
||||
} from './components/prescription-order-utils'
|
||||
import PrescriptionSlip from '@/components/prescription-slip/index.vue'
|
||||
import EsignPrescriptionPanel from '@/components/EsignPrescriptionPanel.vue'
|
||||
import { downloadPrescriptionPdfIfRequired, requiresOriginalEsignPdf } from '@/utils/prescription-esign'
|
||||
import type { PrescriptionEsignStatus } from '@/api/tcm'
|
||||
import { canApprovePrescriptionEsign, downloadPrescriptionPdfIfRequired, requiresOriginalEsignPdf } from '@/utils/prescription-esign'
|
||||
import html2canvas from 'html2canvas'
|
||||
import { jsPDF } from 'jspdf'
|
||||
import { getDictData } from '@/api/app'
|
||||
@@ -4665,25 +4678,35 @@ async function submitEdit() {
|
||||
}
|
||||
|
||||
const auditVisible = ref(false)
|
||||
const route = useRoute()
|
||||
const auditKind = ref<'prescription' | 'payment'>('prescription')
|
||||
const auditTargetId = ref(0)
|
||||
const auditRowData = ref<any>(null)
|
||||
const auditRemark = ref('')
|
||||
const auditSubmitting = ref(false)
|
||||
const auditEsign = ref<PrescriptionEsignStatus | null>(null)
|
||||
const auditReview = ref<import('@/api/tcm').PrescriptionEsignReviewStatus | null>(null)
|
||||
const canApproveAudit = computed(() => auditKind.value === 'payment' || (
|
||||
canApprovePrescriptionEsign(auditEsign.value) && auditReview.value?.can_approve === true
|
||||
))
|
||||
|
||||
const auditTitle = computed(() =>
|
||||
auditKind.value === 'prescription' ? '处方业务审核' : '关联支付单审核'
|
||||
)
|
||||
|
||||
function openAudit(row: { id: number }, kind: 'prescription' | 'payment') {
|
||||
function openAudit(row: Record<string, any>, kind: 'prescription' | 'payment') {
|
||||
if (auditSubmitting.value) return
|
||||
auditKind.value = kind
|
||||
auditTargetId.value = row.id
|
||||
auditTargetId.value = Number(row.id)
|
||||
auditRowData.value = row
|
||||
auditEsign.value = null
|
||||
auditReview.value = null
|
||||
auditRemark.value = ''
|
||||
auditVisible.value = true
|
||||
}
|
||||
|
||||
async function submitAudit(action: 'approve' | 'reject') {
|
||||
if (auditSubmitting.value || (action === 'approve' && !canApproveAudit.value)) return
|
||||
if (action === 'reject' && !auditRemark.value.trim()) {
|
||||
feedback.msgError('驳回或阻止时必须填写明确的审核意见')
|
||||
return
|
||||
@@ -4864,6 +4887,8 @@ onMounted(async () => {
|
||||
await loadServicePackageOptions()
|
||||
await loadDoctorAssistantOptions()
|
||||
getLists()
|
||||
const reviewOrderId = Number(route.query.review_order)
|
||||
if (Number.isSafeInteger(reviewOrderId) && reviewOrderId > 0) await openDetail(reviewOrderId)
|
||||
})
|
||||
|
||||
// ─── 快捷填写快递单号 ────────────────────────────────────────────
|
||||
|
||||
@@ -32,6 +32,16 @@
|
||||
</prescription-order-detail-drawer>
|
||||
|
||||
<el-dialog v-model="auditVisible" :title="auditTitle" width="480px" append-to-body destroy-on-close>
|
||||
<EsignPrescriptionPanel
|
||||
v-if="auditVisible && auditKind === 'prescription'"
|
||||
:key="actionRow.id"
|
||||
:prescription-id="Number(actionRow.prescription_id) || 0"
|
||||
audit
|
||||
:review-order-id="Number(actionRow.id)"
|
||||
@review-change="auditReview = $event"
|
||||
class="mb-3"
|
||||
@status-change="auditEsign = $event"
|
||||
/>
|
||||
<el-alert
|
||||
title="通过时审核意见可不填;驳回时必须填写明确原因。"
|
||||
type="warning"
|
||||
@@ -49,7 +59,7 @@
|
||||
/>
|
||||
<template #footer>
|
||||
<el-button @click="auditVisible = false">取消</el-button>
|
||||
<el-button type="primary" :loading="submitting" @click="submitAudit('approve')">同意通过</el-button>
|
||||
<el-button type="primary" :loading="submitting" :disabled="!canApproveAudit" @click="submitAudit('approve')">同意通过</el-button>
|
||||
<el-button type="danger" :loading="submitting" @click="submitAudit('reject')">驳回</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
@@ -243,6 +253,9 @@ import { computed, reactive, ref } from 'vue'
|
||||
import { ArrowDown } from '@element-plus/icons-vue'
|
||||
import { ElMessageBox } from 'element-plus'
|
||||
import feedback from '@/utils/feedback'
|
||||
import EsignPrescriptionPanel from '@/components/EsignPrescriptionPanel.vue'
|
||||
import type { PrescriptionEsignStatus } from '@/api/tcm'
|
||||
import { canApprovePrescriptionEsign } from '@/utils/prescription-esign'
|
||||
import PrescriptionOrderDetailDrawer from '@/views/consumer/prescription/components/PrescriptionOrderDetailDrawer.vue'
|
||||
import {
|
||||
myPatientOrderAddPayOrder,
|
||||
@@ -299,6 +312,11 @@ const completeOptions = [
|
||||
const auditVisible = ref(false)
|
||||
const auditKind = ref<'prescription' | 'payment'>('prescription')
|
||||
const auditRemark = ref('')
|
||||
const auditEsign = ref<PrescriptionEsignStatus | null>(null)
|
||||
const auditReview = ref<import('@/api/tcm').PrescriptionEsignReviewStatus | null>(null)
|
||||
const canApproveAudit = computed(() => auditKind.value === 'payment' || (
|
||||
canApprovePrescriptionEsign(auditEsign.value) && auditReview.value?.can_approve === true
|
||||
))
|
||||
const auditTitle = computed(() => auditKind.value === 'prescription' ? '处方业务审核' : '关联支付单审核')
|
||||
|
||||
const trackVisible = ref(false)
|
||||
@@ -387,6 +405,7 @@ async function openEdit(row: Record<string, any>) {
|
||||
}
|
||||
|
||||
function openAction(row: Record<string, any>, action: MyPatientOrderAction) {
|
||||
if (submitting.value && (action === 'audit_prescription' || action === 'audit_payment')) return
|
||||
actionRow.value = row
|
||||
switch (action) {
|
||||
case 'edit':
|
||||
@@ -395,6 +414,8 @@ function openAction(row: Record<string, any>, action: MyPatientOrderAction) {
|
||||
case 'audit_prescription':
|
||||
case 'audit_payment':
|
||||
auditKind.value = action === 'audit_prescription' ? 'prescription' : 'payment'
|
||||
auditEsign.value = null
|
||||
auditReview.value = null
|
||||
auditRemark.value = ''
|
||||
auditVisible.value = true
|
||||
break
|
||||
@@ -450,6 +471,7 @@ async function changed(message: string) {
|
||||
}
|
||||
|
||||
async function submitAudit(action: 'approve' | 'reject') {
|
||||
if (submitting.value || (action === 'approve' && !canApproveAudit.value)) return
|
||||
if (action === 'reject' && !auditRemark.value.trim()) {
|
||||
feedback.msgError('驳回时必须填写审核意见')
|
||||
return
|
||||
|
||||
@@ -0,0 +1,353 @@
|
||||
const assert = require('node:assert/strict')
|
||||
const fs = require('node:fs')
|
||||
const path = require('node:path')
|
||||
const test = require('node:test')
|
||||
const ts = require('typescript')
|
||||
const vue = require('vue')
|
||||
const { parse, compileScript, compileTemplate } = require('@vue/compiler-sfc')
|
||||
|
||||
const dialogFile = 'components/EsignDoctorDialog.vue'
|
||||
const menuFile = 'layout/default/components/header/user-drop-down.vue'
|
||||
const authUrl = 'https://smlt.esign.cn/verify?flow=synthetic'
|
||||
const currentTime = Date.parse('2026-11-19T08:00:00Z')
|
||||
const status = (changes = {}) => ({ enabled: true, status: 'unbound', cert_expires_at: 0, ...changes })
|
||||
const authenticating = (changes = {}) => status({ status: 'authenticating', auth_url: authUrl, ...changes })
|
||||
const grant = (changes = {}) => status({
|
||||
status: 'ready',
|
||||
cert_expires_at: currentTime / 1000 + 86400,
|
||||
quicksign_enabled: true,
|
||||
quicksign_expires_at: currentTime / 1000 + 600,
|
||||
quicksign_remaining_times: 5,
|
||||
...changes
|
||||
})
|
||||
|
||||
function source(filename) {
|
||||
return fs.readFileSync(path.join(__dirname, '../src', filename), 'utf8')
|
||||
}
|
||||
|
||||
function compile(filename) {
|
||||
const { descriptor, errors } = parse(source(filename), { filename })
|
||||
assert.deepEqual(errors, [])
|
||||
const script = compileScript(descriptor, { id: filename })
|
||||
const template = compileTemplate({
|
||||
source: descriptor.template.content, filename, id: filename,
|
||||
compilerOptions: { bindingMetadata: script.bindings }
|
||||
})
|
||||
assert.deepEqual(template.errors, [])
|
||||
return { script: script.content, template: descriptor.template.content }
|
||||
}
|
||||
|
||||
function load(code, imports, globals = {}) {
|
||||
const compiled = ts.transpileModule(code, {
|
||||
compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS }
|
||||
}).outputText
|
||||
const exports = {}
|
||||
new Function('require', 'exports', ...Object.keys(globals), compiled)((id) => {
|
||||
assert.ok(Object.hasOwn(imports, id), `Unexpected import ${id}`)
|
||||
return imports[id]
|
||||
}, exports, ...Object.values(globals))
|
||||
return exports
|
||||
}
|
||||
|
||||
const dialogScript = compile(dialogFile)
|
||||
const menuScript = compile(menuFile)
|
||||
const urlUtil = load(source('utils/prescription-esign.ts'), { '@/api/tcm': {} })
|
||||
|
||||
const flush = () => new Promise((resolve) => setImmediate(resolve))
|
||||
|
||||
function createDialog({ read = () => status(), start = () => authenticating(), complete = () => grant() } = {}) {
|
||||
const calls = []
|
||||
const mounted = []
|
||||
const unmounted = []
|
||||
const timers = new Map()
|
||||
const document = new EventTarget()
|
||||
document.visibilityState = 'visible'
|
||||
let time = currentTime
|
||||
let timerId = 0
|
||||
const component = load(dialogScript.script, {
|
||||
vue: { ...vue, onMounted: (fn) => mounted.push(fn), onBeforeUnmount: (fn) => unmounted.push(fn) },
|
||||
'@/api/tcm': {
|
||||
prescriptionEsignDoctorStatus: async (signal) => {
|
||||
calls.push(['read', signal])
|
||||
return read(signal)
|
||||
},
|
||||
prescriptionEsignDoctorStart: async (payload) => {
|
||||
calls.push(['start', payload])
|
||||
return start(payload)
|
||||
},
|
||||
prescriptionEsignDoctorComplete: async (payload) => {
|
||||
calls.push(['complete', payload])
|
||||
return complete(payload)
|
||||
}
|
||||
},
|
||||
'@/utils/prescription-esign': urlUtil
|
||||
}, {
|
||||
document,
|
||||
Date: { now: () => time },
|
||||
setTimeout(callback, delay) {
|
||||
timers.set(++timerId, { callback, due: time + delay })
|
||||
return timerId
|
||||
},
|
||||
clearTimeout(id) { timers.delete(id) }
|
||||
}).default
|
||||
const model = component.setup({ serverTimeOffsetMs: 0 }, { expose() {}, emit() {} })
|
||||
mounted.forEach((fn) => fn())
|
||||
return {
|
||||
...model,
|
||||
calls,
|
||||
writeCalls: () => calls.filter(([kind]) => kind !== 'read'),
|
||||
async advance(ms) {
|
||||
const until = time + ms
|
||||
while (timers.size) {
|
||||
const queued = [...timers.entries()].sort((a, b) => a[1].due - b[1].due)[0]
|
||||
const [id, { callback, due }] = queued
|
||||
if (due > until) break
|
||||
timers.delete(id)
|
||||
time = due
|
||||
callback()
|
||||
await flush()
|
||||
}
|
||||
time = until
|
||||
},
|
||||
visibility(value) {
|
||||
document.visibilityState = value
|
||||
document.dispatchEvent(new Event('visibilitychange'))
|
||||
},
|
||||
unmount: () => unmounted.forEach((fn) => fn())
|
||||
}
|
||||
}
|
||||
|
||||
test('account menu requires a signed-in doctor with a prescription write grant', async () => {
|
||||
const store = vue.reactive({ token: 'synthetic', userInfo: { id: 21, role_ids: [2], root: 1 }, perms: ['*'] })
|
||||
let mounted
|
||||
const component = load(menuScript.script, {
|
||||
vue: { ...vue, onMounted: (handler) => { mounted = handler } },
|
||||
'vue-router': { useRoute: () => ({ fullPath: '/doctor' }) },
|
||||
'@/api/tcm': { prescriptionEsignConfig: async () => ({ enabled: true, review_enabled: true, verification_method: 'quick' }) },
|
||||
'@/api/setting/system': {},
|
||||
'@/components/EsignDoctorDialog.vue': {},
|
||||
'@/stores/modules/user': { default: () => store },
|
||||
'@/utils/feedback': {},
|
||||
'@/utils/perm': { hasPermission: ([perm]) => store.perms.includes(perm) }
|
||||
}).default
|
||||
const scope = vue.effectScope()
|
||||
const menu = scope.run(() => component.setup({}, { expose() {} }))
|
||||
await mounted()
|
||||
await menu.handleCommand('doctor-esign')
|
||||
assert.equal(menu.doctorEsignOpen.value, false)
|
||||
|
||||
store.userInfo = { id: 22, role_ids: [1], root: 0 }
|
||||
store.perms = ['tcm.prescription/audit']
|
||||
await menu.handleCommand('doctor-esign')
|
||||
assert.equal(menu.doctorEsignOpen.value, false)
|
||||
await menu.handleCommand('review-esign')
|
||||
assert.equal(menu.reviewEsignOpen.value, true)
|
||||
store.perms = ['cf.prescription/edit']
|
||||
assert.equal(menu.reviewEsignOpen.value, false)
|
||||
await menu.handleCommand('doctor-esign')
|
||||
assert.equal(menu.doctorEsignOpen.value, true)
|
||||
store.userInfo.id = 23
|
||||
assert.equal(menu.doctorEsignOpen.value, false)
|
||||
store.token = ''
|
||||
await menu.handleCommand('doctor-esign')
|
||||
assert.equal(menu.doctorEsignOpen.value, false)
|
||||
scope.stop()
|
||||
})
|
||||
|
||||
test('opening a pending enrollment performs a GET and requires an explicit resume and completion', async () => {
|
||||
let result = authenticating()
|
||||
const settings = createDialog({ read: () => result, complete: () => status({ status: 'ready' }) })
|
||||
await flush()
|
||||
assert.equal(settings.canResume.value, true)
|
||||
assert.equal(settings.frameUrl.value, '')
|
||||
assert.deepEqual(settings.writeCalls(), [])
|
||||
await settings.advance(5000)
|
||||
assert.equal(settings.calls.length, 1)
|
||||
|
||||
settings.openAuthentication()
|
||||
assert.equal(settings.frameUrl.value, authUrl)
|
||||
result = status({ status: 'binding_required' })
|
||||
await settings.advance(5000)
|
||||
assert.equal(settings.frameUrl.value, '')
|
||||
assert.equal(settings.canComplete.value, true)
|
||||
assert.equal(settings.needsIdentityNumber.value, false)
|
||||
assert.deepEqual(settings.writeCalls(), [])
|
||||
await settings.complete()
|
||||
assert.deepEqual(settings.writeCalls(), [['complete', {}]])
|
||||
assert.equal(settings.canComplete.value, false)
|
||||
settings.unmount()
|
||||
})
|
||||
|
||||
test('certificate renewal uses the explicitly entered mobile and clears it after starting', async () => {
|
||||
const settings = createDialog({ read: () => status({ status: 'renewal_required' }) })
|
||||
await flush()
|
||||
assert.equal(settings.startLabel.value, '开始续期认证')
|
||||
settings.mobile.value = '123'
|
||||
await settings.start()
|
||||
assert.deepEqual(settings.writeCalls(), [])
|
||||
assert.equal(settings.mobile.value, '')
|
||||
settings.mobile.value = '13800138000'
|
||||
await settings.start()
|
||||
assert.deepEqual(settings.writeCalls(), [['start', { mobile: '13800138000' }]])
|
||||
assert.equal(settings.frameUrl.value, authUrl)
|
||||
assert.equal(settings.mobile.value, '')
|
||||
settings.unmount()
|
||||
})
|
||||
|
||||
test('supplemental document is masked, short-lived and submitted only once after an explicit click', async () => {
|
||||
let finish
|
||||
const settings = createDialog({
|
||||
read: () => status({ status: 'binding_required', identity_details_required: true, identity_number: 'ignored' }),
|
||||
complete: () => new Promise((resolve) => { finish = resolve })
|
||||
})
|
||||
await flush()
|
||||
assert.match(dialogScript.template, /v-model="identityNumber"[\s\S]*?type="password"[\s\S]*?autocomplete="off"/)
|
||||
assert.equal(settings.needsIdentityNumber.value, true)
|
||||
assert.equal(settings.state.value.identity_number, undefined)
|
||||
settings.identityNumber.value = '123'
|
||||
await settings.complete()
|
||||
assert.equal(settings.identityNumber.value, '')
|
||||
assert.deepEqual(settings.writeCalls(), [])
|
||||
|
||||
settings.identityNumber.value = '11010519491231002x'
|
||||
const completion = settings.complete()
|
||||
await settings.complete()
|
||||
assert.equal(settings.identityNumber.value, '')
|
||||
assert.deepEqual(settings.writeCalls(), [['complete', { identity_number: '11010519491231002X' }]])
|
||||
settings.dismiss()
|
||||
finish(grant())
|
||||
await completion
|
||||
assert.equal(settings.state.value, null)
|
||||
settings.unmount()
|
||||
})
|
||||
|
||||
test('quick authorization reuses the bound identity and exposes its validity and remaining count', async () => {
|
||||
let result = grant({ quicksign_expires_at: 0, quicksign_remaining_times: 0, quicksign_unavailable_reason: 'exhausted' })
|
||||
const quickFields = { quicksign_enabled: true, quicksign_authorizing: true }
|
||||
const settings = createDialog({
|
||||
read: () => result,
|
||||
start: () => authenticating(quickFields),
|
||||
complete: () => grant()
|
||||
})
|
||||
await flush()
|
||||
assert.equal(settings.needsMobile.value, false)
|
||||
assert.equal(settings.startLabel.value, '授权快捷签')
|
||||
assert.match(settings.guidance.value, /次数已用完/)
|
||||
await settings.start()
|
||||
assert.equal(settings.needsMobile.value, false)
|
||||
assert.equal(settings.frameUrl.value, authUrl)
|
||||
assert.deepEqual(settings.writeCalls(), [['start', {}]])
|
||||
|
||||
result = status({ ...quickFields, status: 'binding_required' })
|
||||
await settings.advance(5000)
|
||||
assert.deepEqual(settings.writeCalls(), [['start', {}]])
|
||||
assert.equal(settings.needsIdentityNumber.value, false)
|
||||
await settings.complete()
|
||||
assert.deepEqual(settings.writeCalls(), [['start', {}], ['complete', {}]])
|
||||
assert.equal(settings.grantActive.value, true)
|
||||
assert.equal(settings.state.value.quicksign_remaining_times, 5)
|
||||
assert.match(settings.formatExpiry(settings.state.value.quicksign_expires_at), /16:10(北京时间)/)
|
||||
await settings.start()
|
||||
assert.equal(settings.writeCalls().length, 2)
|
||||
await settings.advance(595000)
|
||||
assert.equal(settings.grantActive.value, false)
|
||||
assert.match(settings.guidance.value, /已过期/)
|
||||
assert.equal(settings.canAuthorizeQuick.value, true)
|
||||
settings.unmount()
|
||||
})
|
||||
|
||||
test('blocked or failed embedded pages can recover via a read without navigating the browser', async () => {
|
||||
let result = authenticating({ auth_url: 'https://smlt.esign.cn.example.test/verify' })
|
||||
const settings = createDialog({ read: () => result })
|
||||
await flush()
|
||||
assert.equal(settings.canResume.value, false)
|
||||
assert.equal(settings.state.value.auth_url, '')
|
||||
assert.match(settings.guidance.value, /验证链接不可用/)
|
||||
assert.match(dialogScript.template, /sandbox="allow-forms allow-scripts allow-same-origin"/)
|
||||
assert.match(dialogScript.template, /referrerpolicy="no-referrer"/)
|
||||
assert.doesNotMatch(source(dialogFile), /window\.open|postMessage|allow-popups|allow-top-navigation|@load|contentWindow/)
|
||||
settings.openAuthentication()
|
||||
assert.equal(settings.frameUrl.value, '')
|
||||
result = authenticating()
|
||||
await settings.refresh()
|
||||
settings.openAuthentication()
|
||||
settings.authenticationUnavailable()
|
||||
assert.equal(settings.frameUrl.value, '')
|
||||
await settings.advance(5000)
|
||||
assert.equal(settings.calls.length, 2)
|
||||
assert.deepEqual(settings.writeCalls(), [])
|
||||
settings.unmount()
|
||||
})
|
||||
|
||||
test('hidden documents abort single-flight polling and discard a late ready result', async () => {
|
||||
let finish
|
||||
let readCount = 0
|
||||
const settings = createDialog({ read: () => {
|
||||
if (++readCount === 2) return new Promise((resolve) => { finish = resolve })
|
||||
return authenticating()
|
||||
} })
|
||||
await flush()
|
||||
settings.openAuthentication()
|
||||
await settings.advance(30000)
|
||||
assert.equal(readCount, 2)
|
||||
settings.visibility('hidden')
|
||||
assert.equal(settings.calls[1][1].aborted, true)
|
||||
assert.equal(settings.frameUrl.value, '')
|
||||
finish(status({ status: 'binding_required', identity_details_required: true }))
|
||||
await flush()
|
||||
assert.equal(settings.canComplete.value, false)
|
||||
settings.visibility('visible')
|
||||
await flush()
|
||||
assert.equal(readCount, 3)
|
||||
assert.equal(settings.canResume.value, true)
|
||||
assert.equal(settings.frameUrl.value, '')
|
||||
assert.deepEqual(settings.writeCalls(), [])
|
||||
settings.unmount()
|
||||
})
|
||||
|
||||
test('the ten-minute frame deadline aborts a status request and requires an explicit resume', async () => {
|
||||
let readCount = 0
|
||||
let finish
|
||||
const settings = createDialog({ read: () => {
|
||||
if (++readCount > 1) return new Promise((resolve) => { finish = resolve })
|
||||
return authenticating()
|
||||
} })
|
||||
await flush()
|
||||
settings.openAuthentication()
|
||||
await settings.advance(600000)
|
||||
assert.equal(settings.frameUrl.value, '')
|
||||
assert.equal(settings.calls[1][1].aborted, true)
|
||||
assert.match(settings.error.value, /自动检查已结束/)
|
||||
finish(status({ status: 'binding_required' }))
|
||||
await flush()
|
||||
assert.equal(settings.canComplete.value, false)
|
||||
assert.equal(settings.canResume.value, true)
|
||||
assert.deepEqual(settings.writeCalls(), [])
|
||||
settings.unmount()
|
||||
})
|
||||
|
||||
test('failed or inconsistent results require recovery from a fresh GET and do not disclose request data', async () => {
|
||||
let result = status({ status: 'binding_required', identity_details_required: true })
|
||||
const settings = createDialog({
|
||||
read: () => result,
|
||||
complete: () => { throw new Error('synthetic identity data 11010519491231002X') }
|
||||
})
|
||||
await flush()
|
||||
settings.identityNumber.value = '11010519491231002X'
|
||||
await settings.complete()
|
||||
assert.equal(settings.state.value, null)
|
||||
assert.equal(settings.identityNumber.value, '')
|
||||
assert.doesNotMatch(settings.error.value, /110105/)
|
||||
await settings.complete()
|
||||
assert.equal(settings.writeCalls().length, 1)
|
||||
|
||||
result = status({ status: 'binding_required', quicksign_authorizing: true, quicksign_enabled: true, identity_details_required: true })
|
||||
await settings.refresh()
|
||||
assert.equal(settings.canComplete.value, false)
|
||||
assert.equal(settings.needsIdentityNumber.value, false)
|
||||
result = status({ enabled: false })
|
||||
await settings.refresh()
|
||||
assert.equal(settings.needsMobile.value, false)
|
||||
assert.match(settings.guidance.value, /未启用/)
|
||||
settings.unmount()
|
||||
})
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
@@ -7,5 +7,5 @@ __version__ = "1.5.4"
|
||||
|
||||
# 调试模式开启时,登录页显示“演示模式”和“服务器设置”。
|
||||
# 正式发布请保持 False;此时程序只使用下面配置的线上域名。
|
||||
DEBUG_MODE = False
|
||||
DEBUG_MODE = True
|
||||
ONLINE_API_BASE_URL = "https://admin.zhenyangtang.com.cn"
|
||||
|
||||
@@ -6,6 +6,7 @@ import base64
|
||||
import binascii
|
||||
import hashlib
|
||||
import hmac
|
||||
import re
|
||||
from collections.abc import Mapping
|
||||
from typing import Any
|
||||
from urllib.parse import urlsplit
|
||||
@@ -23,12 +24,18 @@ ESIGN_LABELS = {
|
||||
"legacy": "历史手写签名",
|
||||
}
|
||||
|
||||
_DOCTOR_IDENTITY_STATES = {
|
||||
"unbound", "needs_mobile", "authenticating", "binding_required", "ready", "renewal_required",
|
||||
}
|
||||
_QUICKSIGN_UNAVAILABLE_REASONS = ("missing", "expired", "exhausted", "invalid")
|
||||
|
||||
|
||||
def esign_config(value: Any) -> dict[str, Any]:
|
||||
if (
|
||||
not isinstance(value, Mapping)
|
||||
or not isinstance(value.get("enabled"), bool)
|
||||
or value.get("environment") not in {"sandbox", "production"}
|
||||
or ("verification_method" in value and not isinstance(value["verification_method"], str))
|
||||
):
|
||||
raise ApiProtocolError("电子签署配置格式不正确")
|
||||
return dict(value)
|
||||
@@ -36,13 +43,129 @@ def esign_config(value: Any) -> dict[str, Any]:
|
||||
|
||||
def esign_status(value: Any) -> dict[str, Any]:
|
||||
result = esign_config(value)
|
||||
if result.get("status") not in ESIGN_LABELS or any(
|
||||
not isinstance(result.get(key), bool) for key in ("required", "can_sign", "can_download")
|
||||
if (
|
||||
result.get("status") not in ESIGN_LABELS
|
||||
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 (
|
||||
"can_resume_identity", "can_retry_verify", "doctor_identity_required", "sms_sent",
|
||||
"signing_authorization_required",
|
||||
))
|
||||
or ("signing_authorization_reason" in result
|
||||
and result["signing_authorization_reason"] not in _QUICKSIGN_UNAVAILABLE_REASONS)
|
||||
):
|
||||
raise ApiProtocolError("电子签署状态格式不正确")
|
||||
return result
|
||||
|
||||
|
||||
def esign_identity_status(value: Any) -> dict[str, Any]:
|
||||
"""Validate a read-only, server-authoritative identity readiness response."""
|
||||
result = esign_status(value)
|
||||
if result.get("identity_status") not in {"INIT", "ING", "SUCCESS", "FAIL", "EXPIRED", "UNAVAILABLE"} or not isinstance(result.get("can_complete"), bool):
|
||||
raise ApiProtocolError("核身查询结果格式不正确")
|
||||
details_required = result.get("identity_details_required", False)
|
||||
if not isinstance(details_required, bool):
|
||||
raise ApiProtocolError("证书身份补录状态格式不正确")
|
||||
method = result.get("verification_method")
|
||||
authorized = (
|
||||
result["identity_status"] == "SUCCESS"
|
||||
and ((result["status"] == "authenticating" and result.get("can_resume_identity", method != "quick") is True)
|
||||
or (result["status"] == "failed" and result.get("can_resume_identity") is True))
|
||||
and result["enabled"] and result["required"] and result["can_sign"]
|
||||
and result.get("doctor_identity_required") is not True
|
||||
and result.get("signing_authorization_required") is not True
|
||||
)
|
||||
if (result["can_complete"] and not authorized) or (
|
||||
details_required and (
|
||||
not authorized or result["can_complete"] or method in {"sms", "quick"}
|
||||
)
|
||||
):
|
||||
raise ApiProtocolError("核身查询结果与签署权限不一致")
|
||||
result["identity_details_required"] = details_required
|
||||
return result
|
||||
|
||||
|
||||
def esign_doctor_status(value: Any) -> dict[str, Any]:
|
||||
"""Validate independent enrollment and retain only display or workflow fields."""
|
||||
if not isinstance(value, Mapping):
|
||||
raise ApiProtocolError("医生签署身份状态格式不正确")
|
||||
enabled, status = value.get("enabled"), value.get("status")
|
||||
expiry = value.get("cert_expires_at", 0)
|
||||
details = value.get("identity_details_required", False)
|
||||
quick_enabled = value.get("quicksign_enabled", False)
|
||||
quick_expiry = value.get("quicksign_expires_at", 0)
|
||||
quick_authorizing = value.get("quicksign_authorizing", False)
|
||||
quick_remaining = value.get("quicksign_remaining_times", 0)
|
||||
quick_unavailable = value.get("quicksign_unavailable_reason", "")
|
||||
if (
|
||||
not isinstance(enabled, bool)
|
||||
or not isinstance(status, str) or status not in _DOCTOR_IDENTITY_STATES
|
||||
or type(expiry) is not int or not 0 <= expiry <= 253402300799
|
||||
or not isinstance(details, bool)
|
||||
or (details and (not enabled or status != "binding_required"))
|
||||
or not isinstance(quick_enabled, bool)
|
||||
or type(quick_expiry) is not int or not 0 <= quick_expiry <= 253402300799
|
||||
or not isinstance(quick_authorizing, bool)
|
||||
or type(quick_remaining) is not int or quick_remaining < 0
|
||||
or quick_unavailable not in ("", *_QUICKSIGN_UNAVAILABLE_REASONS)
|
||||
or (quick_authorizing and (
|
||||
not enabled or not quick_enabled or details or status not in {"authenticating", "binding_required"}
|
||||
))
|
||||
):
|
||||
raise ApiProtocolError("医生签署身份状态格式不正确")
|
||||
result = {"enabled": enabled, "status": status, "cert_expires_at": expiry,
|
||||
"identity_details_required": details, "quicksign_enabled": quick_enabled,
|
||||
"quicksign_expires_at": quick_expiry, "quicksign_authorizing": quick_authorizing}
|
||||
if "quicksign_remaining_times" in value:
|
||||
result["quicksign_remaining_times"] = quick_remaining
|
||||
if quick_unavailable:
|
||||
result["quicksign_unavailable_reason"] = quick_unavailable
|
||||
if enabled and status == "authenticating" and value.get("auth_url"):
|
||||
result["auth_url"] = authentication_url(value["auth_url"])
|
||||
return result
|
||||
|
||||
|
||||
def esign_doctor_mobile(value: Any) -> str:
|
||||
mobile = value.strip() if isinstance(value, str) else ""
|
||||
if not re.fullmatch(r"1[3-9][0-9]{9}", mobile):
|
||||
raise ValueError("请输入 11 位中国大陆手机号码。")
|
||||
return mobile
|
||||
|
||||
|
||||
def esign_sms_code(value: Any) -> str:
|
||||
code = value.strip() if isinstance(value, str) else ""
|
||||
if not re.fullmatch(r"[0-9]{6}", code):
|
||||
raise ValueError("请输入短信中的六位数字验证码。")
|
||||
return code
|
||||
|
||||
|
||||
def certificate_identity_number(value: Any) -> str:
|
||||
"""Validate only mainland ID shape; the server verifies the authenticated person."""
|
||||
if not isinstance(value, str):
|
||||
raise ValueError("请输入 15 或 18 位中国大陆居民身份证号码,18 位号码末位可以是 X。")
|
||||
number = value.strip().upper()
|
||||
if not re.fullmatch(r"[1-9](?:[0-9]{14}|[0-9]{16}[0-9X])", number):
|
||||
raise ValueError("请输入 15 或 18 位中国大陆居民身份证号码,18 位号码末位可以是 X。")
|
||||
return number
|
||||
|
||||
|
||||
def authentication_navigation_allowed(value: Any) -> bool:
|
||||
"""Restrict embedded documents to HTTPS on the provider's own domains."""
|
||||
url = str(value or "")
|
||||
try:
|
||||
parts = urlsplit(url)
|
||||
host = parts.hostname or ""
|
||||
return bool(
|
||||
parts.scheme == "https"
|
||||
and host.isascii() and "%" not in host
|
||||
and any(host.endswith("." + domain) for domain in ("esign.cn", "tsign.cn"))
|
||||
and not parts.username and not parts.password
|
||||
and (parts.port in (None, 443) or (host == "smlfront.esign.cn" and parts.port == 8890))
|
||||
and not any(ord(char) < 33 or char == "\\" for char in url)
|
||||
)
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
|
||||
def authentication_url(value: Any) -> str:
|
||||
"""Accept only an HTTPS link returned by the authenticated application server."""
|
||||
url = str(value or "").strip()
|
||||
|
||||
@@ -181,11 +181,13 @@ class ApiClient:
|
||||
*,
|
||||
headers: Mapping[str, str] | None = None,
|
||||
timeout: float | httpx.Timeout | None = None,
|
||||
max_retries: int | None = None,
|
||||
) -> Any:
|
||||
"""Issue a GET request and return the unwrapped envelope data."""
|
||||
|
||||
return self.request(
|
||||
"GET", endpoint, params=params, headers=headers, timeout=timeout
|
||||
"GET", endpoint, params=params, headers=headers, timeout=timeout,
|
||||
max_retries=max_retries,
|
||||
)
|
||||
|
||||
def post(
|
||||
@@ -497,6 +499,7 @@ class ApiClient:
|
||||
files: Mapping[str, Any] | None = None,
|
||||
headers: Mapping[str, str] | None = None,
|
||||
timeout: float | httpx.Timeout | None = None,
|
||||
max_retries: int | None = None,
|
||||
) -> Any:
|
||||
"""Issue one API request with structured transport/envelope errors."""
|
||||
|
||||
@@ -514,7 +517,10 @@ class ApiClient:
|
||||
headers,
|
||||
json_content_type=files is None and data is None,
|
||||
)
|
||||
attempts = self.max_retries + 1 if verb == "GET" else 1
|
||||
if max_retries is not None and max_retries < 0:
|
||||
raise ValueError("max_retries must be non-negative")
|
||||
retries = self.max_retries if max_retries is None else max_retries
|
||||
attempts = retries + 1 if verb == "GET" else 1
|
||||
response: httpx.Response | None = None
|
||||
request_timeout = self.timeout if timeout is None else timeout
|
||||
with self._borrow_client() as client:
|
||||
|
||||
@@ -102,6 +102,7 @@ DEMO_PERMISSIONS: tuple[str, ...] = (
|
||||
"wcf.prescription/delete",
|
||||
"tcm.prescription/lists",
|
||||
"tcm.prescription/detail",
|
||||
"tcm.prescription/void",
|
||||
"cf.prescription/add",
|
||||
"cf.prescription/read",
|
||||
"cf.prescription/edit",
|
||||
@@ -1295,7 +1296,10 @@ class DemoDoctorRepository:
|
||||
rows = [row for row in rows if row.create_time >= start_time]
|
||||
if end_time:
|
||||
rows = [row for row in rows if row.create_time <= end_time]
|
||||
return _page(rows, page_no, page_size)
|
||||
page = _page(rows, page_no, page_size)
|
||||
for result in page.items:
|
||||
self._add_prescription_actions(result)
|
||||
return page
|
||||
|
||||
def get_prescription(self, prescription_id: int) -> Prescription:
|
||||
"""Return one issued demo prescription by identifier."""
|
||||
@@ -1305,25 +1309,53 @@ class DemoDoctorRepository:
|
||||
if prescription.id == prescription_id:
|
||||
result = deepcopy(prescription)
|
||||
result.esign = self._disabled_prescription_esign()
|
||||
self._add_prescription_actions(result)
|
||||
return result
|
||||
raise RepositoryNotFoundError(f"prescription {prescription_id} not found")
|
||||
|
||||
@staticmethod
|
||||
def _add_prescription_actions(prescription: Prescription) -> None:
|
||||
prescription.raw["can_void"] = not prescription.void_status and not prescription.has_prescription_order
|
||||
prescription.raw["can_restore_rejected"] = (
|
||||
prescription.void_status == 1 and prescription.audit_status == 2
|
||||
)
|
||||
|
||||
def get_prescription_esign_config(self) -> dict[str, Any]:
|
||||
return {"enabled": False, "environment": "sandbox"}
|
||||
|
||||
def get_prescription_esign_status(self, prescription_id: int) -> dict[str, Any]:
|
||||
return self.get_prescription(prescription_id).esign
|
||||
|
||||
def get_prescription_esign_identity_status(self, prescription_id: int) -> dict[str, Any]:
|
||||
return {**self.get_prescription_esign_status(prescription_id),
|
||||
"identity_status": "UNAVAILABLE", "can_complete": False,
|
||||
"identity_details_required": False}
|
||||
|
||||
def get_esign_doctor_status(self) -> dict[str, Any]:
|
||||
return {"enabled": False, "status": "unbound", "cert_expires_at": 0}
|
||||
|
||||
def start_esign_doctor(self, mobile: str) -> dict[str, Any]:
|
||||
return self.get_esign_doctor_status()
|
||||
|
||||
def complete_esign_doctor(self, identity_number: str = "") -> dict[str, Any]:
|
||||
return self.get_esign_doctor_status()
|
||||
|
||||
def _disabled_prescription_esign(self) -> dict[str, Any]:
|
||||
return {**self.get_prescription_esign_config(), "required": False,
|
||||
"status": "legacy", "status_label": "历史手写签名",
|
||||
"can_sign": False, "can_download": False,
|
||||
"message": "演示模式未启用电子签署。"}
|
||||
|
||||
def start_prescription_esign(self, prescription_id: int) -> dict[str, Any]:
|
||||
def start_prescription_esign(self, prescription_id: int, *, restart_identity: bool = False) -> dict[str, Any]:
|
||||
return self.get_prescription_esign_status(prescription_id)
|
||||
|
||||
def complete_prescription_esign(self, prescription_id: int) -> dict[str, Any]:
|
||||
def verify_prescription_esign_willingness(self, prescription_id: int, auth_code: str) -> dict[str, Any]:
|
||||
return self.get_prescription_esign_identity_status(prescription_id)
|
||||
|
||||
def complete_prescription_esign(self, prescription_id: int, identity_number: str = "") -> dict[str, Any]:
|
||||
return self.get_prescription_esign_status(prescription_id)
|
||||
|
||||
def verify_prescription_esign(self, prescription_id: int) -> dict[str, Any]:
|
||||
return self.get_prescription_esign_status(prescription_id)
|
||||
|
||||
def download_prescription_esign(self, prescription_id: int) -> dict[str, Any]:
|
||||
@@ -1479,6 +1511,8 @@ class DemoDoctorRepository:
|
||||
|
||||
with self._lock:
|
||||
prescription = self._find_prescription(prescription_id)
|
||||
if prescription.void_status:
|
||||
raise ApiBusinessError("该处方已作废", code=0)
|
||||
if prescription.has_prescription_order:
|
||||
raise ApiBusinessError("已有业务订单,处方不可作废", code=0)
|
||||
prescription.void_status = 1
|
||||
@@ -1491,6 +1525,7 @@ class DemoDoctorRepository:
|
||||
"void_time": prescription.void_time,
|
||||
}
|
||||
)
|
||||
self._sync_prescription_flag(prescription.diagnosis_id)
|
||||
return {"id": prescription_id, "void_status": 1}
|
||||
|
||||
def list_prescriptions_by_diagnosis(self, diagnosis_id: int) -> list[Prescription]:
|
||||
@@ -1502,15 +1537,19 @@ class DemoDoctorRepository:
|
||||
)
|
||||
|
||||
def get_prescription_by_appointment(self, appointment_id: int) -> Prescription | None:
|
||||
"""Return only the prescription explicitly linked to this appointment."""
|
||||
"""Prefer the latest active prescription linked to this appointment."""
|
||||
|
||||
with self._lock:
|
||||
self._find_appointment(appointment_id)
|
||||
match = next(
|
||||
match = max(
|
||||
(row for row in self._prescriptions if row.appointment_id == appointment_id),
|
||||
None,
|
||||
key=lambda row: (not row.void_status, row.id),
|
||||
default=None,
|
||||
)
|
||||
return deepcopy(match)
|
||||
result = deepcopy(match)
|
||||
if result is not None:
|
||||
self._add_prescription_actions(result)
|
||||
return result
|
||||
|
||||
def list_prescription_orders(
|
||||
self, *, page_no: int = 1, page_size: int = 20, **filters: Any
|
||||
@@ -1534,6 +1573,8 @@ class DemoDoctorRepository:
|
||||
body = _body(payload, fields)
|
||||
with self._lock:
|
||||
prescription = self._find_prescription(int(body.get("prescription_id") or 0))
|
||||
if prescription.void_status:
|
||||
raise ApiBusinessError("已作废处方不可创建业务订单", code=0)
|
||||
order = {
|
||||
"id": self._next_order_id,
|
||||
"order_no": f"PO{self._today.strftime('%Y%m%d')}{self._next_order_id}",
|
||||
|
||||
@@ -17,6 +17,7 @@ from uuid import uuid4
|
||||
|
||||
from doctor_workstation.core.errors import (
|
||||
ApiBusinessError,
|
||||
ApiError,
|
||||
ApiHttpError,
|
||||
ApiProtocolError,
|
||||
ApiTransportError,
|
||||
@@ -256,11 +257,29 @@ class DoctorRepository(Protocol):
|
||||
def get_prescription_esign_status(self, prescription_id: int) -> dict[str, Any]:
|
||||
"""Query the authoritative signature state and current actor capabilities."""
|
||||
|
||||
def start_prescription_esign(self, prescription_id: int) -> dict[str, Any]:
|
||||
def get_prescription_esign_identity_status(self, prescription_id: int) -> dict[str, Any]:
|
||||
"""Read identity readiness without signing or retrying a timed-out query."""
|
||||
|
||||
def get_esign_doctor_status(self) -> dict[str, Any]:
|
||||
"""Read the signed-in doctor's enrollment without a prescription ID."""
|
||||
|
||||
def start_esign_doctor(self, mobile: str) -> dict[str, Any]:
|
||||
"""Start provider identity authentication for the signed-in doctor."""
|
||||
|
||||
def complete_esign_doctor(self, identity_number: str = "") -> dict[str, Any]:
|
||||
"""Complete independent enrollment without or with a one-time ID number."""
|
||||
|
||||
def start_prescription_esign(self, prescription_id: int, *, restart_identity: bool = False) -> dict[str, Any]:
|
||||
"""Start or resume the creator's identity authentication flow."""
|
||||
|
||||
def complete_prescription_esign(self, prescription_id: int) -> dict[str, Any]:
|
||||
"""Ask the server to verify authentication and perform signing."""
|
||||
def verify_prescription_esign_willingness(self, prescription_id: int, auth_code: str) -> dict[str, Any]:
|
||||
"""Verify the SMS code for one prescription without signing it."""
|
||||
|
||||
def complete_prescription_esign(self, prescription_id: int, identity_number: str = "") -> dict[str, Any]:
|
||||
"""Reverify authentication and sign, optionally binding one-time certificate details."""
|
||||
|
||||
def verify_prescription_esign(self, prescription_id: int) -> dict[str, Any]:
|
||||
"""Reverify the archived original without requesting a new signature."""
|
||||
|
||||
def download_prescription_esign(self, prescription_id: int) -> dict[str, Any]:
|
||||
"""Return the original signed PDF, filename and SHA-256."""
|
||||
@@ -1715,22 +1734,98 @@ class RemoteDoctorRepository:
|
||||
from ..core.esign import esign_config
|
||||
return esign_config(self.client.get("tcm.prescription/esignConfig"))
|
||||
|
||||
def _prescription_esign_request(self, action: str, prescription_id: int, *, mutation: bool = False) -> dict[str, Any]:
|
||||
def _prescription_esign_request(
|
||||
self, action: str, prescription_id: int, *, mutation: bool = False, **fields: Any,
|
||||
) -> dict[str, Any]:
|
||||
from ..core.esign import esign_status
|
||||
if prescription_id <= 0:
|
||||
raise ValueError("prescription id is required")
|
||||
endpoint = f"tcm.prescription/{action}"
|
||||
result = _client_request(self.client, "post" if mutation else "get", endpoint, {"id": prescription_id}, timeout=180.0 if mutation else 60.0)
|
||||
result = _client_request(self.client, "post" if mutation else "get", endpoint,
|
||||
{"id": prescription_id, **fields}, timeout=180.0 if mutation else 60.0)
|
||||
return esign_status(result)
|
||||
|
||||
def get_prescription_esign_status(self, prescription_id: int) -> dict[str, Any]:
|
||||
return self._prescription_esign_request("esignStatus", prescription_id)
|
||||
|
||||
def start_prescription_esign(self, prescription_id: int) -> dict[str, Any]:
|
||||
def get_prescription_esign_identity_status(self, prescription_id: int) -> dict[str, Any]:
|
||||
from ..core.esign import esign_identity_status
|
||||
if prescription_id <= 0:
|
||||
raise ValueError("prescription id is required")
|
||||
return esign_identity_status(self.client.get(
|
||||
"tcm.prescription/esignIdentityStatus", {"id": prescription_id},
|
||||
timeout=30.0, max_retries=0,
|
||||
))
|
||||
|
||||
def get_esign_doctor_status(self) -> dict[str, Any]:
|
||||
from ..core.esign import esign_doctor_status
|
||||
|
||||
return esign_doctor_status(self.client.get(
|
||||
"tcm.prescription/esignDoctorStatus", timeout=30.0, max_retries=0,
|
||||
))
|
||||
|
||||
def start_esign_doctor(self, mobile: str) -> dict[str, Any]:
|
||||
from ..core.esign import esign_doctor_mobile, esign_doctor_status
|
||||
|
||||
payload = {"mobile": esign_doctor_mobile(mobile)} if mobile else {}
|
||||
return esign_doctor_status(self._post_esign_proof(
|
||||
"esignDoctorStart", payload, "医生人脸认证启动状态待确认",
|
||||
))
|
||||
|
||||
def complete_esign_doctor(self, identity_number: str = "") -> dict[str, Any]:
|
||||
from ..core.esign import certificate_identity_number, esign_doctor_status
|
||||
|
||||
payload = {"identity_number": certificate_identity_number(identity_number)} if identity_number else {}
|
||||
return esign_doctor_status(self._post_esign_proof(
|
||||
"esignDoctorComplete", payload, "医生签署证书绑定状态待确认",
|
||||
))
|
||||
|
||||
def start_prescription_esign(self, prescription_id: int, *, restart_identity: bool = False) -> dict[str, Any]:
|
||||
if restart_identity:
|
||||
return self._prescription_esign_request("esignStart", prescription_id, mutation=True, restart_identity=True)
|
||||
return self._prescription_esign_request("esignStart", prescription_id, mutation=True)
|
||||
|
||||
def complete_prescription_esign(self, prescription_id: int) -> dict[str, Any]:
|
||||
return self._prescription_esign_request("esignComplete", prescription_id, mutation=True)
|
||||
def verify_prescription_esign_willingness(self, prescription_id: int, auth_code: str) -> dict[str, Any]:
|
||||
from ..core.esign import esign_identity_status, esign_sms_code
|
||||
|
||||
if prescription_id <= 0:
|
||||
raise ValueError("prescription id is required")
|
||||
result = esign_identity_status(self._post_esign_proof(
|
||||
"esignVerifyWillingness", {"id": prescription_id, "auth_code": esign_sms_code(auth_code)},
|
||||
"短信验证码校验状态待确认",
|
||||
))
|
||||
if result.get("verification_method") != "sms":
|
||||
raise ApiProtocolError("短信验证码校验结果格式不正确")
|
||||
return result
|
||||
|
||||
def _post_esign_proof(self, action: str, payload: dict[str, Any], failure: str) -> Any:
|
||||
try:
|
||||
return _client_request(self.client, "post", f"tcm.prescription/{action}", payload, timeout=60.0)
|
||||
except AuthenticationExpiredError:
|
||||
error: ApiError = AuthenticationExpiredError("登录状态已失效,请重新登录。")
|
||||
except ApiError:
|
||||
error = ApiBusinessError(failure)
|
||||
finally:
|
||||
payload.clear()
|
||||
# Do not forward provider responses that could echo an identifier or a code.
|
||||
raise error
|
||||
|
||||
def complete_prescription_esign(self, prescription_id: int, identity_number: str = "") -> dict[str, Any]:
|
||||
if identity_number == "":
|
||||
return self._prescription_esign_request("esignComplete", prescription_id, mutation=True)
|
||||
from ..core.esign import certificate_identity_number, esign_status
|
||||
if prescription_id <= 0:
|
||||
raise ValueError("prescription id is required")
|
||||
payload = {"id": prescription_id, "identity_number": certificate_identity_number(identity_number)}
|
||||
try:
|
||||
return esign_status(_client_request(
|
||||
self.client, "post", "tcm.prescription/esignComplete", payload, timeout=180.0,
|
||||
))
|
||||
finally:
|
||||
payload.clear()
|
||||
|
||||
def verify_prescription_esign(self, prescription_id: int) -> dict[str, Any]:
|
||||
return self._prescription_esign_request("esignComplete", prescription_id, mutation=True, verify_only=True)
|
||||
|
||||
def download_prescription_esign(self, prescription_id: int) -> dict[str, Any]:
|
||||
if prescription_id <= 0:
|
||||
|
||||
@@ -444,6 +444,8 @@ def prescription_action(record: Any, *, force_open: bool = False) -> tuple[str,
|
||||
if explicit_legacy is not None
|
||||
else audit in {0, 1, 2}
|
||||
)
|
||||
if has_current and voided == 1:
|
||||
return "重新开方", "reissue"
|
||||
if not has_current:
|
||||
return "开方", "open"
|
||||
if audit == 1 and voided != 1:
|
||||
@@ -451,6 +453,13 @@ def prescription_action(record: Any, *, force_open: bool = False) -> tuple[str,
|
||||
return "编辑处方", "edit"
|
||||
|
||||
|
||||
def can_void_prescription(record: Any) -> bool:
|
||||
_, mode = prescription_action(record)
|
||||
return mode in {"edit", "view"} and not _as_bool(
|
||||
first_value(record, "has_prescription_order", default=False)
|
||||
)
|
||||
|
||||
|
||||
def _prescription_action_label(record: Any, *, force_open: bool = False) -> str:
|
||||
return prescription_action(record, force_open=force_open)[0]
|
||||
|
||||
@@ -2100,6 +2109,11 @@ class DiagnosisTableHost(QFrame):
|
||||
command, item
|
||||
),
|
||||
)
|
||||
if self.action_policy.get("prescription", False) and can_void_prescription(record):
|
||||
_add_menu_action(
|
||||
menu, "作废处方", "close",
|
||||
lambda _checked=False, item=record: self.action_requested.emit("void_prescription", item),
|
||||
)
|
||||
if demoted_actions and self.action_policy.get("assign", False):
|
||||
menu.addSeparator()
|
||||
if self.action_policy.get("assign", False):
|
||||
|
||||
@@ -3509,11 +3509,20 @@ class DiagnosisDialog(QDialog):
|
||||
appointment, "doctor_name", default=first_value(diagnosis, "doctor_name")
|
||||
),
|
||||
}
|
||||
def save_new(payload: dict[str, Any]) -> Any:
|
||||
authoritative = {
|
||||
"diagnosis_id": diagnosis_id,
|
||||
"appointment_id": appointment_id,
|
||||
"case_record": seed["case_record"],
|
||||
}
|
||||
return invoke(self.repository, "create_prescription", prescription=payload | authoritative)
|
||||
|
||||
dialog = PrescriptionEditorDialog(
|
||||
self.repository,
|
||||
seed,
|
||||
mode="add",
|
||||
current_user=getattr(self.parentWidget(), "current_user", None),
|
||||
save_draft=save_new,
|
||||
parent=self,
|
||||
)
|
||||
dialog.diagnosis_requested.connect(self._open_current_diagnosis_detail)
|
||||
@@ -3521,16 +3530,16 @@ class DiagnosisDialog(QDialog):
|
||||
dialog.setStyleSheet(DIAGNOSIS_QSS)
|
||||
if dialog.exec() != QDialog.DialogCode.Accepted:
|
||||
return
|
||||
saved_draft = getattr(dialog, "saved_draft", None)
|
||||
if saved_draft is not None:
|
||||
self._media_generation += 1
|
||||
self._media_mutation_success(
|
||||
"处方已开具并提交审核。", "prescription", diagnosis_id, self._media_generation, saved_draft
|
||||
)
|
||||
return
|
||||
payload = dialog.payload()
|
||||
payload.update(
|
||||
{
|
||||
"diagnosis_id": diagnosis_id,
|
||||
"appointment_id": appointment_id,
|
||||
"case_record": seed["case_record"],
|
||||
}
|
||||
)
|
||||
self._run_media_mutation(
|
||||
lambda: invoke(self.repository, "create_prescription", prescription=payload),
|
||||
lambda: save_new(payload),
|
||||
"处方已开具并提交审核。",
|
||||
"prescription",
|
||||
)
|
||||
@@ -4149,11 +4158,16 @@ class DiagnosisDialog(QDialog):
|
||||
def _open_prescription_edit_dialog(self, prescription: Any, prescription_id: int) -> None:
|
||||
from .prescription import PrescriptionEditorDialog
|
||||
|
||||
def save_changes(payload: dict[str, Any]) -> Any:
|
||||
return invoke(self.repository, "update_prescription", prescription=prescription_id, changes=payload)
|
||||
|
||||
diagnosis_id = self._diagnosis_id
|
||||
dialog = PrescriptionEditorDialog(
|
||||
self.repository,
|
||||
prescription,
|
||||
mode="edit",
|
||||
current_user=getattr(self.parentWidget(), "current_user", None),
|
||||
save_draft=save_changes,
|
||||
parent=self,
|
||||
)
|
||||
dialog.diagnosis_requested.connect(self._open_current_diagnosis_detail)
|
||||
@@ -4161,14 +4175,16 @@ class DiagnosisDialog(QDialog):
|
||||
dialog.setStyleSheet(DIAGNOSIS_QSS)
|
||||
if dialog.exec() != QDialog.DialogCode.Accepted:
|
||||
return
|
||||
saved_draft = getattr(dialog, "saved_draft", None)
|
||||
if saved_draft is not None:
|
||||
self._media_generation += 1
|
||||
self._media_mutation_success(
|
||||
"处方已保存并重新进入待审核。", "prescription", diagnosis_id, self._media_generation, saved_draft
|
||||
)
|
||||
return
|
||||
payload = dialog.payload()
|
||||
self._run_media_mutation(
|
||||
lambda: invoke(
|
||||
self.repository,
|
||||
"update_prescription",
|
||||
prescription=prescription_id,
|
||||
changes=payload,
|
||||
),
|
||||
lambda: save_changes(payload),
|
||||
"处方已保存并重新进入待审核。",
|
||||
"prescription",
|
||||
)
|
||||
|
||||
@@ -0,0 +1,384 @@
|
||||
"""Independent eSign identity enrollment for the signed-in doctor."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from time import monotonic
|
||||
from typing import Any
|
||||
|
||||
from PySide6.QtCore import QDateTime, Qt, QTimer, QTimeZone
|
||||
from PySide6.QtWidgets import (
|
||||
QDialog,
|
||||
QDialogButtonBox,
|
||||
QHBoxLayout,
|
||||
QLabel,
|
||||
QLineEdit,
|
||||
QPushButton,
|
||||
QVBoxLayout,
|
||||
QWidget,
|
||||
)
|
||||
from shiboken6 import isValid
|
||||
|
||||
from ...core.esign import certificate_identity_number, esign_doctor_mobile, esign_doctor_status
|
||||
from ..design_system import clinical_stylesheet
|
||||
from ..widgets import MessageBanner, run_async
|
||||
from .esign_webview import UNAVAILABLE_MESSAGE, create_identity_view
|
||||
|
||||
_NEEDS_MOBILE = {"unbound", "needs_mobile", "renewal_required"}
|
||||
_STATUS_TEXT = {
|
||||
"unbound": "首次电子签署前,请验证本人身份并绑定签署证书。",
|
||||
"needs_mobile": "请输入本人手机号码,完成签署身份验证。",
|
||||
"authenticating": "请使用手机支付宝扫描 e签宝认证页面中的二维码并完成人脸识别。完成后可在这里检查状态。",
|
||||
"binding_required": "身份验证已通过。请确认绑定医生签署证书。",
|
||||
"ready": "签署身份已就绪。开具处方时,请使用短信验证码确认当次签署。",
|
||||
"renewal_required": "医生签署证书需要更新。请使用本人手机号码完成人脸认证。",
|
||||
}
|
||||
_QUICKSIGN_STATUS_TEXT = {
|
||||
"authenticating": "请在 e签宝页面使用手机支付宝扫码刷脸。如出现协议,请本人阅读后选择是否同意。刷脸后可在这里确认快捷签授权。",
|
||||
"binding_required": "已收到 e签宝授权结果。请确认启用本人快捷签。",
|
||||
}
|
||||
_QUICKSIGN_RENEWAL_TEXT = {
|
||||
"expired": "快捷签授权已过期,请重新授权。",
|
||||
"exhausted": "快捷签授权次数已用完,请重新授权。",
|
||||
"invalid": "快捷签授权已失效,请重新授权。",
|
||||
}
|
||||
_BEIJING_TIME = QTimeZone(b"Asia/Shanghai")
|
||||
_SENSITIVE_INPUT = Qt.InputMethodHint.ImhSensitiveData | Qt.InputMethodHint.ImhNoPredictiveText
|
||||
|
||||
|
||||
class EsignDoctorDialog(QDialog):
|
||||
POLL_INTERVAL_MS = 5_000
|
||||
AUTH_TIMEOUT_SECONDS = 600
|
||||
|
||||
def __init__(self, repository: Any, *, parent: QWidget | None = None) -> None:
|
||||
super().__init__(parent)
|
||||
self.repository = repository
|
||||
self.state: dict[str, Any] = {}
|
||||
self._busy = False
|
||||
self._closed = False
|
||||
self._generation = 0
|
||||
self._retry_mobile = False
|
||||
self._deadline: float | None = None
|
||||
self._native_window_id: int | None = None
|
||||
self._native_hide_pending = False
|
||||
self.identity_view: Any = None
|
||||
self.poll_timer = QTimer(self)
|
||||
self.poll_timer.setInterval(self.POLL_INTERVAL_MS)
|
||||
self.poll_timer.timeout.connect(self._poll)
|
||||
|
||||
self.setWindowTitle("医生电子签署身份")
|
||||
self.setMinimumSize(740, 550)
|
||||
self.resize(900, 680)
|
||||
self.setStyleSheet(clinical_stylesheet("QDialog { background:#FFFFFF; }"))
|
||||
layout = QVBoxLayout(self)
|
||||
layout.setContentsMargins(24, 24, 24, 24)
|
||||
layout.setSpacing(12)
|
||||
self.banner = MessageBanner(parent=self)
|
||||
self.banner.label.setTextFormat(Qt.TextFormat.PlainText)
|
||||
layout.addWidget(self.banner)
|
||||
|
||||
self.mobile_form = QWidget(self)
|
||||
mobile_layout = QVBoxLayout(self.mobile_form)
|
||||
mobile_layout.setContentsMargins(0, 0, 0, 0)
|
||||
mobile_label = QLabel("本人手机号码", self.mobile_form)
|
||||
self.mobile_input = QLineEdit(self.mobile_form)
|
||||
self.mobile_input.setInputMethodHints(_SENSITIVE_INPUT | Qt.InputMethodHint.ImhDigitsOnly)
|
||||
self.mobile_input.setPlaceholderText("请输入 11 位手机号码")
|
||||
self.mobile_input.setAccessibleName("本人手机号码")
|
||||
mobile_label.setBuddy(self.mobile_input)
|
||||
mobile_layout.addWidget(mobile_label)
|
||||
mobile_layout.addWidget(self.mobile_input)
|
||||
layout.addWidget(self.mobile_form)
|
||||
|
||||
self.identity_form = QWidget(self)
|
||||
identity_layout = QVBoxLayout(self.identity_form)
|
||||
identity_layout.setContentsMargins(0, 0, 0, 0)
|
||||
identity_label = QLabel("请输入与本次人脸认证一致的身份证号码,用于首次绑定证书。", self.identity_form)
|
||||
identity_label.setWordWrap(True)
|
||||
self.identity_input = QLineEdit(self.identity_form)
|
||||
self.identity_input.setInputMethodHints(_SENSITIVE_INPUT)
|
||||
self.identity_input.setEchoMode(QLineEdit.EchoMode.Password)
|
||||
self.identity_input.setAccessibleName("证书绑定身份证号码")
|
||||
self.identity_input.setPlaceholderText("请输入 15 或 18 位中国大陆居民身份证号码")
|
||||
identity_label.setBuddy(self.identity_input)
|
||||
identity_layout.addWidget(identity_label)
|
||||
identity_layout.addWidget(self.identity_input)
|
||||
layout.addWidget(self.identity_form)
|
||||
|
||||
self.view_host = QWidget(self)
|
||||
self.view_layout = QVBoxLayout(self.view_host)
|
||||
self.view_layout.setContentsMargins(0, 0, 0, 0)
|
||||
layout.addWidget(self.view_host, 1)
|
||||
|
||||
footer = QHBoxLayout()
|
||||
self.start_button = QPushButton("开始人脸认证", self)
|
||||
self.start_button.clicked.connect(self._start)
|
||||
self.resume_button = QPushButton("继续人脸认证", self)
|
||||
self.resume_button.clicked.connect(self._open_authentication)
|
||||
self.change_mobile_button = QPushButton("重新输入手机号", self)
|
||||
self.change_mobile_button.clicked.connect(self._enter_mobile)
|
||||
self.bind_button = QPushButton("确认绑定证书", self)
|
||||
self.bind_button.clicked.connect(self._bind)
|
||||
self.refresh_button = QPushButton("检查认证状态", self)
|
||||
self.refresh_button.clicked.connect(self.refresh)
|
||||
self._buttons = (self.start_button, self.resume_button, self.bind_button,
|
||||
self.change_mobile_button, self.refresh_button)
|
||||
for button in self._buttons:
|
||||
button.setAutoDefault(False)
|
||||
footer.addWidget(button)
|
||||
for button in (self.start_button, self.resume_button, self.bind_button):
|
||||
button.setProperty("variant", "primary")
|
||||
footer.addStretch(1)
|
||||
close = QDialogButtonBox(QDialogButtonBox.StandardButton.Close, self)
|
||||
close_button = close.button(QDialogButtonBox.StandardButton.Close)
|
||||
close_button.setText("关闭")
|
||||
close_button.setAutoDefault(False)
|
||||
close.rejected.connect(self.reject)
|
||||
footer.addWidget(close)
|
||||
layout.addLayout(footer)
|
||||
self.banner.show_message("正在查询医生签署身份…", "info")
|
||||
self.refresh()
|
||||
|
||||
def _sync_actions(self) -> None:
|
||||
active = not self._busy and not self._closed and not self._native_hide_pending
|
||||
enabled = self.state.get("enabled") is True
|
||||
status = self.state.get("status")
|
||||
enrollment = enabled and (status in _NEEDS_MOBILE or self._retry_mobile)
|
||||
authenticating = enabled and status == "authenticating" and not enrollment
|
||||
binding = enabled and status == "binding_required"
|
||||
quick_authorizing = self.state.get("quicksign_authorizing") is True
|
||||
quick_start = (enabled and status == "ready" and self.state.get("quicksign_enabled") is True
|
||||
and not self.state.get("quicksign_expires_at"))
|
||||
self.start_button.setText("授权快捷签" if quick_start else "开始人脸认证")
|
||||
self.resume_button.setText("继续快捷签授权" if quick_authorizing else "继续人脸认证")
|
||||
self.bind_button.setText("确认快捷签授权" if quick_authorizing else "确认绑定证书")
|
||||
inputs = enrollment, binding and self.state.get("identity_details_required") is True
|
||||
for visible, form, field in zip(inputs, (self.mobile_form, self.identity_form),
|
||||
(self.mobile_input, self.identity_input), strict=True):
|
||||
if not visible:
|
||||
field.setText("")
|
||||
form.setVisible(visible)
|
||||
field.setEnabled(active and visible)
|
||||
controls = (
|
||||
enrollment or quick_start,
|
||||
authenticating and bool(self.state.get("auth_url")) and self.identity_view is None,
|
||||
binding,
|
||||
authenticating and self.identity_view is None and not quick_authorizing,
|
||||
True,
|
||||
)
|
||||
for button, visible in zip(self._buttons, controls, strict=True):
|
||||
button.setVisible(visible)
|
||||
button.setEnabled(active and visible)
|
||||
|
||||
def _apply_status(self, result: Any) -> None:
|
||||
self.state = esign_doctor_status(result)
|
||||
self._retry_mobile = False
|
||||
status = self.state["status"]
|
||||
if not self.state["enabled"] or status != "authenticating":
|
||||
self._stop_view()
|
||||
if not self.state["enabled"]:
|
||||
self.banner.show_message("当前环境未启用医生电子签署身份。", "info")
|
||||
else:
|
||||
message = (_QUICKSIGN_STATUS_TEXT[status] if self.state["quicksign_authorizing"] else _STATUS_TEXT[status])
|
||||
if self.state["quicksign_authorizing"] and status == "authenticating" and not self.state.get("auth_url"):
|
||||
message = "e签宝快捷签授权请求处理中,请稍后检查认证状态。"
|
||||
if status == "ready" and self.state["quicksign_enabled"]:
|
||||
quick_expiry = self.state["quicksign_expires_at"]
|
||||
if quick_expiry:
|
||||
date = QDateTime.fromSecsSinceEpoch(quick_expiry, _BEIJING_TIME).toString("yyyy-MM-dd HH:mm")
|
||||
message = f"快捷签授权有效期至 {date}(北京时间)。"
|
||||
remaining = self.state.get("quicksign_remaining_times")
|
||||
if remaining is not None:
|
||||
message += f"剩余 {remaining} 次。"
|
||||
message += "每张处方仍由开方医生本人确认签名。"
|
||||
else:
|
||||
reason = self.state.get("quicksign_unavailable_reason")
|
||||
message = _QUICKSIGN_RENEWAL_TEXT.get(reason, "签署身份已就绪。请授权使用本人的快捷签。")
|
||||
message += "每张处方仍由开方医生本人确认签名。"
|
||||
expires = self.state["cert_expires_at"]
|
||||
if status == "ready" and expires:
|
||||
date = QDateTime.fromSecsSinceEpoch(expires, _BEIJING_TIME).toString("yyyy-MM-dd HH:mm")
|
||||
message += f" 签署证书有效期至 {date}(北京时间)。"
|
||||
self.banner.show_message(message, "success" if status == "ready" else "info")
|
||||
self._sync_actions()
|
||||
|
||||
def _request(self, method: str, proof: str | None = None) -> None:
|
||||
if self._busy or self._closed:
|
||||
return
|
||||
self._busy = True
|
||||
generation = self._generation
|
||||
self._sync_actions()
|
||||
repository = self.repository
|
||||
|
||||
def current() -> bool:
|
||||
return isValid(self) and not self._closed and self._generation == generation
|
||||
|
||||
def loaded(result: Any) -> None:
|
||||
if not current():
|
||||
return
|
||||
try:
|
||||
self._apply_status(result)
|
||||
except Exception:
|
||||
failed(ValueError())
|
||||
|
||||
def failed(_error: Exception) -> None:
|
||||
if current():
|
||||
self._stop_view()
|
||||
self.state = {}
|
||||
self.banner.show_message("医生签署身份状态待确认,请检查认证状态后继续。", "warning")
|
||||
self._sync_actions()
|
||||
|
||||
def finished() -> None:
|
||||
if isValid(self):
|
||||
self._busy = False
|
||||
if self._closed:
|
||||
return
|
||||
self._sync_actions()
|
||||
if (current() and method == "start_esign_doctor" and self.isVisible()
|
||||
and self.state.get("auth_url")):
|
||||
self._open_authentication()
|
||||
|
||||
def work() -> Any:
|
||||
nonlocal proof
|
||||
try:
|
||||
return getattr(repository, method)(proof) if proof is not None else getattr(repository, method)()
|
||||
finally:
|
||||
proof = None
|
||||
|
||||
run_async(work, on_success=loaded, on_error=failed, on_finished=finished)
|
||||
|
||||
def refresh(self) -> None:
|
||||
if self._busy or self._closed:
|
||||
return
|
||||
self.mobile_input.setText("")
|
||||
self.identity_input.setText("")
|
||||
self._request("get_esign_doctor_status")
|
||||
|
||||
def _enter_mobile(self) -> None:
|
||||
self._retry_mobile = True
|
||||
self._sync_actions()
|
||||
self.mobile_input.setFocus()
|
||||
|
||||
def _start(self) -> None:
|
||||
if not self.start_button.isEnabled() or not self.isVisible():
|
||||
return
|
||||
if self.state.get("status") == "ready":
|
||||
self._request("start_esign_doctor", "")
|
||||
return
|
||||
try:
|
||||
mobile = esign_doctor_mobile(self.mobile_input.text())
|
||||
except ValueError as error:
|
||||
self.mobile_input.setText("")
|
||||
self.banner.show_message(str(error), "warning")
|
||||
return
|
||||
self.mobile_input.setText("")
|
||||
self._request("start_esign_doctor", mobile)
|
||||
|
||||
def _bind(self) -> None:
|
||||
if not self.bind_button.isEnabled() or not self.isVisible():
|
||||
return
|
||||
identity_number = ""
|
||||
if self.state.get("identity_details_required") is True:
|
||||
try:
|
||||
identity_number = certificate_identity_number(self.identity_input.text())
|
||||
except ValueError as error:
|
||||
self.identity_input.setText("")
|
||||
self.banner.show_message(str(error), "warning")
|
||||
return
|
||||
self.identity_input.setText("")
|
||||
self._request("complete_esign_doctor", identity_number or None)
|
||||
|
||||
def _open_authentication(self) -> None:
|
||||
if (self._busy or self._closed or not self.isVisible() or self.identity_view is not None
|
||||
or self.state.get("status") != "authenticating" or not self.state.get("auth_url")):
|
||||
return
|
||||
try:
|
||||
self._native_window_id = int(self.winId())
|
||||
view = create_identity_view(self.view_host)
|
||||
self.identity_view = view
|
||||
view.initialized.connect(lambda: self._native_ready(view))
|
||||
view.failed.connect(lambda _message: self._view_failed(view))
|
||||
self._deadline = monotonic() + self.AUTH_TIMEOUT_SECONDS
|
||||
self.view_layout.addWidget(view)
|
||||
if self.identity_view is view:
|
||||
view.load_authentication(self.state["auth_url"])
|
||||
if self.identity_view is view:
|
||||
view.show()
|
||||
if not self._native_hide_pending:
|
||||
self.poll_timer.start()
|
||||
except Exception:
|
||||
self._stop_view()
|
||||
self.banner.show_message(UNAVAILABLE_MESSAGE, "warning")
|
||||
self._sync_actions()
|
||||
|
||||
def _poll(self) -> None:
|
||||
if self._deadline is None or self._native_hide_pending or not self.isVisible():
|
||||
return
|
||||
if monotonic() >= self._deadline:
|
||||
self._generation += 1
|
||||
self._stop_view()
|
||||
self._sync_actions()
|
||||
self.banner.show_message("本次自动检查已结束。请检查认证状态后继续。", "warning")
|
||||
else:
|
||||
self._request("get_esign_doctor_status")
|
||||
|
||||
def _view_failed(self, view: Any) -> None:
|
||||
if view is self.identity_view and not self._closed:
|
||||
self._stop_view()
|
||||
self._sync_actions()
|
||||
self.banner.show_message("无法加载 e签宝认证页面,请检查认证状态后重试。", "warning")
|
||||
|
||||
def _stop_view(self) -> None:
|
||||
self.poll_timer.stop()
|
||||
self._deadline = None
|
||||
self._native_window_id = None
|
||||
self._native_hide_pending = False
|
||||
if self.identity_view is not None:
|
||||
view, self.identity_view = self.identity_view, None
|
||||
view.stop()
|
||||
self.view_layout.removeWidget(view)
|
||||
view.deleteLater()
|
||||
|
||||
def _native_ready(self, view: Any) -> None:
|
||||
if view is self.identity_view and not self._native_hide_pending:
|
||||
self._native_window_id = None
|
||||
|
||||
def _suspend(self) -> None:
|
||||
self._generation += 1
|
||||
self.mobile_input.setText("")
|
||||
self.identity_input.setText("")
|
||||
self._stop_view()
|
||||
if self._busy:
|
||||
self.state = {}
|
||||
self._sync_actions()
|
||||
|
||||
def _resolve_native_hide(self, native_id: int, generation: int) -> None:
|
||||
if not isValid(self) or self._closed or generation != self._generation or not self._native_hide_pending:
|
||||
return
|
||||
if self.identity_view is not None and self.isVisible() and not self.isMinimized() and int(self.winId()) != native_id:
|
||||
self._native_window_id = None
|
||||
self._native_hide_pending = False
|
||||
self.poll_timer.start()
|
||||
self._sync_actions()
|
||||
else:
|
||||
self._suspend()
|
||||
|
||||
def hideEvent(self, event: Any) -> None:
|
||||
if self._native_window_id is not None and not event.spontaneous() and not self._closed:
|
||||
# Qt can briefly hide the dialog while recreating its surface for WebEngine.
|
||||
self._native_hide_pending = True
|
||||
self.poll_timer.stop()
|
||||
native_id, generation = self._native_window_id, self._generation
|
||||
QTimer.singleShot(0, lambda: self._resolve_native_hide(native_id, generation))
|
||||
self._sync_actions()
|
||||
elif not self._closed:
|
||||
self._suspend()
|
||||
super().hideEvent(event)
|
||||
|
||||
def hide(self) -> None:
|
||||
self._suspend()
|
||||
super().hide()
|
||||
|
||||
def done(self, result: int) -> None:
|
||||
self._closed = True
|
||||
self._suspend()
|
||||
super().done(result)
|
||||
@@ -0,0 +1,168 @@
|
||||
"""Isolated official identity page; it has no application or signing bridge."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from PySide6.QtCore import Qt, QUrl, Signal
|
||||
from PySide6.QtWidgets import QVBoxLayout, QWidget
|
||||
|
||||
from ...core.esign import authentication_navigation_allowed, authentication_url
|
||||
|
||||
try:
|
||||
from PySide6.QtWebEngineCore import (
|
||||
QWebEnginePage,
|
||||
QWebEngineProfile,
|
||||
QWebEngineSettings,
|
||||
QWebEngineUrlRequestInterceptor,
|
||||
)
|
||||
from PySide6.QtWebEngineWidgets import QWebEngineView
|
||||
except (ImportError, OSError):
|
||||
WEBENGINE_AVAILABLE = False
|
||||
else:
|
||||
WEBENGINE_AVAILABLE = True
|
||||
|
||||
|
||||
UNAVAILABLE_MESSAGE = "当前安装缺少内置核身组件,请联系管理员修复或更新医生工作站后继续签署。"
|
||||
|
||||
|
||||
if WEBENGINE_AVAILABLE:
|
||||
class IdentityPage(QWebEnginePage):
|
||||
blocked = Signal(str)
|
||||
|
||||
def __init__(self, profile: Any, parent: QWidget) -> None:
|
||||
super().__init__(profile, parent)
|
||||
self.shutting_down = False
|
||||
|
||||
def acceptNavigationRequest(self, url: QUrl, navigation_type: Any, is_main_frame: bool) -> bool:
|
||||
del navigation_type, is_main_frame
|
||||
if self.shutting_down:
|
||||
return url.toString() == "about:blank"
|
||||
if authentication_navigation_allowed(url.toString()):
|
||||
return True
|
||||
self.blocked.emit("核身页面请求离开系统支持的认证范围,已停止。请联系管理员检查核身方式。")
|
||||
return False
|
||||
|
||||
def createWindow(self, window_type: Any) -> None:
|
||||
del window_type
|
||||
self.blocked.emit("当前核身页面要求打开新窗口,系统已阻止。请联系管理员使用短信核身方式。")
|
||||
return None
|
||||
|
||||
def chooseFiles(self, mode: Any, old_files: Any, accepted_types: Any) -> list[str]:
|
||||
del mode, old_files, accepted_types
|
||||
return []
|
||||
|
||||
def javaScriptConsoleMessage(self, level: Any, message: str, line: int, source: str) -> None:
|
||||
# Provider messages may contain identity/session data; never log them.
|
||||
pass
|
||||
|
||||
|
||||
class IdentityRequests(QWebEngineUrlRequestInterceptor):
|
||||
def interceptRequest(self, info: Any) -> None:
|
||||
url = info.requestUrl()
|
||||
# Inline resources are allowed; top-level/iframe navigation still goes
|
||||
# through IdentityPage. Network access stays on official HTTPS hosts.
|
||||
if url.scheme() not in {"data", "blob", "about"}:
|
||||
info.block(not authentication_navigation_allowed(url.toString()))
|
||||
|
||||
|
||||
class EmbeddedIdentityView(QWidget):
|
||||
"""Own a fresh memory-only profile for the lifetime of one authentication."""
|
||||
|
||||
failed = Signal(str)
|
||||
initialized = Signal()
|
||||
|
||||
def __init__(self, parent: QWidget | None = None) -> None:
|
||||
if not WEBENGINE_AVAILABLE:
|
||||
raise RuntimeError(UNAVAILABLE_MESSAGE)
|
||||
super().__init__(parent)
|
||||
self._stopped = False
|
||||
self._auth_url: str | None = None
|
||||
self.profile = QWebEngineProfile(self)
|
||||
if not self.profile.isOffTheRecord():
|
||||
raise RuntimeError("无法创建隔离的内置核身窗口,请联系管理员。")
|
||||
self.profile.setPersistentCookiesPolicy(QWebEngineProfile.PersistentCookiesPolicy.NoPersistentCookies)
|
||||
self.profile.setHttpCacheType(QWebEngineProfile.HttpCacheType.MemoryHttpCache)
|
||||
self.interceptor = IdentityRequests(self.profile)
|
||||
self.profile.setUrlRequestInterceptor(self.interceptor)
|
||||
self.profile.downloadRequested.connect(self._deny_download)
|
||||
self.view = QWebEngineView(self)
|
||||
self.page = IdentityPage(self.profile, self.view)
|
||||
self.view.setPage(self.page)
|
||||
# The profile must outlive its page even during deferred widget deletion.
|
||||
self.profile.setParent(None)
|
||||
self.page.destroyed.connect(self.profile.deleteLater)
|
||||
self.view.setContextMenuPolicy(Qt.ContextMenuPolicy.NoContextMenu)
|
||||
self.view.setAcceptDrops(False)
|
||||
settings = self.page.settings()
|
||||
attributes = QWebEngineSettings.WebAttribute
|
||||
for name in (
|
||||
"JavascriptCanOpenWindows", "JavascriptCanAccessClipboard", "JavascriptCanPaste",
|
||||
"LocalContentCanAccessRemoteUrls", "LocalContentCanAccessFileUrls",
|
||||
"AllowRunningInsecureContent", "PluginsEnabled", "FullScreenSupportEnabled",
|
||||
"ScreenCaptureEnabled", "HyperlinkAuditingEnabled",
|
||||
):
|
||||
attribute = getattr(attributes, name, None)
|
||||
if attribute is not None:
|
||||
settings.setAttribute(attribute, False)
|
||||
settings.setUnknownUrlSchemePolicy(QWebEngineSettings.UnknownUrlSchemePolicy.DisallowUnknownUrlSchemes)
|
||||
self.page.blocked.connect(self.failed)
|
||||
self.page.certificateError.connect(self._deny_certificate)
|
||||
if hasattr(self.page, "permissionRequested"):
|
||||
self.page.permissionRequested.connect(self._deny_permission)
|
||||
else:
|
||||
self.page.featurePermissionRequested.connect(self._deny_feature)
|
||||
self.page.renderProcessTerminated.connect(
|
||||
lambda *_args: self._failure("内置核身页面已停止,请查询当前状态后重新进入。")
|
||||
)
|
||||
self.view.loadFinished.connect(self._loaded)
|
||||
layout = QVBoxLayout(self)
|
||||
layout.setContentsMargins(0, 0, 0, 0)
|
||||
layout.addWidget(self.view)
|
||||
|
||||
def load_authentication(self, url: str) -> None:
|
||||
validated = authentication_url(url)
|
||||
if validated != self._auth_url:
|
||||
self._auth_url = validated
|
||||
self.view.setUrl(QUrl(validated))
|
||||
|
||||
def _failure(self, message: str) -> None:
|
||||
if not self._stopped:
|
||||
self.failed.emit(message)
|
||||
|
||||
def _loaded(self, success: bool) -> None:
|
||||
# A successful page load has no relationship to successful identity.
|
||||
if success and not self._stopped:
|
||||
self.initialized.emit()
|
||||
elif not success:
|
||||
self._failure("内置核身页面加载失败,请检查网络并查询当前状态后重试。")
|
||||
|
||||
def _deny_download(self, download: Any) -> None:
|
||||
download.cancel()
|
||||
self._failure("核身页面中的文件下载已禁用。已签原件请使用窗口下方的下载按钮。")
|
||||
|
||||
def _deny_certificate(self, error: Any) -> None:
|
||||
error.rejectCertificate()
|
||||
self._failure("核身页面的安全证书校验失败,已停止加载。请联系管理员检查网络或证书。")
|
||||
|
||||
def _deny_feature(self, origin: Any, feature: Any) -> None:
|
||||
self.page.setFeaturePermission(origin, feature, QWebEnginePage.PermissionPolicy.PermissionDeniedByUser)
|
||||
self._failure("当前核身页面请求设备权限,已停止。请联系管理员使用短信核身方式。")
|
||||
|
||||
def _deny_permission(self, permission: Any) -> None:
|
||||
permission.deny()
|
||||
self._failure("当前核身页面请求设备权限,已停止。请联系管理员使用短信核身方式。")
|
||||
|
||||
def stop(self) -> None:
|
||||
if self._stopped:
|
||||
return
|
||||
self._stopped = True
|
||||
self.page.shutting_down = True
|
||||
self.view.stop()
|
||||
self.view.setUrl(QUrl("about:blank"))
|
||||
self.profile.cookieStore().deleteAllCookies()
|
||||
self.hide()
|
||||
|
||||
|
||||
def create_identity_view(parent: QWidget) -> EmbeddedIdentityView:
|
||||
return EmbeddedIdentityView(parent)
|
||||
@@ -15,7 +15,7 @@ import os
|
||||
import re
|
||||
import sys
|
||||
import tempfile
|
||||
from collections.abc import Iterable, Mapping, Sequence
|
||||
from collections.abc import Callable, Iterable, Mapping, Sequence
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
from time import monotonic
|
||||
@@ -97,6 +97,7 @@ from PySide6.QtWidgets import (
|
||||
QWidget,
|
||||
)
|
||||
|
||||
from ...core.esign import esign_config, esign_status
|
||||
from .. import icons
|
||||
from ..design_system import clinical_stylesheet
|
||||
from ..diagnosis_terms import shared_terms
|
||||
@@ -116,8 +117,13 @@ from ..widgets import (
|
||||
show_toast,
|
||||
)
|
||||
from .diagnosis import DiagnosisDialog as _StructuredDiagnosisDialog
|
||||
from ...core.esign import esign_config, esign_status, signed_pdf_bytes
|
||||
from .prescription_esign import PrescriptionEsignDialog, signature_state
|
||||
from .prescription_esign import (
|
||||
PrescriptionEsignDialog,
|
||||
open_saved_original,
|
||||
save_signed_original,
|
||||
signature_state,
|
||||
signature_time_text,
|
||||
)
|
||||
|
||||
PRESCRIPTION_DRAWER_QSS = clinical_stylesheet(r"""
|
||||
QFrame#PrescriptionDrawerSurface {
|
||||
@@ -966,6 +972,133 @@ def _mapping(value: Any) -> dict[str, Any]:
|
||||
return result
|
||||
|
||||
|
||||
PRESCRIBE_PERMISSIONS = (
|
||||
"cf.prescription/add", "tcm.prescription/add", "tcm.diagnosis/chufang", "tcm.diagnosis/kaifang",
|
||||
)
|
||||
PRESCRIPTION_VOIDED_RESULT = 2
|
||||
_REISSUE_FIELDS = (
|
||||
"diagnosis_id", "appointment_id", "patient_id", "patient_name", "phone",
|
||||
"gender", "age", "visit_no", "case_record", "prescription_name", "prescription_type",
|
||||
"clinical_diagnosis", "tongue", "tongue_image", "pulse", "pulse_condition",
|
||||
"herbs", "dose_count", "dose_unit", "dosage_amount", "dosage_unit", "dosage_bag_count",
|
||||
"need_decoction", "bags_per_dose", "usage_days", "times_per_day", "usage_instruction",
|
||||
"usage_time", "usage_way", "dietary_taboo", "usage_notes", "aux_usage", "ai_assisted",
|
||||
)
|
||||
|
||||
|
||||
def prescription_is_voided(prescription: Any) -> bool:
|
||||
return _int(first_value(prescription, "void_status", "is_void")) == 1
|
||||
|
||||
|
||||
def can_void_issued_prescription(prescription: Any) -> bool:
|
||||
return not prescription_is_voided(prescription) and _bool(get_value(prescription, "can_void"))
|
||||
|
||||
|
||||
def can_reissue_prescription(prescription: Any, current_user: Any, permissions: Any) -> bool:
|
||||
actor_id = _int(first_value(current_user, "id", "user_id", "admin_id"))
|
||||
creator_id = _int(first_value(prescription, "creator_id", "doctor_id"))
|
||||
return (prescription_is_voided(prescription) and actor_id > 0 and actor_id == creator_id
|
||||
and has_permission(permissions, PRESCRIBE_PERMISSIONS))
|
||||
|
||||
|
||||
def prescription_edit_is_locked(prescription: Any) -> bool:
|
||||
if prescription_is_voided(prescription):
|
||||
can_restore = get_value(prescription, "can_restore_rejected")
|
||||
if can_restore is not None:
|
||||
return not _bool(can_restore)
|
||||
if _int(first_value(prescription, "audit_status", "status")) != 2:
|
||||
return True
|
||||
state = signature_state(prescription)
|
||||
return state.get("required") is True and state.get("status") != "pending"
|
||||
|
||||
|
||||
def reissue_prescription_seed(prescription: Any) -> dict[str, Any]:
|
||||
source = _mapping(prescription)
|
||||
seed = {key: source[key] for key in _REISSUE_FIELDS if key in source}
|
||||
if seed.get("visit_no") == source.get("sn"):
|
||||
seed.pop("visit_no", None)
|
||||
return seed
|
||||
|
||||
|
||||
def prescription_matches_appointment(
|
||||
prescription: Any, *, appointment_id: int, diagnosis_id: int, previous_id: int,
|
||||
) -> bool:
|
||||
current_id = _int(first_value(prescription, "id", "prescription_id"))
|
||||
current_appointment = _int(first_value(prescription, "appointment_id"))
|
||||
current_diagnosis = _int(first_value(prescription, "diagnosis_id"))
|
||||
if current_id <= 0 or (appointment_id > 0 and current_appointment > 0 and appointment_id != current_appointment):
|
||||
return False
|
||||
if diagnosis_id > 0 and current_diagnosis > 0 and diagnosis_id != current_diagnosis:
|
||||
return False
|
||||
# A list snapshot can refer to an older prescription. Accept a fresh ID only
|
||||
# when the appointment lookup proves it belongs to the same appointment.
|
||||
return previous_id <= 0 or current_id == previous_id or (appointment_id > 0 and appointment_id == current_appointment)
|
||||
|
||||
|
||||
def confirm_prescription_void(parent: QWidget, prescription: Any, *, current_changed: bool = False) -> bool:
|
||||
number = first_value(prescription, "sn", "id", "prescription_id")
|
||||
box = QMessageBox(parent)
|
||||
box.setWindowTitle("作废处方")
|
||||
box.setIcon(QMessageBox.Icon.Warning)
|
||||
box.setTextFormat(Qt.TextFormat.PlainText)
|
||||
box.setText(f"确定作废处方 {number}?")
|
||||
note = "原处方将保留作废记录。需要再次开具时,请重新开方并签署。"
|
||||
if current_changed:
|
||||
note = "此挂号已有更新的处方,本次将作废上方编号的处方。\n" + note
|
||||
box.setInformativeText(note)
|
||||
confirm = box.addButton("确认作废", QMessageBox.ButtonRole.DestructiveRole)
|
||||
cancel = box.addButton("取消", QMessageBox.ButtonRole.RejectRole)
|
||||
box.setDefaultButton(cancel)
|
||||
box.setEscapeButton(cancel)
|
||||
box.exec()
|
||||
return box.clickedButton() == confirm
|
||||
|
||||
|
||||
class _PrescriptionVoidButton(QPushButton):
|
||||
busy_changed = Signal(bool)
|
||||
|
||||
def __init__(self, dialog: QDialog, repository: Any, prescription: Any, banner: MessageBanner) -> None:
|
||||
super().__init__("作废处方", dialog)
|
||||
self.dialog = dialog
|
||||
self.repository = repository
|
||||
self.prescription = prescription
|
||||
self.banner = banner
|
||||
self.busy = False
|
||||
self.setProperty("variant", "danger")
|
||||
self.clicked.connect(self._submit)
|
||||
|
||||
def _submit(self) -> None:
|
||||
prescription_id = _int(first_value(self.prescription, "id", "prescription_id"))
|
||||
if self.busy or prescription_id <= 0 or not confirm_prescription_void(self.dialog, self.prescription):
|
||||
return
|
||||
self.busy = True
|
||||
self.busy_changed.emit(True)
|
||||
self.setEnabled(False)
|
||||
self.setText("正在作废…")
|
||||
self.banner.clear()
|
||||
result_received = False
|
||||
|
||||
def succeeded(_result: Any) -> None:
|
||||
nonlocal result_received
|
||||
result_received = True
|
||||
|
||||
def finished() -> None:
|
||||
self.busy = False
|
||||
self.busy_changed.emit(False)
|
||||
if result_received:
|
||||
self.dialog.done(PRESCRIPTION_VOIDED_RESULT)
|
||||
else:
|
||||
self.setEnabled(True)
|
||||
self.setText("重试作废")
|
||||
|
||||
run_async(
|
||||
lambda: self.repository.void_prescription(prescription_id),
|
||||
on_success=succeeded,
|
||||
on_error=lambda error: self.banner.show_message(friendly_error(error), "danger"),
|
||||
on_finished=finished,
|
||||
)
|
||||
|
||||
|
||||
_DIAGNOSIS_TYPE_LABELS = {
|
||||
"first_visit": "初诊",
|
||||
"follow_up": "复诊",
|
||||
@@ -2861,6 +2994,8 @@ class PrescriptionEditorDialog(QDialog):
|
||||
mode: str = "add",
|
||||
current_user: Any = None,
|
||||
permissions: Any = None,
|
||||
save_draft: Callable[[dict[str, Any]], Any] | None = None,
|
||||
allow_void: bool = False,
|
||||
parent: QWidget | None = None,
|
||||
) -> None:
|
||||
super().__init__(parent)
|
||||
@@ -2880,6 +3015,9 @@ class PrescriptionEditorDialog(QDialog):
|
||||
self._esign_ready = not callable(getattr(repository, "get_prescription_esign_config", None))
|
||||
self._save_fingerprint = ""
|
||||
self._save_request_key = ""
|
||||
self._save_draft = save_draft
|
||||
self._draft_saving = False
|
||||
self.saved_draft: Any = None
|
||||
self._loading_data = False
|
||||
self._linked_order_generation = 0
|
||||
self._diagnosis_view: _StructuredDiagnosisDialog | None = None
|
||||
@@ -2991,6 +3129,12 @@ class PrescriptionEditorDialog(QDialog):
|
||||
self.save_button = QPushButton("确定", button_row)
|
||||
self.save_button.setProperty("variant", "primary")
|
||||
self.save_button.clicked.connect(self.accept)
|
||||
self.void_button = None
|
||||
if (allow_void and mode == "edit" and can_void_issued_prescription(prescription)
|
||||
and callable(getattr(repository, "void_prescription", None))):
|
||||
self.void_button = _PrescriptionVoidButton(self, repository, prescription, self.validation)
|
||||
self.void_button.busy_changed.connect(self._void_busy_changed)
|
||||
button_layout.addWidget(self.void_button)
|
||||
button_layout.addWidget(self.cancel_button)
|
||||
button_layout.addWidget(self.save_button)
|
||||
self.buttons = button_row
|
||||
@@ -3000,8 +3144,13 @@ class PrescriptionEditorDialog(QDialog):
|
||||
self.tabs = _PrescriptionSectionNavigator(self)
|
||||
self._load_values()
|
||||
self._load_editor_context()
|
||||
self.save_button.setEnabled(not self._esign_content_locked())
|
||||
self._load_esign_config()
|
||||
|
||||
def _void_busy_changed(self, busy: bool) -> None:
|
||||
self.cancel_button.setEnabled(not busy)
|
||||
self.save_button.setEnabled(not busy and self._esign_ready and not self._esign_content_locked())
|
||||
|
||||
def _load_esign_config(self) -> None:
|
||||
method = getattr(self.repository, "get_prescription_esign_config", None)
|
||||
if not callable(method):
|
||||
@@ -3021,19 +3170,22 @@ class PrescriptionEditorDialog(QDialog):
|
||||
return
|
||||
self._esign_ready = True
|
||||
self._esign_enabled = config["enabled"]
|
||||
self.save_button.setEnabled(not self._esign_content_locked())
|
||||
self.save_button.setText("保存草稿并继续" if self._esign_enabled else "确定")
|
||||
self.save_button.setEnabled(not self._esign_content_locked() and not (self.void_button and self.void_button.busy))
|
||||
self.signature_field.setVisible(not self._esign_enabled)
|
||||
self.esign_retry_button.hide()
|
||||
self.esign_hint.setVisible(self._esign_enabled)
|
||||
environment = "(沙箱测试)" if config["environment"] == "sandbox" else ""
|
||||
self.esign_hint.setText(f"已启用 e签宝电子签署{environment}。保存后由开方医生完成核身并确认签署,无需手写签名。")
|
||||
next_step = "保存草稿后,请开方医生本人确认签名。" if config.get("verification_method") == "quick" else (
|
||||
"保存草稿后,请开方医生验证身份,再确认签名。"
|
||||
)
|
||||
self.esign_hint.setText(f"已启用 e签宝电子签署{environment}。{next_step}")
|
||||
if self._esign_content_locked():
|
||||
self.esign_hint.setText("处方已进入电子签署,内容已冻结;如需修改,请先作废后重新开方。")
|
||||
self.esign_hint.show()
|
||||
|
||||
def _esign_content_locked(self) -> bool:
|
||||
state = signature_state(self.prescription)
|
||||
return state.get("required") is True and state.get("status") not in {"pending", "legacy"}
|
||||
return self.mode == "edit" and prescription_edit_is_locked(self.prescription)
|
||||
|
||||
def _esign_config_failed(self, error: Exception) -> None:
|
||||
self._esign_ready = False
|
||||
@@ -4151,6 +4303,8 @@ class PrescriptionEditorDialog(QDialog):
|
||||
return f"{formula}第{count}味"
|
||||
|
||||
def accept(self) -> None:
|
||||
if self._draft_saving or (self.void_button is not None and self.void_button.busy):
|
||||
return
|
||||
payload = self.payload()
|
||||
if not self._esign_ready:
|
||||
self.validation.show_message("请先确认电子签署方式,再保存处方。", "warning")
|
||||
@@ -4217,9 +4371,48 @@ class PrescriptionEditorDialog(QDialog):
|
||||
self.validation.show_message(f"{label}药材剂量必须大于0", "warning")
|
||||
return
|
||||
self.validation.clear()
|
||||
if self._esign_enabled and self._save_draft is not None:
|
||||
self._submit_draft(payload)
|
||||
return
|
||||
super().accept()
|
||||
|
||||
def _submit_draft(self, payload: dict[str, Any]) -> None:
|
||||
save = self._save_draft
|
||||
if save is None or self._draft_saving:
|
||||
return
|
||||
self._draft_saving = True
|
||||
self.save_button.setText("正在保存草稿…")
|
||||
self.workspace_splitter.setEnabled(False)
|
||||
if self.void_button is not None:
|
||||
self.void_button.setEnabled(False)
|
||||
|
||||
def submit() -> Any:
|
||||
result = save(payload)
|
||||
if _int(first_value(result, "id", "prescription_id"), 0) <= 0:
|
||||
raise ValueError("未收到处方编号,请重试保存草稿。")
|
||||
return result
|
||||
|
||||
def saved(result: Any) -> None:
|
||||
self.saved_draft = result
|
||||
|
||||
def failed(error: Exception) -> None:
|
||||
self.validation.show_message(f"草稿保存失败。{friendly_error(error)}", "danger")
|
||||
|
||||
def finished() -> None:
|
||||
self._draft_saving = False
|
||||
self.workspace_splitter.setEnabled(True)
|
||||
if self.saved_draft is not None:
|
||||
super(PrescriptionEditorDialog, self).accept()
|
||||
else:
|
||||
self.save_button.setText("重试保存草稿")
|
||||
if self.void_button is not None:
|
||||
self.void_button.setEnabled(True)
|
||||
|
||||
run_async(submit, on_success=saved, on_error=failed, on_finished=finished)
|
||||
|
||||
def done(self, result: int) -> None:
|
||||
if self._draft_saving or (self.void_button is not None and self.void_button.busy):
|
||||
return
|
||||
if self._diagnosis_view is not None and self._diagnosis_view.isVisible():
|
||||
self._diagnosis_view.reject()
|
||||
super().done(result)
|
||||
@@ -4579,6 +4772,21 @@ _SLIP_COMPANY_LINE = "成都双流甄养堂互联网医院有限公司 联系方
|
||||
_SLIP_ADDRESS_LINE = "地址:四川省成都市双流区黄甲街道黄龙大道二段280号"
|
||||
|
||||
|
||||
def _prescription_signature_size(signature: str, *, is_internal: bool) -> str:
|
||||
bounds = QSize(78, 36) if is_internal else QSize(76, 24)
|
||||
if signature.startswith("data:image/") and "," in signature:
|
||||
try:
|
||||
image = QImage.fromData(base64.b64decode(signature.split(",", 1)[1], validate=True))
|
||||
except ValueError:
|
||||
return f'height="{bounds.height()}"'
|
||||
if not image.isNull():
|
||||
size = image.size()
|
||||
if size.width() > bounds.width() or size.height() > bounds.height():
|
||||
size = size.scaled(bounds, Qt.AspectRatioMode.KeepAspectRatio)
|
||||
return f'width="{max(1, size.width())}" height="{max(1, size.height())}"'
|
||||
return f'height="{bounds.height()}"'
|
||||
|
||||
|
||||
def render_prescription_html(
|
||||
prescription: Any,
|
||||
*,
|
||||
@@ -4607,7 +4815,6 @@ def render_prescription_html(
|
||||
rp_font_size = "16px"
|
||||
section_font_size = "12px"
|
||||
info_padding = "9px 12px"
|
||||
bottom_height = "52px"
|
||||
herbs = _herb_rows(prescription)
|
||||
dose_count = max(1, _int(source.get("dose_count"), 1))
|
||||
main = [row for row in herbs if _formula(row.get("formula_type")) == "主方"]
|
||||
@@ -4813,7 +5020,8 @@ def render_prescription_html(
|
||||
days_text = "—"
|
||||
signature = str(source.get("doctor_signature") or "").strip()
|
||||
signature_html = (
|
||||
f'<img class="signature" src="{html.escape(signature, quote=True)}" alt="医师签名" />'
|
||||
f'<img class="signature" src="{html.escape(signature, quote=True)}" '
|
||||
f'{_prescription_signature_size(signature, is_internal=is_internal)} alt="医师签名" />'
|
||||
if signature
|
||||
else f'<span class="doctor-name">{esc(source.get("doctor_name"))}</span>'
|
||||
)
|
||||
@@ -4867,15 +5075,15 @@ def render_prescription_html(
|
||||
)
|
||||
if is_internal:
|
||||
bottom_row = (
|
||||
f'<td class="doctor"><span class="doctor-title">医师</span>{signature_html}</td>'
|
||||
f'<td><span class="meta-key">类型:</span> {esc(type_text)}</td>'
|
||||
f'<td><span class="meta-key">天数:</span> {html.escape(days_text)}</td>'
|
||||
f'<td><span class="meta-key">剂量:</span> {per_dose}克</td>'
|
||||
f'<td width="16.7%" class="pharmacy-doctor"><span class="pharmacy-key">医师</span> {signature_html}</td>'
|
||||
f'<td width="19.9%"><span class="pharmacy-key">类型:</span> {esc(type_text)}</td>'
|
||||
f'<td width="10.2%" class="pharmacy-days"><span class="pharmacy-key">天数:</span> {html.escape(days_text)}</td>'
|
||||
f'<td width="53.2%" class="pharmacy-dose"><span class="pharmacy-key">剂量:</span> {per_dose}克</td>'
|
||||
)
|
||||
hospital_colspan = 4
|
||||
else:
|
||||
bottom_row = (
|
||||
f'<td class="doctor"><span class="doctor-title">医师</span>{signature_html}</td>'
|
||||
f'<td class="doctor"><span class="doctor-title">医师</span> {signature_html}</td>'
|
||||
f'<td><span class="meta-key">天数:</span> {html.escape(days_text)}</td>'
|
||||
)
|
||||
hospital_colspan = 2
|
||||
@@ -4945,14 +5153,20 @@ body {{ margin:0; padding:{body_padding}; background:{body_background}; color:#1
|
||||
.empty-herbs {{ color:#8a8f98; padding:18px 6px !important; text-align:center; }}
|
||||
.rx-text {{ border:1px solid #c8c8c8; border-top:0; padding:10px 12px; line-height:1.75; font-size:13px; }}
|
||||
.rx-text p {{ margin:0; padding:0; }}
|
||||
.rx-text.pharmacy-text p {{ line-height:1.85; }}
|
||||
.warning {{ color:#d72424; font-weight:600; }}
|
||||
.bottom {{ width:100%; border-collapse:collapse; table-layout:fixed; }}
|
||||
.bottom td {{ border:1px solid #c8c8c8; border-top:0; padding:8px 12px;
|
||||
height:{bottom_height}; vertical-align:middle; font-size:12px; color:#1f1f1f; }}
|
||||
height:52px; vertical-align:middle; font-size:12px; color:#1f1f1f; }}
|
||||
.bottom .doctor {{ width:40%; }}
|
||||
.bottom .pharmacy-signoff td {{ border-top:1px solid #c8c8c8; }}
|
||||
.bottom .pharmacy-doctor {{ padding-left:10px; padding-right:0; }}
|
||||
.bottom .pharmacy-days {{ padding-left:8px; padding-right:0; }}
|
||||
.bottom .pharmacy-dose {{ line-height:53px; }}
|
||||
.pharmacy-key {{ color:#1f1f1f; }}
|
||||
.doctor-title {{ margin-right:8px; color:#6b7280; }}
|
||||
.doctor-name {{ font-size:13px; }}
|
||||
.signature {{ max-width:110px; max-height:40px; vertical-align:middle; }}
|
||||
.signature {{ max-width:76px; max-height:24px; vertical-align:middle; }}
|
||||
.meta-key {{ color:#6b7280; margin-right:6px; }}
|
||||
.hospital {{ height:auto; vertical-align:top; padding:10px 12px; font-size:12px;
|
||||
color:#6b7280; line-height:1.65; }}
|
||||
@@ -4983,8 +5197,8 @@ body {{ margin:0; padding:{body_padding}; background:{body_background}; color:#1
|
||||
{herb_html}
|
||||
</table>
|
||||
</td></tr></table>
|
||||
<div class="rx-text">{"".join(text_rows)}</div>
|
||||
<table class="bottom" width="100%" cellspacing="0" cellpadding="0"><tr>
|
||||
<div class="rx-text{' pharmacy-text' if is_internal else ''}">{"".join(text_rows)}</div>
|
||||
<table class="bottom" width="100%" cellspacing="0" cellpadding="0"><tr class="{'pharmacy-signoff' if is_internal else ''}">
|
||||
{bottom_row}
|
||||
</tr>
|
||||
<tr><td class="hospital" colspan="{hospital_colspan}">
|
||||
@@ -5292,6 +5506,7 @@ class PrescriptionDetailDialog(QDialog):
|
||||
can_open_diagnosis: bool = True,
|
||||
can_open_orders: bool = False,
|
||||
repository: Any = None,
|
||||
allow_void: bool = False,
|
||||
parent: QWidget | None = None,
|
||||
) -> None:
|
||||
super().__init__(parent)
|
||||
@@ -5306,6 +5521,7 @@ class PrescriptionDetailDialog(QDialog):
|
||||
self.esign = {}
|
||||
self._esign_unconfirmed = True
|
||||
self._esign_busy = False
|
||||
self._saved_original: Path | None = None
|
||||
self.document = QTextDocument(self)
|
||||
self.document.setDocumentMargin(0)
|
||||
self.document.setHtml(render_prescription_html(prescription, variant="internal"))
|
||||
@@ -5326,7 +5542,7 @@ class PrescriptionDetailDialog(QDialog):
|
||||
self.orders_button.setVisible(can_open_orders and prescription_id > 0)
|
||||
self.orders_button.clicked.connect(lambda: self.orders_requested.emit(prescription_id))
|
||||
actions.addWidget(self.orders_button)
|
||||
self.esign_button = QPushButton("电子签署 / 查询", self)
|
||||
self.esign_button = QPushButton("查看签署状态", self)
|
||||
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)
|
||||
actions.addWidget(self.esign_button)
|
||||
@@ -5334,6 +5550,9 @@ class PrescriptionDetailDialog(QDialog):
|
||||
print_button = QPushButton("打印")
|
||||
print_button.clicked.connect(self.print_slip)
|
||||
actions.addWidget(print_button)
|
||||
self.open_original_button = QPushButton("打开已保存原件", self)
|
||||
self.open_original_button.clicked.connect(self._open_saved_original)
|
||||
actions.addWidget(self.open_original_button)
|
||||
pdf_button = QPushButton("导出 PDF")
|
||||
self.pdf_button = pdf_button
|
||||
pdf_button.setProperty("variant", "primary")
|
||||
@@ -5369,6 +5588,7 @@ class PrescriptionDetailDialog(QDialog):
|
||||
self.status_banner.show_message(" ".join(status_lines), banner_kind)
|
||||
root.addWidget(self.status_banner)
|
||||
self.esign_banner = MessageBanner(parent=self)
|
||||
self.esign_banner.label.setTextFormat(Qt.TextFormat.PlainText)
|
||||
root.addWidget(self.esign_banner)
|
||||
self.preview = _PrescriptionPaperPreview(prescription, variant="internal")
|
||||
self.preview.setObjectName("PrescriptionPaperPreview")
|
||||
@@ -5413,12 +5633,24 @@ class PrescriptionDetailDialog(QDialog):
|
||||
close = QDialogButtonBox(QDialogButtonBox.StandardButton.Close)
|
||||
close.button(QDialogButtonBox.StandardButton.Close).setText("关闭")
|
||||
close.rejected.connect(self.reject)
|
||||
self.void_button = None
|
||||
if (allow_void and can_void_issued_prescription(prescription)
|
||||
and callable(getattr(self.repository, "void_prescription", None))):
|
||||
self.void_button = _PrescriptionVoidButton(self, self.repository, prescription, self.esign_banner)
|
||||
close.addButton(self.void_button, QDialogButtonBox.ButtonRole.ActionRole)
|
||||
self.void_button.busy_changed.connect(lambda busy: self.tabs.setEnabled(not busy))
|
||||
root.addWidget(close)
|
||||
self.tabs.currentChanged.connect(self._sync_esign_export)
|
||||
if not self._esign_unconfirmed:
|
||||
self._render_esign_status()
|
||||
self._sync_esign_export()
|
||||
if callable(getattr(self.repository, "get_prescription_esign_status", None)):
|
||||
self.refresh_esign()
|
||||
|
||||
def done(self, result: int) -> None:
|
||||
if self.void_button is None or not self.void_button.busy:
|
||||
super().done(result)
|
||||
|
||||
def refresh_esign(self) -> None:
|
||||
if self._esign_busy:
|
||||
return
|
||||
@@ -5434,14 +5666,27 @@ class PrescriptionDetailDialog(QDialog):
|
||||
self._esign_failed(error)
|
||||
return
|
||||
self._esign_unconfirmed = False
|
||||
label = str(self.esign.get("status_label") or self.esign["status"])
|
||||
environment = " · 沙箱测试" if self.esign["environment"] == "sandbox" and self.esign["status"] != "legacy" else ""
|
||||
if self.esign["enabled"] or self.esign["required"]:
|
||||
self.esign_banner.show_message(f"电子签署:{label}{environment} {self.esign.get('message') or ''}", "success" if self.esign["status"] == "signed" else "info")
|
||||
else:
|
||||
self.esign_banner.clear()
|
||||
self._render_esign_status()
|
||||
self._sync_esign_export()
|
||||
|
||||
def _render_esign_status(self) -> None:
|
||||
time_text = signature_time_text(self.esign)
|
||||
if not (self.esign["enabled"] or self.esign["required"] or time_text):
|
||||
self.esign_banner.clear()
|
||||
return
|
||||
status = self.esign["status"]
|
||||
label = str(self.esign.get("status_label") or status)
|
||||
environment = " · 沙箱测试" if self.esign["environment"] == "sandbox" and status != "legacy" else ""
|
||||
status_message = str(self.esign.get("message") or "")
|
||||
heading = f"电子签署:{label}{environment}"
|
||||
if status_message:
|
||||
heading += f" {status_message}"
|
||||
edit_hint = ""
|
||||
if self.void_button is not None and self.esign["required"] and status not in {"pending", "voided"}:
|
||||
edit_hint = "签署流程已开始。如需修改处方内容,请先点击底部「作废处方」,再重新开方。"
|
||||
message = "\n".join(filter(None, (heading, time_text, edit_hint)))
|
||||
self.esign_banner.show_message(message, "success" if status == "signed" else "info")
|
||||
|
||||
def _esign_failed(self, error: Exception) -> None:
|
||||
self._esign_unconfirmed = True
|
||||
self.esign_banner.show_message(f"签署状态尚未确认:{friendly_error(error)} 请打开电子签署查询结果。", "warning")
|
||||
@@ -5457,11 +5702,19 @@ class PrescriptionDetailDialog(QDialog):
|
||||
self.pdf_button.setText("下载已签原件" if electronic and not case_record else "导出 PDF")
|
||||
allowed = case_record or (not self._esign_unconfirmed and (not electronic or self.esign.get("can_download") is True))
|
||||
self.pdf_button.setEnabled(allowed and not self._esign_busy)
|
||||
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.setEnabled(original_available and not self._esign_busy)
|
||||
if not self._esign_unconfirmed and self.esign.get("can_sign") is True:
|
||||
self.esign_button.setText("继续开方签名")
|
||||
else:
|
||||
self.esign_button.setText("查看签署状态")
|
||||
self.esign_button.setEnabled(not self._esign_busy)
|
||||
self.tabs.setEnabled(not self._esign_busy)
|
||||
|
||||
def open_esign(self) -> None:
|
||||
dialog = PrescriptionEsignDialog(self.repository, {"id": first_value(self.prescription, "id"), "esign": self.esign}, parent=self)
|
||||
draft = _mapping(self.prescription) | {"id": first_value(self.prescription, "id"), "esign": self.esign}
|
||||
dialog = PrescriptionEsignDialog(self.repository, draft, parent=self)
|
||||
dialog.status_changed.connect(self._esign_loaded)
|
||||
dialog.exec()
|
||||
self.refresh_esign()
|
||||
@@ -5500,6 +5753,9 @@ class PrescriptionDetailDialog(QDialog):
|
||||
painter.end()
|
||||
|
||||
def choose_pdf_path(self) -> None:
|
||||
if not self._is_case_record_selected() and self.esign.get("can_download") is True:
|
||||
self.export_pdf()
|
||||
return
|
||||
patient = str(first_value(self.prescription, "patient_name", default="患者"))
|
||||
if self._is_case_record_selected():
|
||||
diagnosis_id = first_value(self.prescription, "diagnosis_id", default="")
|
||||
@@ -5518,44 +5774,62 @@ class PrescriptionDetailDialog(QDialog):
|
||||
if path:
|
||||
self.export_pdf(path)
|
||||
|
||||
def export_pdf(self, path: str | Path) -> None:
|
||||
output = str(path)
|
||||
if not output.lower().endswith(".pdf"):
|
||||
def _open_saved_original(self) -> None:
|
||||
if self.open_original_button.isEnabled() and self._saved_original is not None:
|
||||
open_saved_original(self._saved_original, self.esign_banner)
|
||||
|
||||
def export_pdf(self, path: str | Path | None = None) -> None:
|
||||
output = str(path) if path is not None else None
|
||||
if output is not None and not output.lower().endswith(".pdf"):
|
||||
output += ".pdf"
|
||||
if self._esign_busy:
|
||||
return
|
||||
if self._is_case_record_selected():
|
||||
self._export_rendered_pdf(output)
|
||||
if output is not None:
|
||||
self._export_rendered_pdf(output)
|
||||
return
|
||||
if callable(getattr(self.repository, "get_prescription_esign_status", None)):
|
||||
self._esign_busy = True
|
||||
self._sync_esign_export()
|
||||
prescription_id = _int(first_value(self.prescription, "id", default=0))
|
||||
|
||||
def check_and_download() -> dict[str, Any]:
|
||||
def check_and_download() -> tuple[dict[str, Any], Path | None]:
|
||||
current = esign_status(self.repository.get_prescription_esign_status(prescription_id))
|
||||
electronic = current["required"] or current["status"] != "legacy" or current["can_download"]
|
||||
if electronic:
|
||||
if current["can_download"] is not True:
|
||||
if output is None:
|
||||
return current, None
|
||||
raise ValueError(current.get("message") or "当前尚无可下载的已签原件,请先完成签署。")
|
||||
result = self.repository.download_prescription_esign(prescription_id)
|
||||
Path(output).write_bytes(signed_pdf_bytes(result))
|
||||
return current
|
||||
return current, save_signed_original(self.repository, prescription_id, current["environment"], output)
|
||||
return current, None
|
||||
|
||||
def checked(current: dict[str, Any]) -> None:
|
||||
def checked(result: tuple[dict[str, Any], Path | None]) -> None:
|
||||
current, saved_path = result
|
||||
self._esign_loaded(current)
|
||||
if current["can_download"]:
|
||||
if saved_path is not None:
|
||||
prefix = "沙箱测试:" if current["environment"] == "sandbox" else ""
|
||||
self.esign_banner.show_message(prefix + "已签原件已下载,并通过 SHA-256 校验。", "success")
|
||||
else:
|
||||
message = "已签原件已下载,并通过 SHA-256 校验。"
|
||||
if output is None:
|
||||
self._saved_original = saved_path
|
||||
message = "已保存到工作站,并通过 SHA-256 校验。可打开已保存原件。"
|
||||
self.esign_banner.show_message(prefix + message, "success")
|
||||
elif output is not None:
|
||||
self._export_rendered_pdf(output)
|
||||
|
||||
run_async(check_and_download, on_success=checked, on_error=self._esign_failed, on_finished=self._esign_finished)
|
||||
def failed(error: Exception) -> None:
|
||||
if output is None:
|
||||
self.esign_banner.show_message(f"保存签署原件失败。{friendly_error(error)} 请重试下载。", "warning")
|
||||
else:
|
||||
self._esign_failed(error)
|
||||
|
||||
run_async(check_and_download, on_success=checked, on_error=failed, on_finished=self._esign_finished)
|
||||
return
|
||||
if self._esign_unconfirmed or self.esign.get("status") != "legacy" or self.esign.get("required") is not False:
|
||||
self.esign_banner.show_message("请先查询并确认电子签署状态,再下载处方。", "warning")
|
||||
return
|
||||
self._export_rendered_pdf(output)
|
||||
if output is not None:
|
||||
self._export_rendered_pdf(output)
|
||||
|
||||
def _export_rendered_pdf(self, output: str) -> None:
|
||||
"""Render only case records or prescriptions authoritatively confirmed as legacy."""
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -45,17 +45,25 @@ from ..appointments_style import appointments_stylesheet
|
||||
from ..dialogs import DiagnosisDialog
|
||||
from ..dialogs.ai_consult import can_open_ai_consult, present_ai_consult
|
||||
from ..dialogs.prescription import (
|
||||
PRESCRIPTION_VOIDED_RESULT,
|
||||
PrescriptionDetailDialog,
|
||||
PrescriptionEditorDialog,
|
||||
build_prescription_clinical_diagnosis,
|
||||
build_prescription_visit_no,
|
||||
can_reissue_prescription,
|
||||
prescription_edit_is_locked,
|
||||
prescription_matches_appointment,
|
||||
reissue_prescription_seed,
|
||||
)
|
||||
from ..dialogs.prescription_ai import (
|
||||
can_open_diagnosis_ai_report,
|
||||
present_diagnosis_ai_report,
|
||||
)
|
||||
from ..dialogs.prescription_esign import (
|
||||
resume_saved_prescription,
|
||||
saved_prescription_message,
|
||||
)
|
||||
from ..filter_disclosure import FilterDisclosure
|
||||
from ..dialogs.prescription_esign import resume_saved_prescription, saved_prescription_message, signature_state
|
||||
from ..icons import icon
|
||||
from ..infinite_list import InfiniteList
|
||||
from ..reception_style import heading_family
|
||||
@@ -241,7 +249,9 @@ def prescription_action_label(row: Any) -> str:
|
||||
)
|
||||
if not has_prescription:
|
||||
return "开方"
|
||||
return "查看" if audit == 1 and voided != 1 else "编辑处方"
|
||||
if voided == 1:
|
||||
return "重新开方"
|
||||
return "查看" if audit == 1 else "编辑处方"
|
||||
|
||||
|
||||
def _patient_cell(_value: Any, row: Any, *, can_plain: bool) -> str:
|
||||
@@ -1859,7 +1869,7 @@ class AppointmentsPage(QWidget):
|
||||
if _diagnosis_id(row) <= 0 or _appointment_id(row) <= 0:
|
||||
show_toast(self, "该预约缺少诊单信息,请先编辑患者。", "warning")
|
||||
return
|
||||
mode = "view" if prescription_action_label(row) == "查看" else "open"
|
||||
mode = {"查看": "view", "重新开方": "reissue"}.get(prescription_action_label(row), "open")
|
||||
self._begin_prescription_load(row, mode=mode)
|
||||
|
||||
def _view_case(self) -> None:
|
||||
@@ -1944,25 +1954,20 @@ class AppointmentsPage(QWidget):
|
||||
expected_id = _as_int(
|
||||
first_value(row, "current_prescription_id", default=0)
|
||||
)
|
||||
actual_appointment_id = _as_int(
|
||||
first_value(existing, "appointment_id", default=0)
|
||||
)
|
||||
expected_appointment_id = _appointment_id(row)
|
||||
identity_changed = (
|
||||
(expected_id > 0 and actual_id != expected_id)
|
||||
or (
|
||||
actual_appointment_id > 0
|
||||
and expected_appointment_id > 0
|
||||
and actual_appointment_id != expected_appointment_id
|
||||
)
|
||||
)
|
||||
if mode == "view" and (not approved or voided or identity_changed):
|
||||
if not prescription_matches_appointment(
|
||||
existing, appointment_id=_appointment_id(row), diagnosis_id=_diagnosis_id(row), previous_id=expected_id,
|
||||
):
|
||||
self.banner.show_message("返回的处方与当前挂号不一致,已停止操作。", "warning")
|
||||
return
|
||||
if mode == "view" and (not approved or voided):
|
||||
self.banner.show_message(
|
||||
"当前挂号的处方状态已变化,请刷新列表后重试。",
|
||||
"warning",
|
||||
)
|
||||
return
|
||||
if (not approved or voided) and not (signature_state(existing).get("required") is True and not voided):
|
||||
if voided and can_reissue_prescription(existing, self.current_user, self.permissions):
|
||||
self._open_new_prescription(reissue_prescription_seed(existing))
|
||||
elif not approved and not prescription_edit_is_locked(existing):
|
||||
self._open_existing_prescription_editor(existing)
|
||||
else:
|
||||
dialog = PrescriptionDetailDialog(
|
||||
@@ -1970,12 +1975,16 @@ class AppointmentsPage(QWidget):
|
||||
can_open_diagnosis=_canonical_allowed(
|
||||
self.permissions, "tcm.diagnosis/readonlyDetail", default=False
|
||||
),
|
||||
allow_void=True,
|
||||
parent=self,
|
||||
)
|
||||
dialog.diagnosis_requested.connect(self._open_diagnosis_id)
|
||||
dialog.exec()
|
||||
if dialog.exec() == PRESCRIPTION_VOIDED_RESULT:
|
||||
self._after_prescription_void()
|
||||
if expected_id > 0 and actual_id != expected_id and not self._mutation_pending:
|
||||
self.refresh(silent=True)
|
||||
return
|
||||
if mode == "view":
|
||||
if mode in {"view", "reissue"}:
|
||||
self.banner.show_message(
|
||||
"当前挂号没有可查看的处方,请刷新列表后重试。",
|
||||
"warning",
|
||||
@@ -1988,30 +1997,38 @@ class AppointmentsPage(QWidget):
|
||||
if prescription_id <= 0:
|
||||
self.banner.show_message("处方编号不完整,无法编辑。", "danger")
|
||||
return
|
||||
def save_changes(payload: Any) -> Any:
|
||||
return invoke(self.repository, "update_prescription", prescription=prescription_id, changes=payload)
|
||||
|
||||
dialog = PrescriptionEditorDialog(
|
||||
self.repository,
|
||||
prescription,
|
||||
mode="edit",
|
||||
current_user=self.current_user,
|
||||
save_draft=save_changes,
|
||||
allow_void=True,
|
||||
parent=self,
|
||||
)
|
||||
diagnosis_signal = getattr(dialog, "diagnosis_requested", None)
|
||||
if diagnosis_signal is not None:
|
||||
diagnosis_signal.connect(self._open_diagnosis_id)
|
||||
if dialog.exec() != QDialog.DialogCode.Accepted:
|
||||
result = dialog.exec()
|
||||
if result == PRESCRIPTION_VOIDED_RESULT:
|
||||
self._after_prescription_void()
|
||||
return
|
||||
if result != QDialog.DialogCode.Accepted:
|
||||
return
|
||||
self._action_generation += 1
|
||||
generation = self._action_generation
|
||||
saved_draft = getattr(dialog, "saved_draft", None)
|
||||
if saved_draft is not None:
|
||||
self._prescription_updated(generation, saved_draft)
|
||||
return
|
||||
frozen_payload = MappingProxyType(dialog.payload())
|
||||
self._mutation_pending = True
|
||||
self._action_generation += 1
|
||||
generation = self._action_generation
|
||||
self.banner.show_message("正在保存处方…", "info")
|
||||
run_async(
|
||||
lambda: invoke(
|
||||
self.repository,
|
||||
"update_prescription",
|
||||
prescription=prescription_id,
|
||||
changes=frozen_payload,
|
||||
),
|
||||
lambda: save_changes(frozen_payload),
|
||||
on_success=lambda result: self._prescription_updated(generation, result),
|
||||
on_error=lambda error: self._action_error(error, generation),
|
||||
on_finished=lambda: self._mutation_finished(generation),
|
||||
@@ -2025,6 +2042,10 @@ class AppointmentsPage(QWidget):
|
||||
self.refresh(silent=True)
|
||||
resume_saved_prescription(self.repository, prescription, self)
|
||||
|
||||
def _after_prescription_void(self) -> None:
|
||||
show_toast(self, "处方已作废。需要再次开具时,请选择「重新开方」。", "success")
|
||||
self.refresh(silent=True)
|
||||
|
||||
def _begin_case_record_load(self, row: Any) -> None:
|
||||
snapshot = deepcopy(row)
|
||||
diagnosis_id = _diagnosis_id(snapshot)
|
||||
@@ -2101,12 +2122,23 @@ class AppointmentsPage(QWidget):
|
||||
self._diagnosis_dialog().open_view_only(diagnosis_id)
|
||||
|
||||
def _open_prescription_editor(self, record: Any, case_record: Any) -> None:
|
||||
seed = self._prescription_seed(record, case_record)
|
||||
self._open_new_prescription(self._prescription_seed(record, case_record))
|
||||
|
||||
def _open_new_prescription(self, seed: dict[str, Any]) -> None:
|
||||
def save_new(payload: dict[str, Any]) -> Any:
|
||||
authoritative = {
|
||||
"diagnosis_id": seed["diagnosis_id"],
|
||||
"appointment_id": seed["appointment_id"],
|
||||
"case_record": deepcopy(seed.get("case_record", {})),
|
||||
}
|
||||
return invoke(self.repository, "create_prescription", prescription=MappingProxyType(payload | authoritative))
|
||||
|
||||
dialog = PrescriptionEditorDialog(
|
||||
self.repository,
|
||||
seed,
|
||||
mode="add",
|
||||
current_user=self.current_user,
|
||||
save_draft=save_new,
|
||||
parent=self,
|
||||
)
|
||||
diagnosis_signal = getattr(dialog, "diagnosis_requested", None)
|
||||
@@ -2114,17 +2146,17 @@ class AppointmentsPage(QWidget):
|
||||
diagnosis_signal.connect(self._open_diagnosis_id)
|
||||
if dialog.exec() != QDialog.DialogCode.Accepted:
|
||||
return
|
||||
payload = dialog.payload()
|
||||
payload["diagnosis_id"] = seed["diagnosis_id"]
|
||||
payload["appointment_id"] = seed["appointment_id"]
|
||||
payload["case_record"] = deepcopy(case_record)
|
||||
frozen_payload = MappingProxyType(payload)
|
||||
self._mutation_pending = True
|
||||
self._action_generation += 1
|
||||
generation = self._action_generation
|
||||
saved_draft = getattr(dialog, "saved_draft", None)
|
||||
if saved_draft is not None:
|
||||
self._prescription_created(generation, saved_draft)
|
||||
return
|
||||
payload = dialog.payload()
|
||||
self._mutation_pending = True
|
||||
self.banner.show_message("正在提交处方…", "info")
|
||||
run_async(
|
||||
lambda: invoke(self.repository, "create_prescription", prescription=frozen_payload),
|
||||
lambda: save_new(payload),
|
||||
on_success=lambda result: self._prescription_created(generation, result),
|
||||
on_error=lambda error: self._action_error(error, generation),
|
||||
on_finished=lambda: self._mutation_finished(generation),
|
||||
|
||||
@@ -48,17 +48,27 @@ from ..diagnosis_index_widgets import (
|
||||
DiagnosisLoadingOverlay,
|
||||
DiagnosisTableHost,
|
||||
FlowWidget,
|
||||
can_void_prescription,
|
||||
prescription_action,
|
||||
video_call_is_live,
|
||||
)
|
||||
from ..dialogs import DiagnosisDialog
|
||||
from ..dialogs.ai_consult import can_open_ai_consult, present_ai_consult
|
||||
from ..dialogs.prescription import (
|
||||
PRESCRIPTION_VOIDED_RESULT,
|
||||
PrescriptionDetailDialog,
|
||||
PrescriptionEditorDialog,
|
||||
build_prescription_clinical_diagnosis,
|
||||
build_prescription_visit_no,
|
||||
can_reissue_prescription,
|
||||
can_void_issued_prescription,
|
||||
confirm_prescription_void,
|
||||
prescription_edit_is_locked,
|
||||
prescription_is_voided,
|
||||
prescription_matches_appointment,
|
||||
reissue_prescription_seed,
|
||||
)
|
||||
from ..dialogs.prescription_esign import resume_saved_prescription, saved_prescription_message
|
||||
from ..filter_disclosure import FilterDisclosure
|
||||
from ..infinite_list import InfiniteList
|
||||
from ..theme import mark_business_dialog
|
||||
@@ -319,16 +329,6 @@ def prescription_action_label(record: Any) -> str:
|
||||
return prescription_action(record)[0]
|
||||
|
||||
|
||||
def can_void_prescription(record: Any) -> bool:
|
||||
if record is None:
|
||||
return False
|
||||
if _as_int(first_value(record, "prescription_void_status", "void_status"), 0) == 1:
|
||||
return False
|
||||
if _as_int(first_value(record, "prescription_audit_status", "audit_status"), -1) == 1:
|
||||
return False
|
||||
return not _as_bool(first_value(record, "has_prescription_order", default=False))
|
||||
|
||||
|
||||
def _status_value(row: Any) -> tuple[str, str]:
|
||||
status = _as_int(_appointment_status(row), -1)
|
||||
fallback = APPOINTMENT_STATUS.get(status)
|
||||
@@ -2365,6 +2365,7 @@ class ConsultationsPage(QWidget):
|
||||
"view": self._open_readonly,
|
||||
"edit": self._open_edit,
|
||||
"prescription": self._open_prescription,
|
||||
"void_prescription": self._void_selected_prescription,
|
||||
"ai_consult": self._open_ai_consult,
|
||||
"appointment": self._book_selected_appointment,
|
||||
"fill_id_card": self._fill_selected_id_card,
|
||||
@@ -3226,7 +3227,7 @@ class ConsultationsPage(QWidget):
|
||||
return deepcopy(detail)
|
||||
|
||||
def _open_prescription(self) -> None:
|
||||
if not _canonical_allowed(self.permissions, "tcm.diagnosis/kaifang"):
|
||||
if self._mutation_pending or self._prescription_busy or not _canonical_allowed(self.permissions, "tcm.diagnosis/kaifang"):
|
||||
return
|
||||
record = self.table.current_data()
|
||||
if _as_int(first_value(record, "diagnosis_id", "id", default=0)) <= 0:
|
||||
@@ -3238,7 +3239,7 @@ class ConsultationsPage(QWidget):
|
||||
self._begin_prescription_load(record, mode=mode)
|
||||
|
||||
def _void_selected_prescription(self) -> None:
|
||||
if not _canonical_allowed(self.permissions, "tcm.diagnosis/kaifang"):
|
||||
if self._mutation_pending or self._prescription_busy or not _canonical_allowed(self.permissions, "tcm.diagnosis/kaifang"):
|
||||
return
|
||||
record = self.table.current_data()
|
||||
if record is None or not can_void_prescription(record):
|
||||
@@ -3267,35 +3268,32 @@ class ConsultationsPage(QWidget):
|
||||
return
|
||||
self.banner.clear()
|
||||
self._last_prescription = existing
|
||||
if mode == "void":
|
||||
self._confirm_void(existing)
|
||||
return
|
||||
if existing is not None:
|
||||
approved = _as_int(first_value(existing, "audit_status", "status"), -1) == 1
|
||||
voided = _as_int(first_value(existing, "void_status", "is_void"), 0) == 1
|
||||
voided = prescription_is_voided(existing)
|
||||
actual_id = _as_int(first_value(existing, "id", "prescription_id", default=0))
|
||||
expected_id = _as_int(
|
||||
first_value(record, "current_prescription_id", default=0)
|
||||
)
|
||||
actual_appointment_id = _as_int(
|
||||
first_value(existing, "appointment_id", default=0)
|
||||
)
|
||||
expected_appointment_id = _appointment_id(record)
|
||||
identity_changed = (
|
||||
(expected_id > 0 and actual_id != expected_id)
|
||||
or (
|
||||
actual_appointment_id > 0
|
||||
and expected_appointment_id > 0
|
||||
and actual_appointment_id != expected_appointment_id
|
||||
)
|
||||
)
|
||||
if mode == "view" and (not approved or voided or identity_changed):
|
||||
if not prescription_matches_appointment(
|
||||
existing, appointment_id=_appointment_id(record),
|
||||
diagnosis_id=_as_int(first_value(record, "diagnosis_id", "id")), previous_id=expected_id,
|
||||
):
|
||||
self.banner.show_message("返回的处方与当前挂号不一致,已停止操作。", "warning")
|
||||
return
|
||||
if mode == "view" and (not approved or voided):
|
||||
self.banner.show_message(
|
||||
"当前挂号的处方状态已变化,请刷新列表后重试。",
|
||||
"warning",
|
||||
)
|
||||
return
|
||||
if not approved or voided:
|
||||
current_changed = expected_id > 0 and actual_id != expected_id
|
||||
if mode == "void":
|
||||
self._confirm_void(existing, current_changed=current_changed)
|
||||
return
|
||||
if voided and can_reissue_prescription(existing, self.current_user, self.permissions):
|
||||
self._open_new_prescription(reissue_prescription_seed(existing))
|
||||
elif not approved and not prescription_edit_is_locked(existing):
|
||||
self._open_existing_prescription_editor(existing)
|
||||
else:
|
||||
detail = PrescriptionDetailDialog(
|
||||
@@ -3303,12 +3301,16 @@ class ConsultationsPage(QWidget):
|
||||
can_open_diagnosis=_canonical_allowed(
|
||||
self.permissions, "tcm.diagnosis/readonlyDetail"
|
||||
),
|
||||
allow_void=True,
|
||||
parent=self,
|
||||
)
|
||||
detail.diagnosis_requested.connect(self._open_diagnosis_id)
|
||||
detail.exec()
|
||||
if detail.exec() == PRESCRIPTION_VOIDED_RESULT:
|
||||
self._after_prescription_void()
|
||||
if current_changed and not self._mutation_pending:
|
||||
self.refresh(silent=True)
|
||||
return
|
||||
if mode == "view":
|
||||
if mode in {"view", "void", "reissue"}:
|
||||
self.banner.show_message(
|
||||
"当前挂号没有可查看的处方,请刷新列表后重试。",
|
||||
"warning",
|
||||
@@ -3321,28 +3323,29 @@ class ConsultationsPage(QWidget):
|
||||
if prescription_id <= 0:
|
||||
self.banner.show_message("处方编号不完整,无法编辑。", "danger")
|
||||
return
|
||||
|
||||
def save_changes(payload: Any) -> Any:
|
||||
return invoke(self.repository, "update_prescription", prescription=prescription_id, changes=payload)
|
||||
|
||||
dialog = PrescriptionEditorDialog(
|
||||
self.repository,
|
||||
prescription,
|
||||
mode="edit",
|
||||
current_user=self.current_user,
|
||||
save_draft=save_changes,
|
||||
allow_void=True,
|
||||
parent=self,
|
||||
)
|
||||
diagnosis_signal = getattr(dialog, "diagnosis_requested", None)
|
||||
if diagnosis_signal is not None:
|
||||
diagnosis_signal.connect(self._open_diagnosis_id)
|
||||
if dialog.exec() != QDialog.DialogCode.Accepted:
|
||||
result = dialog.exec()
|
||||
if result == PRESCRIPTION_VOIDED_RESULT:
|
||||
self._after_prescription_void()
|
||||
return
|
||||
frozen_payload = MappingProxyType(dialog.payload())
|
||||
self._run_mutation(
|
||||
lambda: invoke(
|
||||
self.repository,
|
||||
"update_prescription",
|
||||
prescription=prescription_id,
|
||||
changes=frozen_payload,
|
||||
),
|
||||
"处方已保存并重新进入待审核。",
|
||||
)
|
||||
if result != QDialog.DialogCode.Accepted:
|
||||
return
|
||||
self._finish_prescription_edit(dialog, save_changes, "处方已保存并重新进入待审核。")
|
||||
|
||||
def _begin_case_record_load(self, record: Any) -> None:
|
||||
record_snapshot = deepcopy(record)
|
||||
@@ -3427,12 +3430,20 @@ class ConsultationsPage(QWidget):
|
||||
}
|
||||
|
||||
def _open_prescription_editor(self, record: Any, case_record: Any) -> None:
|
||||
seed = self._prescription_seed(record, case_record)
|
||||
self._open_new_prescription(self._prescription_seed(record, case_record))
|
||||
|
||||
def _open_new_prescription(self, seed: dict[str, Any]) -> None:
|
||||
linked_fields = {key: seed[key] for key in ("diagnosis_id", "appointment_id", "case_record") if key in seed}
|
||||
|
||||
def save_new(payload: dict[str, Any]) -> Any:
|
||||
return invoke(self.repository, "create_prescription", prescription=MappingProxyType(dict(payload) | linked_fields))
|
||||
|
||||
dialog = PrescriptionEditorDialog(
|
||||
self.repository,
|
||||
seed,
|
||||
mode="add",
|
||||
current_user=self.current_user,
|
||||
save_draft=save_new,
|
||||
parent=self,
|
||||
)
|
||||
diagnosis_signal = getattr(dialog, "diagnosis_requested", None)
|
||||
@@ -3440,17 +3451,27 @@ class ConsultationsPage(QWidget):
|
||||
diagnosis_signal.connect(self._open_diagnosis_id)
|
||||
if dialog.exec() != QDialog.DialogCode.Accepted:
|
||||
return
|
||||
payload = dialog.payload()
|
||||
payload["diagnosis_id"] = seed["diagnosis_id"]
|
||||
payload["appointment_id"] = seed["appointment_id"]
|
||||
payload["case_record"] = deepcopy(case_record)
|
||||
frozen_payload = MappingProxyType(payload)
|
||||
self._run_mutation(
|
||||
lambda: invoke(self.repository, "create_prescription", prescription=frozen_payload),
|
||||
"处方已开具并提交审核。",
|
||||
)
|
||||
self._finish_prescription_edit(dialog, save_new, "处方已开具并提交审核。")
|
||||
|
||||
def _finish_prescription_edit(self, dialog: PrescriptionEditorDialog, save: Any, message: str) -> None:
|
||||
saved = getattr(dialog, "saved_draft", None)
|
||||
if saved is not None:
|
||||
self._prescription_saved(saved, message)
|
||||
return
|
||||
payload = MappingProxyType(dialog.payload())
|
||||
self._run_mutation(lambda: save(payload), message, on_saved=self._prescription_saved)
|
||||
|
||||
def _prescription_saved(self, prescription: Any, fallback: str) -> None:
|
||||
message, kind = saved_prescription_message(prescription, fallback)
|
||||
show_toast(self, message, kind)
|
||||
self.refresh(silent=True)
|
||||
resume_saved_prescription(self.repository, prescription, self)
|
||||
|
||||
def _after_prescription_void(self) -> None:
|
||||
show_toast(self, "处方已作废。需要再次开具时,请选择「重新开方」。", "success")
|
||||
self.refresh(silent=True)
|
||||
|
||||
def _confirm_void(self, prescription: Any) -> None:
|
||||
def _confirm_void(self, prescription: Any, *, current_changed: bool = False) -> None:
|
||||
if prescription is None:
|
||||
self.banner.show_message("当前诊单没有可作废的处方。", "warning")
|
||||
return
|
||||
@@ -3460,21 +3481,14 @@ class ConsultationsPage(QWidget):
|
||||
if _as_int(first_value(prescription, "void_status", "is_void"), 0) == 1:
|
||||
self.banner.show_message("该处方已经作废。", "warning")
|
||||
return
|
||||
if _as_int(first_value(prescription, "audit_status", "status"), -1) == 1:
|
||||
self.banner.show_message("审核通过且有效的处方仅供查看,不能在此作废。", "warning")
|
||||
return
|
||||
prescription_id = _as_int(first_value(prescription, "id", "prescription_id"))
|
||||
if prescription_id <= 0:
|
||||
self.banner.show_message("处方信息不完整,无法作废。", "warning")
|
||||
return
|
||||
answer = QMessageBox.warning(
|
||||
self,
|
||||
"作废处方",
|
||||
"确定作废该处方吗?作废后不可恢复。",
|
||||
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.Cancel,
|
||||
QMessageBox.StandardButton.Cancel,
|
||||
)
|
||||
if answer != QMessageBox.StandardButton.Yes:
|
||||
if not can_void_issued_prescription(prescription):
|
||||
self.banner.show_message("当前处方不可作废,请核对操作权限和订单状态。", "warning")
|
||||
return
|
||||
if not confirm_prescription_void(self, prescription, current_changed=current_changed):
|
||||
return
|
||||
self._run_mutation(
|
||||
lambda: invoke(
|
||||
@@ -3483,19 +3497,26 @@ class ConsultationsPage(QWidget):
|
||||
prescription_id=prescription_id,
|
||||
id=prescription_id,
|
||||
),
|
||||
"处方已作废。",
|
||||
"处方已作废。需要再次开具时,请选择「重新开方」。",
|
||||
)
|
||||
|
||||
def _run_mutation(self, operation: Any, success_message: str) -> None:
|
||||
def _run_mutation(self, operation: Any, success_message: str, *, on_saved: Any = None) -> None:
|
||||
self._mutation_generation += 1
|
||||
generation = self._mutation_generation
|
||||
self._mutation_pending = True
|
||||
self.table_host.setEnabled(False)
|
||||
self._checked_changed(len(self.table_host.selected_records()))
|
||||
self._selection_changed()
|
||||
def succeeded(result: Any) -> None:
|
||||
if on_saved is None:
|
||||
self._mutation_success(success_message, generation)
|
||||
elif generation == self._mutation_generation:
|
||||
self.table_host.clear_checks()
|
||||
on_saved(result, success_message)
|
||||
|
||||
run_async(
|
||||
operation,
|
||||
on_success=lambda _result: self._mutation_success(success_message, generation),
|
||||
on_success=succeeded,
|
||||
on_error=lambda error: self._mutation_error(error, generation),
|
||||
on_finished=lambda: self._mutation_finished(generation),
|
||||
)
|
||||
|
||||
@@ -48,12 +48,14 @@ from ...core.appointment_modes import (
|
||||
appointment_type_description,
|
||||
appointment_type_value,
|
||||
)
|
||||
from ...core.esign import esign_status
|
||||
from .. import icons
|
||||
from ..appointment_drawer import AppointmentDrawer
|
||||
from ..design_system import PALETTE, clinical_stylesheet
|
||||
from ..dialogs import DiagnosisDialog, present_ai_consult, present_order_detail
|
||||
from ..dialogs.ai_consult import can_open_ai_consult
|
||||
from ..dialogs.prescription import PrescriptionOrderListDialog
|
||||
from ..dialogs.prescription_esign import PrescriptionEsignDialog, can_continue_prescription_esign
|
||||
from ..filter_disclosure import FilterDisclosure
|
||||
from ..infinite_list import InfiniteList
|
||||
from ..patient_orders_style import patient_orders_stylesheet
|
||||
@@ -3185,6 +3187,7 @@ class PatientsPage(QWidget):
|
||||
self._detail_generation = 0
|
||||
self._edit_generation = 0
|
||||
self._assistant_generation = 0
|
||||
self._order_review_generation = 0
|
||||
|
||||
root = QVBoxLayout(self)
|
||||
root.setContentsMargins(28, 8, 26, 8)
|
||||
@@ -3647,6 +3650,63 @@ class PatientsPage(QWidget):
|
||||
if generation == self._edit_generation:
|
||||
self.order_workspace.banner.show_message(friendly_error(error), "danger")
|
||||
|
||||
def _submit_order_audit(self, order_id: int, *, prescription: bool, action: str) -> None:
|
||||
label = "处方审核" if prescription else "支付单审核"
|
||||
remark, accepted = QInputDialog.getText(self, label, "审核备注:")
|
||||
if not accepted:
|
||||
return
|
||||
if action == "reject" and not remark.strip():
|
||||
show_toast(self, "驳回时必须填写审核意见。", "danger")
|
||||
return
|
||||
method = "audit_patient_order_prescription" if prescription else "audit_patient_order_payment"
|
||||
self._run_action(
|
||||
"正在处理订单…",
|
||||
lambda: _invoke_first(
|
||||
self.repository, (method,), order_id=order_id, action=action, remark=remark.strip()
|
||||
),
|
||||
success=f"{label}已提交。",
|
||||
)
|
||||
|
||||
def _check_order_signature_before_approval(self, row: Any, order_id: int) -> None:
|
||||
status_method = getattr(self.repository, "get_prescription_esign_status", None)
|
||||
if not callable(status_method):
|
||||
self._submit_order_audit(order_id, prescription=True, action="approve")
|
||||
return
|
||||
prescription_id = _as_int(first_value(row, "prescription_id"))
|
||||
if prescription_id <= 0:
|
||||
self.order_workspace.banner.show_message("找不到此订单的处方,请刷新订单后重试。", "warning")
|
||||
return
|
||||
self._order_review_generation += 1
|
||||
generation = self._order_review_generation
|
||||
self.order_workspace.banner.show_message("正在核对关联处方的签署状态…", "info")
|
||||
|
||||
def failed(error: Exception) -> None:
|
||||
if self._order_review_generation == generation:
|
||||
self.order_workspace.banner.show_message(f"未能核对签署状态。{friendly_error(error)}", "warning")
|
||||
|
||||
def checked(state: dict[str, Any]) -> None:
|
||||
if self._order_review_generation != generation:
|
||||
return
|
||||
verified = state["required"] and state["status"] == "signed" and state["can_download"]
|
||||
historical = not state["required"] and state["status"] == "legacy" and not state["can_download"]
|
||||
if verified or historical:
|
||||
self.order_workspace.banner.clear()
|
||||
self._submit_order_audit(order_id, prescription=True, action="approve")
|
||||
return
|
||||
if can_continue_prescription_esign(state, self.permissions):
|
||||
dialog = PrescriptionEsignDialog(self.repository, {"id": prescription_id, "esign": state}, parent=self)
|
||||
dialog.exec()
|
||||
self.order_workspace.banner.show_message("请在签署验签通过后,再点击处方审核。", "info")
|
||||
self.order_workspace.refresh(silent=True)
|
||||
else:
|
||||
message = state.get("message") or (
|
||||
"签署原件暂不可用,请联系管理员核验。" if state["status"] == "signed"
|
||||
else "请开方医生完成处方签署并通过验签,再审核通过。"
|
||||
)
|
||||
self.order_workspace.banner.show_message(str(message), "warning")
|
||||
|
||||
run_async(lambda: esign_status(status_method(prescription_id)), on_success=checked, on_error=failed)
|
||||
|
||||
def _handle_order_action(self, key: str, row: Any) -> None:
|
||||
allowed_keys = {item[0] for item in self.order_workspace._available_actions(row)}
|
||||
if key not in allowed_keys:
|
||||
@@ -3662,35 +3722,20 @@ class PatientsPage(QWidget):
|
||||
call: Any
|
||||
success = "订单已更新。"
|
||||
if key in {"audit_prescription", "audit_payment"}:
|
||||
label = "处方审核" if key == "audit_prescription" else "支付单审核"
|
||||
self._order_review_generation += 1
|
||||
prescription = key == "audit_prescription"
|
||||
label = "处方审核" if prescription else "支付单审核"
|
||||
action_label, accepted = QInputDialog.getItem(
|
||||
self, label, "审核结果:", ["通过", "驳回"], 0, False
|
||||
)
|
||||
if not accepted:
|
||||
return
|
||||
remark, accepted = QInputDialog.getText(self, label, "审核备注:")
|
||||
if not accepted:
|
||||
return
|
||||
method = (
|
||||
"audit_patient_order_prescription"
|
||||
if key == "audit_prescription"
|
||||
else "audit_patient_order_payment"
|
||||
)
|
||||
action = "approve" if action_label == "通过" else "reject"
|
||||
if action == "reject" and not remark.strip():
|
||||
show_toast(self, "驳回时必须填写审核意见。", "danger")
|
||||
return
|
||||
|
||||
def call() -> Any:
|
||||
return _invoke_first(
|
||||
self.repository,
|
||||
(method,),
|
||||
order_id=order_id,
|
||||
action=action,
|
||||
remark=remark.strip(),
|
||||
)
|
||||
|
||||
success = f"{label}已提交。"
|
||||
if prescription and action == "approve":
|
||||
self._check_order_signature_before_approval(row, order_id)
|
||||
else:
|
||||
self._submit_order_audit(order_id, prescription=prescription, action=action)
|
||||
return
|
||||
elif key in {"revoke_rx_audit", "revoke_pay_audit", "withdraw", "upload_pharmacy"}:
|
||||
labels = {
|
||||
"revoke_rx_audit": "撤回处方审核",
|
||||
@@ -3833,6 +3878,7 @@ class PatientsPage(QWidget):
|
||||
self.refresh()
|
||||
|
||||
def hideEvent(self, event: Any) -> None:
|
||||
self._order_review_generation += 1
|
||||
self.progress_workspace.set_active(False)
|
||||
super().hideEvent(event)
|
||||
|
||||
|
||||
@@ -62,6 +62,7 @@ from PySide6.QtWidgets import (
|
||||
QWidget,
|
||||
)
|
||||
|
||||
from ...core.esign import esign_status
|
||||
from .. import icons, motion
|
||||
from ..design_system import PALETTE, clinical_stylesheet
|
||||
from ..dialogs.issued_prescription_ai import (
|
||||
@@ -75,6 +76,7 @@ from ..dialogs.issued_prescription_ai import (
|
||||
status_tooltip,
|
||||
)
|
||||
from ..dialogs.prescription import (
|
||||
PRESCRIBE_PERMISSIONS,
|
||||
AuditPrescriptionDialog,
|
||||
DiagnosisDetailDialog,
|
||||
PatchPatientDialog,
|
||||
@@ -82,9 +84,20 @@ from ..dialogs.prescription import (
|
||||
PrescriptionEditorDialog,
|
||||
PrescriptionOrderDialog,
|
||||
PrescriptionOrderListDialog,
|
||||
can_reissue_prescription,
|
||||
can_void_issued_prescription,
|
||||
confirm_prescription_void,
|
||||
prescription_edit_is_locked,
|
||||
reissue_prescription_seed,
|
||||
)
|
||||
from ..dialogs.prescription_esign import (
|
||||
PrescriptionEsignDialog,
|
||||
can_continue_prescription_esign,
|
||||
resume_saved_prescription,
|
||||
saved_prescription_message,
|
||||
signature_state,
|
||||
)
|
||||
from ..filter_disclosure import FilterDisclosure
|
||||
from ..dialogs.prescription_esign import resume_saved_prescription, saved_prescription_message
|
||||
from ..infinite_list import InfiniteList
|
||||
from ..prescriptions_style import prescriptions_stylesheet
|
||||
from ..reception_style import body_family, heading_family
|
||||
@@ -364,7 +377,8 @@ def _row_action_button(
|
||||
button.setAccessibleName(tooltip)
|
||||
button.setToolTip(tooltip)
|
||||
button.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||
button.setFixedSize(64 if label else 28, 28)
|
||||
width = max(64, button.fontMetrics().horizontalAdvance(label) + 26) if label else 28
|
||||
button.setFixedSize(width, 28)
|
||||
button.setIcon(_painted_icon(kind, "danger" if danger else "accent", 15))
|
||||
button.setIconSize(QSize(15, 15))
|
||||
button.setEnabled(enabled)
|
||||
@@ -424,6 +438,13 @@ def prescription_status(row: Any) -> tuple[str, str]:
|
||||
return "已驳回", "danger"
|
||||
if status == 1:
|
||||
return "已通过", "success"
|
||||
signature = signature_state(row)
|
||||
if signature.get("required") is True and signature.get("status") not in {"signed", "voided"}:
|
||||
if signature.get("status") == "signing":
|
||||
return "签名处理中", "warning"
|
||||
if signature.get("status") == "uncertain":
|
||||
return ("待验签" if signature.get("can_retry_verify") is True else "签署结果待确认", "warning")
|
||||
return "待签名", "warning"
|
||||
return "待审核", "warning"
|
||||
|
||||
|
||||
@@ -444,7 +465,7 @@ def can_create_order(row: Any) -> bool:
|
||||
)
|
||||
|
||||
|
||||
def can_audit(row: Any) -> bool:
|
||||
def _is_pending_audit(row: Any) -> bool:
|
||||
return (
|
||||
row is not None
|
||||
and _int(first_value(row, "audit_status", "status"), 0) == 0
|
||||
@@ -452,10 +473,23 @@ def can_audit(row: Any) -> bool:
|
||||
)
|
||||
|
||||
|
||||
def can_audit(row: Any) -> bool:
|
||||
signature = 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:
|
||||
return row is not None and not is_approved_active(row)
|
||||
|
||||
|
||||
def _voided(row: Any) -> bool:
|
||||
return _int(first_value(row, "void_status", "is_void"), 0) == 1
|
||||
|
||||
|
||||
def _can_change_issued_prescription(row: Any) -> bool:
|
||||
return can_edit_or_delete(row) and not prescription_edit_is_locked(row)
|
||||
|
||||
|
||||
def _formula(value: Any) -> str:
|
||||
text = str(value or "").strip().lower()
|
||||
return "辅方" if text in {"2", "aux", "auxiliary", "辅方"} else "主方"
|
||||
@@ -593,7 +627,7 @@ def _audit_cell(_value: Any, row: Any) -> str:
|
||||
|
||||
|
||||
def _void_cell(_value: Any, row: Any) -> str:
|
||||
return "作废" if _int(first_value(row, "void_status", "is_void"), 0) == 1 else "—"
|
||||
return "作废" if _voided(row) else "—"
|
||||
|
||||
|
||||
def _doctor_cell(_value: Any, row: Any) -> str:
|
||||
@@ -1198,6 +1232,7 @@ class PrescriptionsPage(QWidget):
|
||||
self._diagnosis_detail_generation = 0
|
||||
self._diagnosis_detail_target = 0
|
||||
self._mutation_pending = False
|
||||
self._audit_check_pending = False
|
||||
self._ai_statuses: dict[int, dict[str, Any]] = {}
|
||||
self._ai_enabled = False
|
||||
self._agreement_visible = False
|
||||
@@ -1411,6 +1446,10 @@ class PrescriptionsPage(QWidget):
|
||||
"审核", "cf.prescription/audit", self._audit_selected
|
||||
)
|
||||
toolbar.addWidget(self.audit_button)
|
||||
self.void_button = self._action_button("作废", None, self._void_selected, danger=True)
|
||||
toolbar.addWidget(self.void_button)
|
||||
self.reissue_button = self._action_button("重新开方", None, self._reissue_selected)
|
||||
toolbar.addWidget(self.reissue_button)
|
||||
self.delete_button = self._action_button(
|
||||
"删除", "cf.prescription/del", self._delete_selected, danger=True
|
||||
)
|
||||
@@ -1549,7 +1588,7 @@ class PrescriptionsPage(QWidget):
|
||||
def _action_button(
|
||||
self,
|
||||
text: str,
|
||||
permission: str,
|
||||
permission: str | None,
|
||||
handler: Callable[[], None],
|
||||
*,
|
||||
danger: bool = False,
|
||||
@@ -1562,6 +1601,7 @@ class PrescriptionsPage(QWidget):
|
||||
"查看": "eye",
|
||||
"编辑": "pencil",
|
||||
"删除": "trash",
|
||||
"重新开方": "plus",
|
||||
}.get(text)
|
||||
if icon_kind:
|
||||
button.setIcon(
|
||||
@@ -1570,7 +1610,7 @@ class PrescriptionsPage(QWidget):
|
||||
button.setIconSize(QSize(15, 15))
|
||||
if danger:
|
||||
button.setProperty("variant", "danger")
|
||||
button.setVisible(has_permission(self.permissions, permission))
|
||||
button.setVisible(permission is not None and has_permission(self.permissions, permission))
|
||||
button.setEnabled(False)
|
||||
button.clicked.connect(handler)
|
||||
return button
|
||||
@@ -1708,6 +1748,7 @@ class PrescriptionsPage(QWidget):
|
||||
self.table.setUpdatesEnabled(True)
|
||||
|
||||
def _decorate_rows_locked(self) -> None:
|
||||
action_width = max(self.table.columnWidth(2), 178 if self._ai_enabled else 144)
|
||||
for row_index in range(self.table.rowCount()):
|
||||
selector = self.table.item(row_index, 0)
|
||||
if selector is None:
|
||||
@@ -1786,7 +1827,10 @@ class PrescriptionsPage(QWidget):
|
||||
actions_host, label="AI",
|
||||
)
|
||||
)
|
||||
if has_permission(self.permissions, "cf.prescription/edit"):
|
||||
can_reissue = self._can_reissue(row)
|
||||
can_change = _can_change_issued_prescription(row)
|
||||
show_changes = can_change or not _voided(row)
|
||||
if show_changes and has_permission(self.permissions, "cf.prescription/edit"):
|
||||
actions.addWidget(
|
||||
_row_action_button(
|
||||
"pencil",
|
||||
@@ -1795,12 +1839,28 @@ class PrescriptionsPage(QWidget):
|
||||
target, self._edit_selected
|
||||
),
|
||||
actions_host,
|
||||
enabled=can_edit_or_delete(row),
|
||||
enabled=can_change,
|
||||
label="编辑",
|
||||
mutation=True,
|
||||
)
|
||||
)
|
||||
if has_permission(self.permissions, "cf.prescription/del"):
|
||||
if self._can_void(row):
|
||||
actions.addWidget(
|
||||
_row_action_button(
|
||||
"close", "作废处方",
|
||||
lambda _checked=False, target=row: self._run_row_action(target, self._void_selected),
|
||||
actions_host, danger=True, label="作废", mutation=True,
|
||||
)
|
||||
)
|
||||
if can_reissue:
|
||||
actions.addWidget(
|
||||
_row_action_button(
|
||||
"plus", "重新开方",
|
||||
lambda _checked=False, target=row: self._run_row_action(target, self._reissue_selected),
|
||||
actions_host, label="重新开方", mutation=True,
|
||||
)
|
||||
)
|
||||
if show_changes and has_permission(self.permissions, "cf.prescription/del"):
|
||||
actions.addWidget(
|
||||
_row_action_button(
|
||||
"trash",
|
||||
@@ -1810,12 +1870,14 @@ class PrescriptionsPage(QWidget):
|
||||
),
|
||||
actions_host,
|
||||
danger=True,
|
||||
enabled=can_edit_or_delete(row),
|
||||
enabled=can_change,
|
||||
mutation=True,
|
||||
)
|
||||
)
|
||||
actions.addStretch(1)
|
||||
action_width = max(action_width, actions.sizeHint().width() + 4)
|
||||
self.table.setCellWidget(row_index, 2, actions_host)
|
||||
self.table.setColumnWidth(2, action_width)
|
||||
self._sync_row_mutation_actions()
|
||||
self.table.resizeRowsToContents()
|
||||
|
||||
@@ -1894,7 +1956,6 @@ class PrescriptionsPage(QWidget):
|
||||
header.moveSection(header.visualIndex(12), header.visualIndex(11) + 1)
|
||||
self.table.setColumnWidth(11, 144)
|
||||
self.table.setColumnWidth(12, 130)
|
||||
self.table.setColumnWidth(2, 178)
|
||||
if changed:
|
||||
self._decorate_rows()
|
||||
|
||||
@@ -2091,9 +2152,27 @@ class PrescriptionsPage(QWidget):
|
||||
self.ai_report_button.setEnabled(ai_available)
|
||||
self.patch_button.setEnabled(active and can_patch_patient(row))
|
||||
self.create_order_button.setEnabled(active and can_create_order(row))
|
||||
self.edit_button.setEnabled(active and can_edit_or_delete(row))
|
||||
self.audit_button.setEnabled(active and can_audit(row))
|
||||
self.delete_button.setEnabled(active and can_edit_or_delete(row))
|
||||
can_change = _can_change_issued_prescription(row)
|
||||
self.edit_button.setEnabled(active and can_change)
|
||||
pending_audit = _is_pending_audit(row)
|
||||
can_review = has_permission(self.permissions, "cf.prescription/audit")
|
||||
can_sign = pending_audit and can_continue_prescription_esign(signature_state(row), self.permissions)
|
||||
self.audit_button.setText("继续签署" if can_sign else "审核")
|
||||
self.audit_button.setVisible(can_review or can_sign)
|
||||
self.audit_button.setEnabled(active and not self._audit_check_pending and pending_audit and (can_review or can_sign))
|
||||
can_void = self._can_void(row)
|
||||
self.void_button.setVisible(can_void)
|
||||
self.void_button.setEnabled(active and can_void)
|
||||
can_reissue = self._can_reissue(row)
|
||||
self.reissue_button.setVisible(can_reissue)
|
||||
self.reissue_button.setEnabled(active and can_reissue)
|
||||
self.delete_button.setEnabled(active and can_change)
|
||||
|
||||
def _can_void(self, row: Any) -> bool:
|
||||
return can_void_issued_prescription(row)
|
||||
|
||||
def _can_reissue(self, row: Any) -> bool:
|
||||
return can_reissue_prescription(row, self.current_user, self.permissions)
|
||||
|
||||
def _set_mutation_pending(self, pending: bool) -> None:
|
||||
self._mutation_pending = pending
|
||||
@@ -2164,9 +2243,10 @@ class PrescriptionsPage(QWidget):
|
||||
row = self._selected()
|
||||
if row is None or not has_permission(self.permissions, "cf.prescription/read"):
|
||||
return
|
||||
self._load_detail(row, self._show_detail)
|
||||
was_signed = signature_state(row).get("status") == "signed"
|
||||
self._load_detail(row, lambda detail: self._show_detail(detail, was_signed=was_signed))
|
||||
|
||||
def _show_detail(self, detail: Any) -> None:
|
||||
def _show_detail(self, detail: Any, *, was_signed: bool = False) -> None:
|
||||
if not has_permission(self.permissions, "cf.prescription/read"):
|
||||
return
|
||||
dialog = PrescriptionDetailDialog(
|
||||
@@ -2178,6 +2258,8 @@ class PrescriptionsPage(QWidget):
|
||||
dialog.diagnosis_requested.connect(self._open_diagnosis)
|
||||
dialog.orders_requested.connect(lambda prescription_id: self._open_orders(prescription_id))
|
||||
dialog.exec()
|
||||
if not was_signed and dialog.esign.get("status") == "signed":
|
||||
self.refresh()
|
||||
|
||||
def _open_diagnosis(self, diagnosis_id: int) -> None:
|
||||
if not has_permission(self.permissions, "tcm.diagnosis/readonlyDetail"):
|
||||
@@ -2231,17 +2313,60 @@ class PrescriptionsPage(QWidget):
|
||||
self.banner.show_message(friendly_error(error), "danger")
|
||||
|
||||
def _add_prescription(self) -> None:
|
||||
if not has_permission(self.permissions, "cf.prescription/add"):
|
||||
if has_permission(self.permissions, "cf.prescription/add"):
|
||||
self._open_new_prescription()
|
||||
|
||||
def _open_new_prescription(self, seed: dict[str, Any] | None = None) -> None:
|
||||
if self._mutation_pending or not has_permission(self.permissions, PRESCRIBE_PERMISSIONS):
|
||||
return
|
||||
dialog = PrescriptionEditorDialog(
|
||||
self.repository,
|
||||
seed,
|
||||
mode="add",
|
||||
current_user=self.current_user,
|
||||
save_draft=lambda payload: self.repository.create_prescription(payload),
|
||||
parent=self,
|
||||
)
|
||||
dialog.diagnosis_requested.connect(self._open_diagnosis)
|
||||
if dialog.exec() == QDialog.DialogCode.Accepted:
|
||||
self._save_prescription(dialog.payload(), None)
|
||||
saved = getattr(dialog, "saved_draft", None)
|
||||
if saved is not None:
|
||||
self._prescription_saved(saved, "处方已新增并提交审核。")
|
||||
else:
|
||||
self._save_prescription(dialog.payload(), None)
|
||||
|
||||
def _void_selected(self) -> None:
|
||||
row = self._selected()
|
||||
if self._mutation_pending or not self._can_void(row):
|
||||
return
|
||||
prescription_id = _int(first_value(row, "id", "prescription_id"))
|
||||
if prescription_id <= 0:
|
||||
self.banner.show_message("处方 ID 无效,请刷新列表后重试。", "warning")
|
||||
return
|
||||
if not confirm_prescription_void(self, row):
|
||||
return
|
||||
self._set_mutation_pending(True)
|
||||
run_async(
|
||||
lambda: self.repository.void_prescription(prescription_id),
|
||||
on_success=lambda _result: self._mutation_success("处方已作废。"),
|
||||
on_error=self._mutation_error,
|
||||
on_finished=lambda: self._set_mutation_pending(False),
|
||||
)
|
||||
|
||||
def _reissue_selected(self) -> None:
|
||||
row = self._selected()
|
||||
if self._mutation_pending or not self._can_reissue(row):
|
||||
return
|
||||
self._load_detail(
|
||||
row, lambda detail: self._open_reissue(merge_prescription_detail(row, detail)),
|
||||
message="正在准备重新开方…",
|
||||
)
|
||||
|
||||
def _open_reissue(self, detail: dict[str, Any]) -> None:
|
||||
if not self._can_reissue(detail):
|
||||
self.banner.show_message("该处方当前不可重新开方,请刷新列表后重试。", "warning")
|
||||
return
|
||||
self._open_new_prescription(reissue_prescription_seed(detail))
|
||||
|
||||
def _edit_selected(self) -> None:
|
||||
row = self._selected()
|
||||
@@ -2249,7 +2374,7 @@ class PrescriptionsPage(QWidget):
|
||||
row is None
|
||||
or self._mutation_pending
|
||||
or not has_permission(self.permissions, "cf.prescription/edit")
|
||||
or not can_edit_or_delete(row)
|
||||
or not _can_change_issued_prescription(row)
|
||||
):
|
||||
return
|
||||
self._load_detail(
|
||||
@@ -2259,29 +2384,32 @@ class PrescriptionsPage(QWidget):
|
||||
)
|
||||
|
||||
def _open_editor(self, detail: Any) -> None:
|
||||
if not can_edit_or_delete(detail):
|
||||
if not _can_change_issued_prescription(detail):
|
||||
self.banner.show_message("该处方状态已变化,当前不能编辑。", "warning")
|
||||
return
|
||||
prescription_id = _int(first_value(detail, "id", "prescription_id"), 0)
|
||||
dialog = PrescriptionEditorDialog(
|
||||
self.repository,
|
||||
detail,
|
||||
mode="edit",
|
||||
current_user=self.current_user,
|
||||
save_draft=lambda payload: self.repository.update_prescription(prescription_id, changes=payload),
|
||||
parent=self,
|
||||
)
|
||||
dialog.diagnosis_requested.connect(self._open_diagnosis)
|
||||
if dialog.exec() == QDialog.DialogCode.Accepted:
|
||||
self._save_prescription(
|
||||
dialog.payload(),
|
||||
_int(first_value(detail, "id", "prescription_id"), 0),
|
||||
)
|
||||
saved = getattr(dialog, "saved_draft", None)
|
||||
if saved is not None:
|
||||
self._prescription_saved(saved, "处方已保存并重新进入待审核。")
|
||||
else:
|
||||
self._save_prescription(dialog.payload(), prescription_id)
|
||||
|
||||
def _save_prescription(
|
||||
self,
|
||||
payload: dict[str, Any],
|
||||
prescription_id: int | None,
|
||||
) -> None:
|
||||
permission = "cf.prescription/edit" if prescription_id else "cf.prescription/add"
|
||||
permission = "cf.prescription/edit" if prescription_id else PRESCRIBE_PERMISSIONS
|
||||
if not has_permission(self.permissions, permission):
|
||||
return
|
||||
self._set_mutation_pending(True)
|
||||
@@ -2312,7 +2440,8 @@ class PrescriptionsPage(QWidget):
|
||||
self.banner.show_message(message, kind)
|
||||
show_toast(self, message, kind, 3600)
|
||||
self.refresh()
|
||||
resume_saved_prescription(self.repository, prescription, self)
|
||||
if resume_saved_prescription(self.repository, prescription, self):
|
||||
self._mutation_success("电子签署已完成,处方等待审核。")
|
||||
|
||||
def _delete_selected(self) -> None:
|
||||
row = self._selected()
|
||||
@@ -2320,7 +2449,7 @@ class PrescriptionsPage(QWidget):
|
||||
row is None
|
||||
or self._mutation_pending
|
||||
or not has_permission(self.permissions, "cf.prescription/del")
|
||||
or not can_edit_or_delete(row)
|
||||
or not _can_change_issued_prescription(row)
|
||||
):
|
||||
return
|
||||
answer = QMessageBox.warning(
|
||||
@@ -2371,12 +2500,74 @@ class PrescriptionsPage(QWidget):
|
||||
|
||||
def _audit_selected(self) -> None:
|
||||
row = self._selected()
|
||||
if (
|
||||
row is None
|
||||
or not has_permission(self.permissions, "cf.prescription/audit")
|
||||
or not can_audit(row)
|
||||
):
|
||||
if self._mutation_pending or self._audit_check_pending or not _is_pending_audit(row):
|
||||
return
|
||||
can_review = has_permission(self.permissions, "cf.prescription/audit")
|
||||
signing_action = can_continue_prescription_esign(signature_state(row), self.permissions)
|
||||
if not (can_review or signing_action):
|
||||
return
|
||||
prescription_id = _int(first_value(row, "id", "prescription_id"), 0)
|
||||
if prescription_id <= 0:
|
||||
self.banner.show_message("处方 ID 无效,请刷新列表后重试。", "warning")
|
||||
return
|
||||
status_method = getattr(self.repository, "get_prescription_esign_status", None)
|
||||
if not callable(status_method):
|
||||
self.banner.show_message("无法查询处方签署状态,请联系管理员。", "warning")
|
||||
return
|
||||
|
||||
def checked(state: dict[str, Any]) -> None:
|
||||
selected = self._selected()
|
||||
if (
|
||||
self._mutation_pending
|
||||
or not _is_pending_audit(selected)
|
||||
or _int(first_value(selected, "id", "prescription_id"), 0) != prescription_id
|
||||
):
|
||||
return
|
||||
if can_continue_prescription_esign(state, self.permissions):
|
||||
draft = {**_row_mapping(selected), "id": prescription_id, "esign": state}
|
||||
dialog = PrescriptionEsignDialog(self.repository, draft, parent=self)
|
||||
dialog.exec()
|
||||
if dialog.state.get("status") == "signed":
|
||||
self._mutation_success("电子签署已完成,处方等待审核。")
|
||||
return
|
||||
status = state["status"]
|
||||
if (state["required"] and status == "signed") or (not state["required"] and status == "legacy"):
|
||||
if signing_action:
|
||||
if status == "signed":
|
||||
self._mutation_success("电子签署已完成,处方等待审核。")
|
||||
else:
|
||||
self.refresh()
|
||||
elif can_review:
|
||||
self._open_audit_dialog(selected)
|
||||
return
|
||||
if status == "voided":
|
||||
message = "处方已作废,请刷新列表。"
|
||||
elif _truthy(first_value(selected, "is_system_auto")):
|
||||
message = "请开方医生编辑并补全系统占号处方,再完成电子签署。"
|
||||
elif not state["enabled"]:
|
||||
message = "审核前须完成电子签署。请联系管理员启用签署服务。"
|
||||
elif status == "signing":
|
||||
message = "处方正在电子签署,请稍后再审核。"
|
||||
elif status == "uncertain":
|
||||
message = "请开方医生核对处方签署结果,确认完成后再审核。"
|
||||
else:
|
||||
message = "请开方医生完成电子签署后再审核。"
|
||||
self.banner.show_message(message, "warning")
|
||||
|
||||
def finished() -> None:
|
||||
self._audit_check_pending = False
|
||||
self._selection_changed()
|
||||
|
||||
self._audit_check_pending = True
|
||||
self._selection_changed()
|
||||
run_async(
|
||||
lambda: esign_status(status_method(prescription_id)),
|
||||
on_success=checked,
|
||||
on_error=self._mutation_error,
|
||||
on_finished=finished,
|
||||
)
|
||||
|
||||
def _open_audit_dialog(self, row: Any) -> None:
|
||||
dialog = AuditPrescriptionDialog(row, self)
|
||||
if dialog.exec() != QDialog.DialogCode.Accepted:
|
||||
return
|
||||
|
||||
@@ -63,7 +63,9 @@ from .design_system import PALETTE, clinical_stylesheet
|
||||
from .dialogs.ai_consult import can_open_ai_consult
|
||||
from .dialogs.ai_consult_picker import select_and_present_ai_consult
|
||||
from .dialogs.diagnosis import DiagnosisDialog
|
||||
from .dialogs.esign_doctor import EsignDoctorDialog
|
||||
from .dialogs.local_audio_queue import LocalAudioQueueDialog
|
||||
from .dialogs.prescription_esign import can_open_esign_doctor
|
||||
from .pages import (
|
||||
AppointmentsPage,
|
||||
ConsultationsPage,
|
||||
@@ -1421,6 +1423,8 @@ class ShellWindow(QMainWindow):
|
||||
self.menu_ai_action = user_menu.addAction("AI 助手")
|
||||
self.menu_ai_action.triggered.connect(self._open_ai_assistant)
|
||||
self.menu_ai_action.setVisible(False)
|
||||
if "1" in self._role_ids() and can_open_esign_doctor(self.repository, self.permissions):
|
||||
user_menu.addAction("医生电子签署身份", self._open_esign_doctor)
|
||||
update_action = user_menu.addAction("检查更新")
|
||||
update_action.triggered.connect(self.update_check_requested.emit)
|
||||
user_menu.addSeparator()
|
||||
@@ -1531,12 +1535,7 @@ class ShellWindow(QMainWindow):
|
||||
department = first_value(
|
||||
self.current_user, "department_name", "department.name", default=""
|
||||
)
|
||||
role_ids = (
|
||||
first_value(self.current_user, "role_ids", "role_id", default=[]) or []
|
||||
)
|
||||
if not isinstance(role_ids, (list, tuple, set, frozenset)):
|
||||
role_ids = [role_ids]
|
||||
role_values = {str(value) for value in role_ids}
|
||||
role_values = self._role_ids()
|
||||
role = (
|
||||
"医生"
|
||||
if "1" in role_values
|
||||
@@ -1546,6 +1545,12 @@ class ShellWindow(QMainWindow):
|
||||
)
|
||||
return f"{department} · {role}" if department else role
|
||||
|
||||
def _role_ids(self) -> set[str]:
|
||||
role_ids = first_value(self.current_user, "role_ids", "role_id", default=[]) or []
|
||||
if not isinstance(role_ids, (list, tuple, set, frozenset)):
|
||||
role_ids = [role_ids]
|
||||
return {str(value) for value in role_ids}
|
||||
|
||||
def toggle_sidebar(self) -> None:
|
||||
"""Toggle the admin-style compact menu while preserving the page state."""
|
||||
|
||||
@@ -1860,6 +1865,11 @@ class ShellWindow(QMainWindow):
|
||||
initial_query=self.global_search.text().strip(),
|
||||
)
|
||||
|
||||
def _open_esign_doctor(self) -> None:
|
||||
dialog = EsignDoctorDialog(self.repository, parent=self)
|
||||
dialog.exec()
|
||||
dialog.deleteLater()
|
||||
|
||||
def _open_local_audio_settings(self) -> None:
|
||||
current = self._local_audio_settings_dialog
|
||||
if current is not None and current.isVisible():
|
||||
|
||||
@@ -183,7 +183,7 @@ def test_nested_appointments_confirmation_and_prescription_labels() -> None:
|
||||
)
|
||||
assert (
|
||||
prescription_action_label({"prescription_audit_status": 1, "prescription_void_status": 1})
|
||||
== "编辑处方"
|
||||
== "重新开方"
|
||||
)
|
||||
assert (
|
||||
prescription_action_label(
|
||||
@@ -672,6 +672,119 @@ def test_existing_pending_prescription_is_edited_in_place_not_duplicated(
|
||||
application.processEvents()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("other_appointment", [False, True])
|
||||
def test_stale_consultation_actions_use_verified_current_prescription(
|
||||
application: QApplication,
|
||||
immediate_async: None,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
other_appointment: bool,
|
||||
) -> None:
|
||||
listed = _row(current_has_prescription=1, current_prescription_id=701, prescription_audit_status=0)
|
||||
current = {
|
||||
"id": 702, "sn": "RX-702", "appointment_id": 102 if other_appointment else 101,
|
||||
"diagnosis_id": 501, "audit_status": 0, "void_status": 0, "can_void": True,
|
||||
}
|
||||
updated: list[int] = []
|
||||
prompted: list[tuple[int, bool]] = []
|
||||
operations: list[int] = []
|
||||
|
||||
def confirm(_parent: QWidget, prescription: dict[str, Any], *, current_changed: bool) -> bool:
|
||||
prompted.append((prescription["id"], current_changed))
|
||||
return False
|
||||
|
||||
repository = SimpleNamespace(
|
||||
get_prescription_by_appointment=lambda appointment_id: current,
|
||||
void_prescription=lambda prescription_id: operations.append(prescription_id),
|
||||
)
|
||||
page = ConsultationsPage(repository, permissions=PermissionSet(["*"]))
|
||||
page.table_host.set_rows([listed])
|
||||
monkeypatch.setattr(page, "refresh", lambda **_kwargs: None)
|
||||
monkeypatch.setattr(page, "_open_existing_prescription_editor", lambda prescription: updated.append(prescription["id"]))
|
||||
monkeypatch.setattr(consultations_module, "confirm_prescription_void", confirm)
|
||||
|
||||
page._row_action("prescription", listed)
|
||||
page._row_action("void_prescription", listed)
|
||||
|
||||
assert not operations
|
||||
if other_appointment:
|
||||
assert not updated and not prompted
|
||||
assert "与当前挂号不一致" in page.banner.label.text()
|
||||
else:
|
||||
assert updated == [702]
|
||||
assert prompted == [(702, True)]
|
||||
page.close()
|
||||
|
||||
|
||||
def test_more_menu_voids_current_prescription_then_reissues_and_resumes_signing(
|
||||
application: QApplication,
|
||||
immediate_async: None,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
original = {
|
||||
"id": 901, "sn": "RX-901", "creator_id": 7, "diagnosis_id": 501,
|
||||
"appointment_id": 202, "audit_status": 0, "void_status": 0, "can_void": True,
|
||||
"patient_name": "虚构测试", "doctor_signature": "archived",
|
||||
"herbs": [{"name": "黄芪", "dosage": 15}],
|
||||
}
|
||||
created: list[dict[str, Any]] = []
|
||||
resumed: list[int] = []
|
||||
voided: list[int] = []
|
||||
|
||||
def current_row() -> dict[str, Any]:
|
||||
return _row(appointment_id=202, current_has_prescription=1,
|
||||
current_prescription_id=901, prescription_audit_status=0,
|
||||
prescription_void_status=original["void_status"])
|
||||
|
||||
class Repository:
|
||||
def get_prescription_by_appointment(self, appointment_id: int) -> dict[str, Any]:
|
||||
assert appointment_id == 202
|
||||
return dict(original)
|
||||
|
||||
def void_prescription(self, prescription_id: int) -> dict[str, Any]:
|
||||
voided.append(prescription_id)
|
||||
original.update(void_status=1, can_void=False, can_restore_rejected=False)
|
||||
return {"id": prescription_id}
|
||||
|
||||
def list_consultations(self, **_kwargs: Any) -> dict[str, Any]:
|
||||
return {"lists": [current_row()], "count": 1}
|
||||
|
||||
def create_prescription(self, prescription: dict[str, Any]) -> dict[str, Any]:
|
||||
created.append(dict(prescription))
|
||||
return {"id": 902}
|
||||
|
||||
class ReissueEditor:
|
||||
def __init__(self, _repository: Any, seed: Any, **kwargs: Any) -> None:
|
||||
assert kwargs["mode"] == "add"
|
||||
assert not {"id", "sn", "doctor_signature", "void_status", "esign"} & seed.keys()
|
||||
self.saved_draft = kwargs["save_draft"](seed)
|
||||
|
||||
def exec(self) -> QDialog.DialogCode:
|
||||
return QDialog.DialogCode.Accepted
|
||||
|
||||
monkeypatch.setattr(consultations_module, "confirm_prescription_void", lambda *_args, **_kwargs: True)
|
||||
monkeypatch.setattr(consultations_module, "PrescriptionEditorDialog", ReissueEditor)
|
||||
monkeypatch.setattr(consultations_module, "resume_saved_prescription",
|
||||
lambda _repository, saved, _parent: resumed.append(saved["id"]))
|
||||
page = ConsultationsPage(Repository(), permissions=PermissionSet(["*"]),
|
||||
current_user=SimpleNamespace(id=7, name="测试医生"))
|
||||
page.table_host.set_rows([current_row()])
|
||||
|
||||
def more_actions() -> dict[str, Any]:
|
||||
widget = page.table_host._action_widget(current_row(), 0)
|
||||
more = widget.findChild(QToolButton, "DiagnosisRowMore")
|
||||
return {action.text(): action for action in more.menu().actions()}
|
||||
|
||||
more_actions()["作废处方"].trigger()
|
||||
assert voided == [901] and original["doctor_signature"] == "archived"
|
||||
actions = more_actions()
|
||||
assert "作废处方" not in actions and "重新开方" in actions
|
||||
actions["重新开方"].trigger()
|
||||
assert len(created) == 1 and created[0]["appointment_id"] == 202
|
||||
assert created[0]["herbs"] == original["herbs"]
|
||||
assert resumed == [902]
|
||||
page.close()
|
||||
|
||||
|
||||
def test_switching_rows_invalidates_prescription_worker_and_clears_busy(
|
||||
application: QApplication,
|
||||
immediate_async: None,
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
"""Opt-in Windows native WebEngine lifecycle regression; never load provider pages.
|
||||
|
||||
Run outside a process-restricted sandbox with ESIGN_NATIVE_QT_TEST=1 and
|
||||
QT_QPA_PLATFORM=windows. Ordinary headless test runs skip this module.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from PySide6.QtCore import QElapsedTimer
|
||||
from PySide6.QtTest import QTest
|
||||
from PySide6.QtWidgets import QApplication
|
||||
|
||||
from doctor_workstation.ui.dialogs import prescription_esign as module
|
||||
from doctor_workstation.ui.dialogs.esign_webview import EmbeddedIdentityView
|
||||
|
||||
pytestmark = pytest.mark.skipif(
|
||||
sys.platform != "win32" or os.getenv("ESIGN_NATIVE_QT_TEST") != "1",
|
||||
reason="opt-in native Windows Qt process test",
|
||||
)
|
||||
|
||||
|
||||
def status(value: str = "pending") -> dict[str, Any]:
|
||||
return dict(enabled=True, required=True, environment="sandbox", status=value,
|
||||
can_sign=True, can_download=False, auth_url="https://smlt.esign.cn/no-request")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("hide_before_ready", [False, True])
|
||||
def test_real_webengine_initialization_and_user_hide(
|
||||
monkeypatch: pytest.MonkeyPatch, hide_before_ready: bool
|
||||
) -> None:
|
||||
app = QApplication.instance() or QApplication([])
|
||||
calls: list[str] = []
|
||||
loaded_urls: list[str] = []
|
||||
queued: list[dict[str, Any]] = []
|
||||
|
||||
class Repository:
|
||||
def get_prescription_esign_status(self, prescription_id: int) -> dict[str, Any]:
|
||||
calls.append("status")
|
||||
return status()
|
||||
|
||||
def dispatch(function: Any, **callbacks: Any) -> None:
|
||||
if not calls:
|
||||
callbacks["on_success"](function())
|
||||
callbacks["on_finished"]()
|
||||
else:
|
||||
queued.append(callbacks)
|
||||
|
||||
monkeypatch.setattr(module, "run_async", dispatch)
|
||||
monkeypatch.setattr(EmbeddedIdentityView, "load_authentication", lambda self, url: loaded_urls.append(url))
|
||||
dialog = module.PrescriptionEsignDialog(Repository(), {"id": 7})
|
||||
dialog.show()
|
||||
QTest.qWait(100)
|
||||
original_id = int(dialog.winId())
|
||||
generation = dialog._generation
|
||||
dialog.start_button.click()
|
||||
assert len(queued) == 1 and dialog.identity_view is None
|
||||
queued[0]["on_success"](status("authenticating"))
|
||||
queued[0]["on_finished"]()
|
||||
assert len(queued) == 2 and dialog.identity_view is None
|
||||
queued[1]["on_success"]({**status("authenticating"), "identity_status": "ING", "can_complete": False})
|
||||
if hide_before_ready:
|
||||
dialog.hide()
|
||||
queued[1]["on_finished"]()
|
||||
timer = QElapsedTimer()
|
||||
timer.start()
|
||||
while timer.elapsed() < 8000:
|
||||
QTest.qWait(20)
|
||||
if hide_before_ready:
|
||||
if not dialog._native_hide_pending:
|
||||
break
|
||||
elif int(dialog.winId()) != original_id and not dialog._native_hide_pending:
|
||||
break
|
||||
assert len(queued) == 2
|
||||
QTest.qWait(100)
|
||||
if hide_before_ready:
|
||||
assert not dialog.isVisible()
|
||||
assert dialog.identity_view is None
|
||||
assert not dialog.poll_timer.isActive()
|
||||
else:
|
||||
assert int(dialog.winId()) != original_id, "native recreation must actually be exercised"
|
||||
assert dialog._generation == generation
|
||||
assert dialog.isVisible() and dialog.state["status"] == "authenticating"
|
||||
assert loaded_urls == ["https://smlt.esign.cn/no-request"]
|
||||
assert dialog.identity_view is not None and dialog.poll_timer.isActive()
|
||||
dialog.poll_timer.timeout.emit()
|
||||
assert len(queued) == 3
|
||||
queued[2]["on_success"]({**status("authenticating"), "identity_status": "SUCCESS", "can_complete": True})
|
||||
queued[2]["on_finished"]()
|
||||
assert len(queued) == 3 and dialog.sign_button.isVisible()
|
||||
assert dialog.identity_view is None and not dialog.poll_timer.isActive()
|
||||
dialog.setVisible(False)
|
||||
assert not dialog._intent and not dialog.sign_button.isEnabled() and not dialog.poll_timer.isActive()
|
||||
assert calls == ["status"]
|
||||
dialog.close()
|
||||
app.processEvents()
|
||||
@@ -0,0 +1,83 @@
|
||||
"""Exercise navigation policy and page security without any provider request."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from PySide6.QtCore import QUrl
|
||||
|
||||
from doctor_workstation.core.esign import authentication_navigation_allowed
|
||||
from doctor_workstation.ui.dialogs import esign_webview
|
||||
|
||||
|
||||
@pytest.mark.parametrize("url", [
|
||||
"https://idverify.esign.cn/identity?flow=test",
|
||||
"https://smlfront.esign.cn:8890/identity/login",
|
||||
"https://static2.tsign.cn/a.css",
|
||||
"https://nested.official.tsign.cn/identity",
|
||||
])
|
||||
def test_official_https_redirects_remain_inside_system(url: str) -> None:
|
||||
assert authentication_navigation_allowed(url)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("url", [
|
||||
"http://idverify.esign.cn/identity", "javascript:alert(1)", "file:///C:/secret",
|
||||
"weixin://identity", "alipays://identity", "data:text/html,test", "about:blank",
|
||||
"https://esign.cn.evil.test/identity", "https://evil-esign.cn/identity",
|
||||
"https://evil.test/identity", "https://user@idverify.esign.cn/identity",
|
||||
"https://idverify.esign.cn:444/identity", "https://idverify.esign.cn:8890/identity",
|
||||
"https://idverify.esign.cn\\@evil.test/identity", "https://a%40b.esign.cn/identity",
|
||||
])
|
||||
def test_offsite_and_app_switch_navigation_is_rejected(url: str) -> None:
|
||||
assert not authentication_navigation_allowed(url)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not esign_webview.WEBENGINE_AVAILABLE, reason="QtWebEngine unavailable")
|
||||
def test_page_blocks_popups_frames_custom_schemes_and_uploads() -> None:
|
||||
blocked: list[str] = []
|
||||
page = SimpleNamespace(shutting_down=False, blocked=SimpleNamespace(emit=blocked.append))
|
||||
for main_frame in (True, False):
|
||||
assert esign_webview.IdentityPage.acceptNavigationRequest(
|
||||
page, QUrl("https://idverify.esign.cn/test"), None, main_frame
|
||||
)
|
||||
assert not esign_webview.IdentityPage.acceptNavigationRequest(
|
||||
page, QUrl("weixin://open"), None, main_frame
|
||||
)
|
||||
assert not esign_webview.IdentityPage.acceptNavigationRequest(
|
||||
page, QUrl("https://offsite.test/"), None, main_frame
|
||||
)
|
||||
assert esign_webview.IdentityPage.createWindow(page, None) is None
|
||||
assert esign_webview.IdentityPage.chooseFiles(page, None, [], []) == []
|
||||
assert len(blocked) == 5
|
||||
page.shutting_down = True
|
||||
assert esign_webview.IdentityPage.acceptNavigationRequest(page, QUrl("about:blank"), None, True)
|
||||
assert not esign_webview.IdentityPage.acceptNavigationRequest(page, QUrl("https://idverify.esign.cn/"), None, True)
|
||||
|
||||
|
||||
def test_loading_is_not_identity_success_and_tls_download_permission_are_denied() -> None:
|
||||
errors: list[str] = []
|
||||
calls: list[str] = []
|
||||
view = SimpleNamespace(_failure=errors.append, _stopped=False, initialized=SimpleNamespace(emit=lambda: None))
|
||||
esign_webview.EmbeddedIdentityView._loaded(view, True)
|
||||
assert errors == []
|
||||
esign_webview.EmbeddedIdentityView._loaded(view, False)
|
||||
esign_webview.EmbeddedIdentityView._deny_certificate(
|
||||
view, SimpleNamespace(rejectCertificate=lambda: calls.append("reject certificate"))
|
||||
)
|
||||
esign_webview.EmbeddedIdentityView._deny_download(
|
||||
view, SimpleNamespace(cancel=lambda: calls.append("cancel download"))
|
||||
)
|
||||
esign_webview.EmbeddedIdentityView._deny_permission(
|
||||
view, SimpleNamespace(deny=lambda: calls.append("deny permission"))
|
||||
)
|
||||
assert calls == ["reject certificate", "cancel download", "deny permission"]
|
||||
assert len(errors) == 4
|
||||
|
||||
|
||||
def test_manual_recheck_preserves_entered_sms_form() -> None:
|
||||
loaded: list[str] = []
|
||||
view = SimpleNamespace(_auth_url=None, view=SimpleNamespace(setUrl=lambda url: loaded.append(url.toString())))
|
||||
esign_webview.EmbeddedIdentityView.load_authentication(view, "https://smlt.esign.cn/abc")
|
||||
esign_webview.EmbeddedIdentityView.load_authentication(view, "https://smlt.esign.cn/abc")
|
||||
assert loaded == ["https://smlt.esign.cn/abc"]
|
||||
@@ -152,6 +152,61 @@ def test_demo_prescription_lookup_is_appointment_authoritative(
|
||||
assert first.case_record["appointment_id"] == 101
|
||||
|
||||
|
||||
def test_demo_void_and_reissue_preserves_the_original_prescription(
|
||||
repository: DemoDoctorRepository,
|
||||
) -> None:
|
||||
original = repository.create_prescription(
|
||||
appointment_id=103,
|
||||
diagnosis_id=503,
|
||||
doctor_signature="/demo/signature.png",
|
||||
)
|
||||
repository.audit_prescription(original.id, action="approve")
|
||||
assert repository.get_reception(103)["appointment"]["has_prescription"] == 1
|
||||
assert repository.get_prescription(original.id).raw["can_void"] is True
|
||||
|
||||
repository.void_prescription(original.id)
|
||||
|
||||
voided = repository.get_prescription(original.id)
|
||||
assert voided.void_status == 1
|
||||
assert voided.raw["can_void"] is False
|
||||
assert voided.void_time
|
||||
assert voided.audit_status == 1
|
||||
assert voided.doctor_signature == original.doctor_signature
|
||||
assert repository.get_reception(103)["appointment"]["has_prescription"] == 0
|
||||
assert repository.get_prescription_by_appointment(103) == voided
|
||||
with pytest.raises(ApiBusinessError, match="该处方已作废"):
|
||||
repository.void_prescription(original.id)
|
||||
|
||||
replacement = repository.create_prescription(appointment_id=103, diagnosis_id=503)
|
||||
|
||||
assert replacement.id != original.id
|
||||
assert replacement.audit_status == 0
|
||||
assert replacement.void_status == 0
|
||||
assert not replacement.doctor_signature
|
||||
assert repository.get_prescription_by_appointment(103) == replacement
|
||||
assert repository.get_reception(103)["appointment"]["has_prescription"] == 1
|
||||
assert repository.get_prescription(original.id) == voided
|
||||
|
||||
|
||||
def test_demo_void_and_order_creation_preserve_the_existing_order(
|
||||
repository: DemoDoctorRepository,
|
||||
) -> None:
|
||||
ordered = repository.get_prescription(801)
|
||||
orders = repository.list_prescription_orders().items
|
||||
assert repository.list_prescriptions(sn=ordered.sn).items[0].raw["can_void"] is False
|
||||
|
||||
with pytest.raises(ApiBusinessError, match="已有业务订单"):
|
||||
repository.void_prescription(ordered.id)
|
||||
|
||||
assert repository.get_prescription(ordered.id) == ordered
|
||||
|
||||
repository.void_prescription(802)
|
||||
with pytest.raises(ApiBusinessError, match="已作废处方不可创建业务订单"):
|
||||
repository.create_prescription_order(prescription_id=802)
|
||||
|
||||
assert repository.list_prescription_orders().items == orders
|
||||
|
||||
|
||||
def test_demo_consultation_filters_and_dictionaries_cover_exposed_ui(
|
||||
repository: DemoDoctorRepository,
|
||||
) -> None:
|
||||
|
||||
@@ -580,6 +580,44 @@ def test_order_audit_action_uses_repository_contract_values(
|
||||
application.processEvents()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("can_sign,opens_signing", [(True, True), (False, False)])
|
||||
def test_order_approval_routes_unsigned_prescription_before_audit(
|
||||
application: QApplication,
|
||||
immediate_async: None,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
can_sign: bool,
|
||||
opens_signing: bool,
|
||||
) -> None:
|
||||
requested = []
|
||||
opened = []
|
||||
state = {"enabled": True, "required": True, "environment": "sandbox", "status": "pending",
|
||||
"can_sign": can_sign, "can_download": False}
|
||||
|
||||
def get_status(prescription_id: int) -> dict[str, Any]:
|
||||
requested.append(prescription_id)
|
||||
return state
|
||||
|
||||
repository = SimpleNamespace(get_prescription_esign_status=get_status)
|
||||
permissions = PermissionSet(["tcm.prescriptionOrder/auditPrescription", "cf.prescription/edit"])
|
||||
page = PatientsPage(repository, permissions)
|
||||
monkeypatch.setattr(page.order_workspace, "refresh", lambda **_kwargs: None)
|
||||
monkeypatch.setattr(page, "_submit_order_audit", lambda *_args, **_kwargs: pytest.fail("unsigned approval"))
|
||||
monkeypatch.setattr(QInputDialog, "getItem", staticmethod(lambda *_args, **_kwargs: ("通过", True)))
|
||||
monkeypatch.setattr(
|
||||
patients_module, "PrescriptionEsignDialog",
|
||||
lambda _repo, prescription, **_kwargs: SimpleNamespace(exec=lambda: opened.append(prescription["id"])),
|
||||
)
|
||||
|
||||
page._handle_order_action("audit_prescription", {"id": 70, "prescription_id": 52,
|
||||
"prescription_audit_status": 0, "fulfillment_status": 1})
|
||||
|
||||
assert requested == [52]
|
||||
assert opened == ([52] if opens_signing else [])
|
||||
assert "签署" in page.order_workspace.banner.label.text()
|
||||
page.close()
|
||||
application.processEvents()
|
||||
|
||||
|
||||
def test_shell_uses_demo_session_menu_and_fits_minimum_window(
|
||||
application: QApplication,
|
||||
immediate_async: None,
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -7,10 +7,10 @@ from typing import Any
|
||||
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
|
||||
|
||||
import pytest
|
||||
from PySide6.QtCore import QDate, QEvent, QObject, QSize, Qt
|
||||
from PySide6.QtGui import QColor, QImage, QPainter
|
||||
from PySide6.QtCore import QBuffer, QDate, QEvent, QIODevice, QObject, QSize, Qt
|
||||
from PySide6.QtGui import QColor, QImage, QPainter, QTextDocument
|
||||
from PySide6.QtPdf import QPdfDocument
|
||||
from PySide6.QtWidgets import QApplication, QComboBox, QDialog, QPushButton, QWidget
|
||||
from PySide6.QtWidgets import QApplication, QComboBox, QDialog, QMessageBox, QPushButton, QWidget
|
||||
|
||||
from doctor_workstation import app as app_module
|
||||
from doctor_workstation.core import PermissionSet, Prescription
|
||||
@@ -479,6 +479,206 @@ def test_editor_builds_complete_add_payload(
|
||||
application.processEvents()
|
||||
|
||||
|
||||
def test_esign_draft_save_retries_without_discarding_form(
|
||||
application: QApplication,
|
||||
immediate_async: None,
|
||||
) -> None:
|
||||
calls: list[dict[str, Any]] = []
|
||||
|
||||
def save(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
calls.append(payload)
|
||||
if len(calls) == 1:
|
||||
raise TimeoutError("request timed out")
|
||||
return {"id": 71}
|
||||
|
||||
repository = SimpleNamespace(
|
||||
get_prescription_esign_config=lambda: {"enabled": True, "environment": "sandbox"},
|
||||
list_medicines=lambda **_kwargs: {"lists": [], "count": 0},
|
||||
)
|
||||
editor = PrescriptionEditorDialog(repository, current_user={"id": 7, "name": "测试医生"}, save_draft=save)
|
||||
editor.show()
|
||||
editor.patient_name.setText("虚构患者")
|
||||
editor.clinical_diagnosis.setPlainText("测试草稿")
|
||||
editor.herbs.add_row(formula_type="主方")
|
||||
editor.herbs.rows[0].medicine.set_value(31, "测试药材")
|
||||
editor.herbs.rows[0].dosage.setValue(15)
|
||||
|
||||
editor.save_button.click()
|
||||
assert editor.isVisible()
|
||||
assert editor.save_button.text() == "重试保存草稿"
|
||||
assert editor.patient_name.text() == "虚构患者"
|
||||
assert len(calls) == 1
|
||||
|
||||
editor.save_button.click()
|
||||
assert editor.result() == QDialog.DialogCode.Accepted
|
||||
assert editor.saved_draft == {"id": 71}
|
||||
assert calls[0] == calls[1]
|
||||
assert calls[1]["request_key"]
|
||||
application.processEvents()
|
||||
|
||||
|
||||
def test_issued_page_voids_and_reissues_as_a_new_prescription(
|
||||
application: QApplication,
|
||||
immediate_async: None,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
original = {
|
||||
"id": 71,
|
||||
"sn": "RX-71",
|
||||
"creator_id": 7,
|
||||
"doctor_name": "周医生",
|
||||
"diagnosis_id": 8,
|
||||
"appointment_id": 9,
|
||||
"patient_name": "沙箱测试",
|
||||
"visit_no": "VISIT-8",
|
||||
"prescription_date": "2026-03-10",
|
||||
"herbs": [{"name": "黄芪", "dosage": 15}],
|
||||
"audit_status": 1,
|
||||
"audit_time": "2026-03-10 09:10:00",
|
||||
"order_no": "ARCHIVED-ORDER",
|
||||
"doctor_signature": "old-signature",
|
||||
"esign": {"required": True, "status": "signed"},
|
||||
"void_status": 0,
|
||||
"can_void": True,
|
||||
}
|
||||
blocked = {**original, "id": 72, "creator_id": 8, "can_void": False}
|
||||
void_calls = []
|
||||
opened = []
|
||||
|
||||
class Repository:
|
||||
def list_prescriptions(self, **_filters: Any) -> dict[str, Any]:
|
||||
return {"lists": [original, blocked], "count": 2}
|
||||
|
||||
def get_prescription(self, prescription_id: int) -> dict[str, Any]:
|
||||
assert prescription_id == original["id"]
|
||||
return dict(original)
|
||||
|
||||
def void_prescription(self, prescription_id: int) -> None:
|
||||
void_calls.append(prescription_id)
|
||||
if len(void_calls) == 1:
|
||||
raise RuntimeError("作废失败,请稍后重试")
|
||||
original.update(void_status=1, can_void=False)
|
||||
|
||||
def capture_new_prescription(dialog: PrescriptionEditorDialog) -> int:
|
||||
assert dialog.mode == "add"
|
||||
opened.append(dialog.payload())
|
||||
return QDialog.DialogCode.Rejected
|
||||
|
||||
confirm_void = False
|
||||
|
||||
def selected_confirmation(box: QMessageBox) -> QPushButton:
|
||||
label = "确认作废" if confirm_void else "取消"
|
||||
return next(button for button in box.buttons() if button.text() == label)
|
||||
|
||||
monkeypatch.setattr(PrescriptionEditorDialog, "exec", capture_new_prescription)
|
||||
monkeypatch.setattr(QMessageBox, "exec", lambda _box: 0)
|
||||
monkeypatch.setattr(QMessageBox, "clickedButton", selected_confirmation)
|
||||
page = PrescriptionsPage(
|
||||
Repository(), {"cf.prescription/read", "cf.prescription/edit", "tcm.diagnosis/kaifang"},
|
||||
SimpleNamespace(id=7, name="周医生"),
|
||||
)
|
||||
page.refresh()
|
||||
page._run_row_action(blocked, page._void_selected)
|
||||
assert page.void_button.isHidden()
|
||||
assert not void_calls
|
||||
|
||||
page._run_row_action(original, page._void_selected)
|
||||
assert page.void_button.isEnabled()
|
||||
assert not void_calls
|
||||
confirm_void = True
|
||||
page.void_button.click()
|
||||
assert void_calls == [71]
|
||||
assert page.void_button.isEnabled() and original["void_status"] == 0
|
||||
assert "请稍后重试" in page.banner.label.text()
|
||||
page.void_button.click()
|
||||
assert void_calls == [71, 71]
|
||||
assert page.void_button.isHidden()
|
||||
assert page.reissue_button.isEnabled()
|
||||
assert not page.edit_button.isEnabled()
|
||||
|
||||
page.reissue_button.click()
|
||||
assert len(opened) == 1
|
||||
draft = opened[0]
|
||||
assert draft["diagnosis_id"] == 8 and draft["appointment_id"] == 9
|
||||
assert draft["patient_name"] == "沙箱测试" and draft["visit_no"] == "VISIT-8"
|
||||
assert draft["creator_id"] == 7
|
||||
assert draft["herbs"][0]["name"] == "黄芪"
|
||||
assert draft["prescription_date"] == QDate.currentDate().toString("yyyy-MM-dd")
|
||||
assert draft["audit_status"] == 0 and draft["doctor_signature"] == ""
|
||||
assert not draft.keys() & {"id", "sn", "order_no", "audit_time", "esign", "void_status"}
|
||||
assert original["void_status"] == 1
|
||||
assert original["esign"]["status"] == "signed" and original["audit_status"] == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("read_only", [False, True])
|
||||
def test_prescription_window_footer_preserves_draft_on_void_failure(
|
||||
application: QApplication,
|
||||
immediate_async: None,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
read_only: bool,
|
||||
) -> None:
|
||||
calls: list[int] = []
|
||||
record = {"id": 71, "sn": "RX-71", "patient_name": "虚构测试", "can_void": True}
|
||||
|
||||
def void_prescription(prescription_id: int) -> dict[str, Any]:
|
||||
calls.append(prescription_id)
|
||||
if len(calls) == 1:
|
||||
raise RuntimeError("网络错误,请稍后重试")
|
||||
return {"id": prescription_id}
|
||||
|
||||
repository = SimpleNamespace(void_prescription=void_prescription)
|
||||
dialog = (
|
||||
PrescriptionDetailDialog(record, repository=repository, allow_void=True)
|
||||
if read_only else PrescriptionEditorDialog(repository, record, mode="edit", allow_void=True)
|
||||
)
|
||||
confirm = False
|
||||
monkeypatch.setattr(dialog_module, "confirm_prescription_void", lambda *_args: confirm)
|
||||
assert dialog.void_button.text() == "作废处方"
|
||||
dialog.void_button.click()
|
||||
assert not calls
|
||||
confirm = True
|
||||
dialog.void_button.click()
|
||||
assert calls == [71] and dialog.void_button.text() == "重试作废"
|
||||
assert "请稍后重试" in dialog.void_button.banner.label.text()
|
||||
dialog.void_button.click()
|
||||
assert calls == [71, 71] and dialog.result() == dialog_module.PRESCRIPTION_VOIDED_RESULT
|
||||
|
||||
|
||||
@pytest.mark.parametrize("variant", ["internal", "user"])
|
||||
def test_prescription_preview_scales_signature_proportionately(
|
||||
application: QApplication, variant: str,
|
||||
) -> None:
|
||||
image = QImage(300, 150, QImage.Format.Format_ARGB32)
|
||||
image.fill(QColor("black"))
|
||||
buffer = QBuffer()
|
||||
assert buffer.open(QIODevice.OpenModeFlag.WriteOnly)
|
||||
assert image.save(buffer, "PNG")
|
||||
signature = "data:image/png;base64," + bytes(buffer.data().toBase64()).decode("ascii")
|
||||
document = QTextDocument()
|
||||
document.setHtml(render_prescription_html({"doctor_signature": signature}, variant=variant))
|
||||
signature_sizes = []
|
||||
block = document.begin()
|
||||
while block.isValid():
|
||||
fragments = block.begin()
|
||||
while not fragments.atEnd():
|
||||
image_format = fragments.fragment().charFormat().toImageFormat()
|
||||
if image_format.name() == signature:
|
||||
signature_sizes.append((image_format.width(), image_format.height()))
|
||||
fragments += 1
|
||||
block = block.next()
|
||||
expected_size = (72, 36) if variant == "internal" else (48, 24)
|
||||
assert signature_sizes == [expected_size]
|
||||
|
||||
|
||||
def test_unsigned_draft_shows_signing_state_before_audit() -> None:
|
||||
row = {"id": 71, "audit_status": 0, "esign": {"required": True, "status": "pending"}}
|
||||
assert prescription_status(row) == ("待签名", "warning")
|
||||
assert not can_audit(row)
|
||||
row["esign"]["status"] = "signed"
|
||||
assert prescription_status(row) == ("待审核", "warning")
|
||||
assert can_audit(row)
|
||||
|
||||
|
||||
def test_prescription_workflows_never_show_orphan_child_controls(
|
||||
application: QApplication,
|
||||
immediate_async: None,
|
||||
@@ -898,7 +1098,7 @@ def test_order_payload_and_a4_print_document(
|
||||
assert "辅方" in rendered
|
||||
assert "105克" in rendered
|
||||
assert "84克" in rendered
|
||||
assert "剂量:</span> 27克" in rendered
|
||||
assert "剂量:</span> 27克" in rendered
|
||||
assert "每天2次, 一次2袋, 每袋5g, 温水送服, 饭后" in rendered
|
||||
assert "主服法:" in rendered
|
||||
assert "辅服法:" in rendered
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,18 @@
|
||||
# e签宝 403 安全诊断
|
||||
|
||||
已在 `server/app/common/service/esign/EsignClient.php` 增加可选的结构化 `EsignProviderException::$reason`,保留原来的 `operation` 和 `providerCode`。
|
||||
|
||||
- `APPLICATION_ACCESS_DENIED`:仅匹配供应商顶层字符串 `msg` 中的“该应用无权调用此接口”。
|
||||
- `IP_WHITELIST_MISMATCH`:仅匹配明确的 IP 不在白名单、IP 白名单不匹配或校验失败短语。
|
||||
- `SIGNATURE_MISMATCH`:仅匹配独立的 `SignatureDoesNotMatch` 标识。
|
||||
- 其他消息、单独的 `FORBIDDEN`、非字符串消息仍为 `null`,创建账号 403 保留原有接口权限及 IP 白名单的通用提示。不对其他供应商错误码应用 403 分类。
|
||||
|
||||
异常只包含固定提示和固定枚举值,不复制、存储或记录供应商消息中的身份证号、姓名、密钥或其他附加文本。未知枚举值也会被构造函数拒绝。未增加任何自动重试。SDK 初始化、认证请求及先前本地修改保持原状。
|
||||
|
||||
验证:
|
||||
|
||||
- `php server/tests/EsignClientTest.php`:297 项离线检查通过。
|
||||
- 两个 PHP 文件语法检查通过。
|
||||
- `git diff --check -- server/app/common/service/esign/EsignClient.php server/tests/EsignClientTest.php`:通过。
|
||||
|
||||
本任务仅修改以上两个 PHP 文件并增加本说明;没有修改 service/controller 其他文件、运行 spool、供应商文件、数据库或环境配置,也没有调用真实供应商接口。真实接口的本次原因仍需由后续请求中识别到的固定枚举判断。
|
||||
@@ -0,0 +1,53 @@
|
||||
# e签宝 SDK 3.0 addPerson 业务错误码 403:官方资料核验
|
||||
|
||||
日期:2026-11-18。范围:只读公开文档和公开错误码查询工具;没有读取项目密钥、环境变量、业务数据库或用户数据,没有调用认证、开户、签署等业务接口。
|
||||
|
||||
## 结论
|
||||
|
||||
- 官方错误码工具查询 `403` 返回三个不同场景,不能把该数字直接等同于 HTTP 403,也不能仅凭数字断定实名信息不匹配。
|
||||
- 其中一项的错误内容为“该应用无权调用此接口”。官方给出的处理方向是:该应用缺少相应接口访问权限,携带 AppID 联系交付顾问开通。
|
||||
- 另两项分别是文件流上传的 HTTP 403 / SignatureDoesNotMatch,以及 FORBIDDEN / IP 白名单不匹配。前者明确属于文件上传 HTTP 状态,不适用于已知的 HTTP 200、JSON `errCode=403` 的 addPerson 响应;后者尚需匹配完整错误信息和实际产品层。
|
||||
- 查询结果没有标出 SDK 版本或接口适用范围。若原始 JSON 的 `msg` 只有 `403` 或缺少描述,公开资料尚不足以对本次 addPerson 失败作唯一归因。
|
||||
- 主任务提供的同一 SDK 查询账号接口返回账号不存在业务码,以及认证成功、checkWillingness 有效等证据,使“应用缺少创建个人签署账号接口权限”成为值得供应商重点核查的候选原因;这是结合现场信息的推断,不是官方对本次请求的诊断。其他接口成功不能证明 addPerson 的权限已开通。
|
||||
|
||||
## 官方错误码工具的可复核查询
|
||||
|
||||
入口:[e签宝错误码查询](https://open.esign.cn/tools/error-code)。公开页面无需登录即可输入错误码查询。
|
||||
|
||||
页面公开资源:
|
||||
|
||||
- [应用 JavaScript](https://asset.tsign.cn/apps/open-platform-front-ssr/prod/4.0.8/js/chunk/app.d912f481.js):配置生产 BASE_URL 为 `https://tapi.esign.cn`,`featchErrorQuery` 使用 POST `/open/public/standard/error/query`。
|
||||
- [错误码页面 JavaScript](https://asset.tsign.cn/apps/open-platform-front-ssr/prod/4.0.8/js/chunk/40.7260f97e.js):按 code 查询时提交 `{"errorCode": 输入值}`;页面展示返回项的 `bizKeyId`、`description` 和 `errorCodeExplanation`。
|
||||
|
||||
本次请求严格按照公开页面逻辑,只发送数字错误码,没有 Cookie、Token、AppID、密钥、姓名或证件号:
|
||||
|
||||
```http
|
||||
POST https://tapi.esign.cn/open/public/standard/error/query
|
||||
Content-Type: application/json;charset=UTF-8
|
||||
|
||||
{"errorCode":"403"}
|
||||
```
|
||||
|
||||
响应 HTTP 200,顶层 `success=true`、`message=执行成功`,`data` 中三个结果摘要如下:
|
||||
|
||||
| bizKeyId | description | 官方排查方向摘要 |
|
||||
| --- | --- | --- |
|
||||
| 403 | SignatureDoesNotMatch | 文件上传 HTTP 状态码;核对 PUT 上传头的 Content-MD5 与取得上传地址时的值,并核对请求方法。 |
|
||||
| 403 | 该应用无权调用此接口 | 该应用缺少该接口访问权限;提供 AppID 联系交付顾问开通。 |
|
||||
| 403 | FORBIDDEN / IP白名单不匹配 | 核对应用的服务器公网出口 IP 白名单配置。 |
|
||||
|
||||
本次记录没有为诊断而更改白名单,也没有提交工单或向第三方发送项目应用标识。
|
||||
|
||||
## SDK 3.0 接口文档核对
|
||||
|
||||
[创建个人签署账号(非 Java / SDK Service)](https://open.esign.cn/doc/opendoc/paas_sdk_3/feq5f4b4x450i0ya) 的官方搜索索引正文对应 `/timevale/account/addPerson`:接口以 `errCode` 表示业务结果,0 成功,其他失败,`msg` 为对应说明。文档建议先完成个人核身认证,创建账号的姓名及证件号应与认证通过的信息一致。
|
||||
|
||||
限制:直接网页读取时当前页面正文只渲染到标题和提示;上述接口细节来自同一官方 URL 的搜索索引正文(索引显示旧更新时间 2026-08-27,直接页面显示 2026-11-10)。因此它可以支持接口的基本语义和一般前提,不能用来推定当前 403 的具体定义。
|
||||
|
||||
本地身份证校验位通过只证实字符串符合本地校验规则,不能替代上述服务端核身结果,也不是 403 的解释。现有公开错误码查询结果不包含姓名或证件号不匹配这一说明。
|
||||
|
||||
## 可交付供应商核查的信息范围
|
||||
|
||||
在用户授权的已有技术支持渠道,提供应用所属环境、SDK 版本、接口路径、响应时间及关联请求标识、HTTP 状态和完整业务错误码/消息;请求核查该环境 AppID 的 addPerson 接口权限以及后端拒绝原因。无需提供应用 Secret 或未经脱敏的身份证号。
|
||||
|
||||
本研究未执行这一对外沟通,仅给出后续定位所需的最小证据方向。
|
||||
@@ -0,0 +1,28 @@
|
||||
# Admin in-system eSign verification
|
||||
|
||||
Implemented in:
|
||||
- admin/src/components/EsignPrescriptionPanel.vue
|
||||
- admin/src/api/tcm.ts
|
||||
- admin/src/utils/prescription-esign.ts
|
||||
- admin/tests/prescription-esign.test.cjs
|
||||
|
||||
## Behavior
|
||||
|
||||
The explicit “核身并签署” action opens an Element Plus dialog in the current application. The user is told that successful server-confirmed identity verification will sign the current prescription automatically. The iframe accepts only the existing exact HTTPS eSign host allowlist, has `allow-forms allow-scripts allow-same-origin` sandbox permissions and `no-referrer`; it has no popup or outer-window navigation permission. No new tab, external link, manual “return and complete” action, frame-content access or frame-message trust remains.
|
||||
|
||||
After a successful start, a single-flight GET `/tcm.prescription/esignIdentityStatus` runs every five seconds after each reply, bounded to ten minutes. Only a validated full status DTO with `identity_status: SUCCESS`, `can_complete: true`, `status: authenticating` and `can_sign: true` can submit completion. The component consumes the explicit intent before the POST, clears timers and never automatically repeats a failed, timed-out or uncertain completion request. The transport also disables retries.
|
||||
|
||||
Close, unmount, deactivation, prescription replacement, independently replaced source state, hidden document, timeout, invalid response, provider failure and terminal state revoke intent and abort readiness reads. Generation checks discard late responses. Parent echoes of this component’s accepted DTO are ignored. Refresh is read-only, revokes automatic signing intent and requires a new explicit action to resume.
|
||||
|
||||
The verified original PDF and SHA-256 download checks are preserved.
|
||||
|
||||
## Validation
|
||||
|
||||
- `node --test tests/prescription-esign.test.cjs` in admin: 46 passed, 0 failed, including the previous 17 tests.
|
||||
- Coverage includes the complete lifecycle, read-only query transport, five-second single-flight cadence, ten-minute bound, stale SUCCESS rejection, hidden/closed/unmounted states, exactly one pending completion, unknown/failed states, official URL validation, no external navigation, Vue SFC compilation, original PDF bytes and hash validation.
|
||||
- `npm run type-check`: repository has 62 existing TypeScript diagnostics, exactly matching `admin/tests/esign-typecheck.log`; no diagnostics reference the modified API, utility or component. Current output: `admin/tests/esign-embedded-typecheck.log`.
|
||||
- LF normalized; scoped `git diff --check` passed.
|
||||
|
||||
## Integration boundary
|
||||
|
||||
No vendor requests or server mutations were performed by this work. New provider requests are configured by the backend owner for SMS-only in-system verification. Existing stored URLs do not identify their previous verification channel. They remain sandboxed; an inline explanation and “核身页面不可用” action stop the flow if an old provider page requires unsupported external navigation. Browsers do not reliably report cross-origin CSP/X-Frame-Options or in-frame provider errors to the parent; no successful embedded provider journey is claimed from local mocked tests. There is deliberately no new-window fallback.
|
||||
@@ -0,0 +1,44 @@
|
||||
# Doctor desktop embedded eSign delivery
|
||||
|
||||
Implemented the shared prescription signing dialog as a 1040 × 800 in-system screen (minimum 900 × 700). The doctor explicitly chooses **核身并签署** and sees that successful authentication will continue signing. The official authentication URL opens only in the embedded QtWebEngine view. There is no external-browser action or fallback.
|
||||
|
||||
## Safety and lifecycle
|
||||
|
||||
- Each authentication view uses an off-the-record, memory-cache profile with no persistent cookies and no application bridge. The profile outlives its page and is deleted after page teardown.
|
||||
- HTTPS navigation and network resources are restricted to official `*.esign.cn` / `*.tsign.cn` hosts; port 8890 is allowed only for the existing official `smlfront.esign.cn` sandbox host. Initial URLs retain the existing exact official entry-host allowlist.
|
||||
- Popups, custom app schemes, external navigation, uploads, downloads, clipboard privileges, device permission requests and invalid TLS certificates are denied. Blocked flows show an actionable inline error. Provider console messages are not logged.
|
||||
- Missing QtWebEngine produces an inline repair/update instruction before a start request is sent.
|
||||
- A visible, explicitly started authentication uses one read-only `GET esignIdentityStatus` at a time, every 5 seconds, bounded to 10 minutes. Its ApiClient call has `max_retries=0`; default retry behavior for unrelated GETs remains unchanged.
|
||||
- Signing is dispatched once only after a structurally valid server response has `identity_status=SUCCESS`, `can_complete=true`, `status=authenticating`, and current actor signing permission. Browser loads, redirects and client events cannot authorize completion.
|
||||
- The completion latch is set before dispatch. A timeout, error, ambiguous response or manual refresh never resubmits the signing POST from the same dialog.
|
||||
- Hide, close, failure, terminal server state and timeout stop polling. Generation checks reject stale results; callbacks verify the dialog still exists. Old webview errors cannot affect a new explicit flow. The close action remains usable during requests.
|
||||
- Manual recheck performs the identity GET and preserves an already-loaded SMS form. Signed-PDF downloads retain authoritative recheck and SHA-256 validation.
|
||||
|
||||
## Changed files
|
||||
|
||||
- `app/src/doctor_workstation/ui/dialogs/prescription_esign.py`
|
||||
- `app/src/doctor_workstation/ui/dialogs/esign_webview.py` (new)
|
||||
- `app/src/doctor_workstation/core/esign.py`
|
||||
- `app/src/doctor_workstation/services/repository.py`
|
||||
- `app/src/doctor_workstation/services/mock_repository.py`
|
||||
- `app/src/doctor_workstation/services/api_client.py` (parent-authorized per-call retry override)
|
||||
- `app/tests/test_prescription_esign.py`
|
||||
- `app/tests/test_esign_webview.py` (new)
|
||||
|
||||
Added lines use LF; unchanged baseline line endings in the large repository modules are preserved to avoid unrelated churn. `app/src/doctor_workstation/__init__.py` was not edited.
|
||||
|
||||
## Verification
|
||||
|
||||
164 passed in 1.91 seconds across `test_prescription_esign.py`, `test_esign_webview.py`, `test_api_client.py`, `test_repository_parity.py`, and `test_mock_repository.py`. Targeted Ruff checks passed. Tests cover in-system entry, no external browser, identity DTO validation, permission gating, single-flight polling, one-shot signing, timeout/error recovery, stale/hide/close callbacks, no completion on browser loads, unchanged GET retry defaults, navigation/permission/TLS restrictions and original download validation. No vendor requests or real authentication were performed by this agent.
|
||||
|
||||
Native QtWebEngine construction in the restricted execution sandbox exits with Windows code `-2147483645` at `QWebEngineProfile(parent)`, both with `offscreen` and ordinary `windows` platforms; this also reproduces with bare Qt classes outside the application code. The parent will verify the real visible launcher outside that execution restriction. No Chromium `--no-sandbox` workaround or TLS relaxation was introduced.
|
||||
|
||||
## Native initialization follow-up
|
||||
|
||||
The parent's elevated visible launch exposed a real Qt lifecycle issue: adding the first WebEngine view to an already visible dialog asynchronously recreates the native parent window. Qt emits a non-spontaneous hide/show pair after the start handler returns. The original hide handler invalidated the pending start response and removed the embedded page.
|
||||
|
||||
The fix now scopes a native-window ID check to creation of a fresh identity view. During the transient hide, polling and completion pause, and pending response callbacks defer. The flow resumes only if the same dialog is visible again with a different native-window ID. A still-hidden window, same-ID hide/show, explicit `hide()`, minimize, close, or already-completed initialization continues to cancel the flow. Normal `hideEvent` safety remains in force outside that narrow initialization transition. Renderer initialization is not identity proof and never authorizes signing.
|
||||
|
||||
Verification after this fix: **167 passed, 2 opt-in native tests skipped** in the targeted delivery set; **2 native Windows Qt tests passed in 4.38 seconds** when run elevated with `ESIGN_NATIVE_QT_TEST=1` and `QT_QPA_PLATFORM=windows`. The native test constructs the actual embedded WebEngine, verifies the native handle really changed, verifies authentication state/polling survive, and verifies a genuine user hide cancels. Both tests replace provider URL loading and use a fake repository; no provider calls occur. Ruff passed. The reproducible native tests are in `app/tests/test_esign_native_lifecycle.py`.
|
||||
|
||||
An optional combined run including `test_prescription_security_ui.py` aborted in that existing suite at line 157 (`application.processEvents()`). The isolated 164-test delivery set above subsequently passed. This broader suite was not modified.
|
||||
@@ -0,0 +1,23 @@
|
||||
# 管理端核身后补充证书绑定信息
|
||||
|
||||
## 实现
|
||||
|
||||
- `admin/src/api/tcm.ts`:只读核身 DTO 增加可选布尔值 `identity_details_required`;`esignComplete` 支持可选 `identity_number`,未提供时请求体只含 `id`,保留 180 秒超时及禁用重试配置。
|
||||
- `admin/src/utils/prescription-esign.ts`:旧服务省略标志时默认 `false`;拒绝非布尔类型、与 `can_complete` 同时为真,以及与 `SUCCESS / authenticating / can_sign` 不一致的结果。
|
||||
- `admin/src/components/EsignPrescriptionPanel.vue`:收到可信补录要求后停止核身轮询、移除核身 iframe,保留原有十分钟截止时间,在系统内显示密码式身份证号输入框及“绑定证书并签署”按钮。说明补录只用于匹配本次已完成认证的证书账户。无需外部跳转。
|
||||
- `admin/tests/prescription-esign.test.cjs`:扩充传输、校验、等待、提交和生命周期回归测试。
|
||||
|
||||
## 隐私和提交约束
|
||||
|
||||
身份证号只保存在单独的短期输入状态中,不放入签署状态 DTO、组件事件、浏览器存储或日志。提交时先清空输入;关闭、隐藏页面、卸载、组件停用、刷新、处方/来源状态更换、超时均清空并撤销意图。输入为密码类型,关闭自动补全且没有明文切换按钮。测试仅使用合成身份证号。
|
||||
|
||||
前端校验 18 位大陆身份证号形状,将末位小写 `x` 规范为大写;日期和校验位由服务端权威校验。补录不会自动发送,也不会由输入事件触发:必须在有效、可见、未过期的当前会话中点击按钮。提交前消费既有单次完成标记,网络错误、超时或不确定结果均不自动重试。证件补录请求异常使用固定错误说明,不将异常对象中的身份证号或供应商消息显示在组件中。服务端同样须提供脱敏状态和错误信封,避免共享请求拦截器回显原始供应商信息。
|
||||
|
||||
## 验证
|
||||
|
||||
- `node --test tests/prescription-esign.test.cjs`(`admin`):63 通过,0 失败;含原有 46 项测试及 17 项新增测试。
|
||||
- 覆盖等待补录期间不再轮询且不签署、明确点击只提交一次、单次标记在未返回请求期间生效、可选请求字段、错误 DTO、无可信授权时不能提交、非法输入清空、八类退出/超时清空、过期响应不能恢复补录、错误/不确定结果不重试和不显示号码,以及 Vue SFC 编译。
|
||||
- `git diff --check -- admin/src/api/tcm.ts admin/src/utils/prescription-esign.ts admin/src/components/EsignPrescriptionPanel.vue admin/tests/prescription-esign.test.cjs`:通过。
|
||||
- `npm run type-check`:退出码 2,共 62 条既有 TypeScript 诊断;与 `admin/tests/esign-embedded-typecheck.log` 完全一致,修改的 API、工具函数和组件均无诊断。当前记录为 `admin/tests/esign-identity-binding-typecheck.log`。
|
||||
|
||||
未调用供应商、访问数据库或读取凭据。仓库 `.trellis` 不存在,保留此前管理端修改及其他工作区改动;本任务不修改 `server`、`app` 或 `.spool`。
|
||||
@@ -0,0 +1,36 @@
|
||||
# eSign identity binding backend verification
|
||||
|
||||
Date: 2026-11-18. Scope: server changes and offline tests only; no real provider call, account, credentials or production database accessed.
|
||||
|
||||
## Behavior
|
||||
|
||||
- `esignIdentityStatus` remains read-only. A successful individual flow with literal `indivInfo: null` and no SDK account returns `identity_details_required: true` and `can_complete: false`.
|
||||
- `esignComplete` accepts an optional POST `identity_number`. For that precise null/unbound case, it checks mainland format, birth date, sequence and (18-digit) checksum, then passes the frozen server doctor name, transient number and validated flow ID to existing SDK `addPerson` via `createPerson`.
|
||||
- The supplemental number is input for SDK verification, not identity proof. Signing and account insertion require SDK binding success; willingness must still be valid.
|
||||
- Missing or invalid local input leaves authentication usable and requests correction. An SDK rejection cannot bind or sign.
|
||||
- Existing SDK-bound flows with null details can continue only when the current doctor account exactly matches the account ID captured when authentication began. Replacement, deletion and concurrent first-time binding remain blocked.
|
||||
- Missing, empty, masked, malformed or explicitly mismatched returned identities cannot be replaced with caller input. Wrong flow/app/object type also fails closed.
|
||||
- Snapshot, creator, environment, operation-token, final account recheck, no-resign and archival behavior are retained. Readiness and detail-required flags are mutually exclusive.
|
||||
|
||||
## Privacy
|
||||
|
||||
- No full identity number is written to prescription evidence, doctor account, PDF, DTO or server-generated error messages.
|
||||
- The completion controller rejects non-string input and never echoes it. SDK adapter exceptions contain only an operation label and a validated numeric provider code, omitting raw provider messages and bodies.
|
||||
- The existing generic operation audit listener (currently disabled in `adminapi/event.php`) now allowlists only prescription ID for completion and strips URL query parameters, including if it is re-enabled later.
|
||||
- Middleware review found no request-body logging in the active common/admin middleware. SDK transport has no body/credential logging and no automatic retry.
|
||||
- This report covers application PHP code. SDK/JVM and reverse-proxy log settings are deployment concerns handled separately by the parent task.
|
||||
|
||||
## Verification
|
||||
|
||||
All checks passed using synthetic fixtures, fake provider transport and isolated temporary SQLite, without loading `.env`:
|
||||
|
||||
- `php tests/PrescriptionEsignFlowTest.php`: **129 checks**. Null/read-only readiness, missing/invalid input, SDK rejection, verified binding input, bound-null success, binding changes, malformed/mismatched provider identity, wrong app/object, expired willingness, stale flow and privacy, plus existing signing/recovery invariants.
|
||||
- `php tests/EsignClientTest.php`: **175 checks**. Includes raw provider rejection containing a synthetic number: exception redacted; exactly one binding attempt.
|
||||
- `php tests/EsignIdentityPrivacyTest.php`: **7 checks**. Actual controller forwards only POST input/current actor, compatibility without input, array/GET rejection, response privacy and actual audit-listener persistence redaction via an in-memory model double.
|
||||
- PHP syntax checks passed for all six changed/new PHP files.
|
||||
|
||||
## Contract and project context
|
||||
|
||||
SDK contract reviewed from `.spool/esign-docs/sdk3-addperson-contract.txt`, cached by the parent from [official SDK addPerson documentation](https://open.esign.cn/doc/opendoc/paas_sdk_3/feq5f4b4x450i0ya): `name` and `idNo` must match authenticated identity, `identityAuthId` links the completed flow, and the provider limits its use to 30 minutes. No new endpoint or database schema is required.
|
||||
|
||||
`.trellis/workflow.md` is absent in this checkout, so no Trellis task/spec files could be read. No commit or deployment was performed by this worker. The tests validate implementation behavior, not a real provider signature.
|
||||
@@ -0,0 +1,33 @@
|
||||
# Desktop supplementary certificate identity binding
|
||||
|
||||
Implemented 2026-11-18 in the existing in-system prescription signature dialog.
|
||||
|
||||
## Behavior and contract
|
||||
|
||||
- `esign_identity_status` accepts optional `identity_details_required` and normalizes an absent field to `False`. Present values must be booleans. A true value is accepted only with `identity_status=SUCCESS`, `status=authenticating`, enabled/required/can_sign all true, and `can_complete=False`. Conflicting flags fail closed. The client never changes `can_complete` to authorize signing.
|
||||
- Only the validated identity-readiness GET can expose the supplementary form. Ordinary signature status responses cannot do so. The dialog stops its timer, drops the previous signing intent, and disposes the embedded authentication view while awaiting input.
|
||||
- The form explains one-time certificate binding and the requirement to match the completed authentication. It uses a password-mode `QLineEdit` with sensitive input hints and the explicit action **绑定证书并签署**. Enter in the input does not submit binding.
|
||||
- Input validation accepts the ASCII shape of legacy 15-digit or modern 18-character mainland identity numbers, with an optional final X in the latter. Client validation does not establish identity; server date/checksum/authentication matching remains authoritative.
|
||||
- Submission clears the input before asynchronous dispatch and sets the existing one-completion latch first. Invalid input clears the entry and stays in the form without dispatch. Cancel, refresh, hide, reject, and close clear the entry. No identity value is added to dialog state, persisted, or logged by this change.
|
||||
- `DoctorRepository`, `RemoteDoctorRepository`, and the demo repository accept `complete_prescription_esign(prescription_id, identity_number="")`. An absent number preserves the original one-argument/no-extra-field behavior. A supplied number is sent only in the existing completion POST body. Existing API transport behavior already prevents POST retry; no `ApiClient` change was needed for this task.
|
||||
- Completion timeout or ambiguity keeps the latch set. Manual refresh cannot repeat signing within the same dialog. Generation and deadline checks reject stale callbacks. Existing Qt native initialization hide/show handling is retained.
|
||||
|
||||
## Verification
|
||||
|
||||
From `D:\web\zyt\app`:
|
||||
|
||||
```powershell
|
||||
& .venv/Scripts/python.exe -m pytest tests/test_prescription_esign.py tests/test_esign_webview.py tests/test_esign_native_lifecycle.py tests/test_repository_parity.py tests/test_api_client.py --basetemp=.pytest-tmp-esign-identity-binding-final
|
||||
```
|
||||
|
||||
Result: **191 passed, 2 skipped** in 4.43 seconds. The skipped cases are opt-in native Qt tests. Coverage includes required-input/no-auto-sign, one explicit completion, input clearing before dispatch and across lifecycle changes, invalid shape rejection, conflicting capabilities, legacy DTO compatibility, stale callbacks, timeout uncertainty, body-only identity transmission, no POST retry, repository parity, and existing embedded-browser behavior.
|
||||
|
||||
Ruff passed for all modified Python files. `git diff --check` passed for the modified desktop files.
|
||||
|
||||
Real Windows Qt verification used `ESIGN_NATIVE_QT_TEST=1`, `QT_QPA_PLATFORM=windows`, and the existing `test_esign_native_lifecycle.py`. Each parameterized case passed in its own process outside the process-restricted sandbox: normal native recreation **1 passed in 3.34 seconds**; genuine user hide **1 passed in 2.83 seconds**. These tests use a fake repository and replace provider URL loading.
|
||||
|
||||
The sandbox native run aborted while initializing WebEngine. An elevated combined run reached both passing assertion markers but exited with code 1 before pytest's final summary; it is not counted as a clean combined pass. The isolated native runs completed with exit code 0. No test or application native-lifecycle implementation was changed to suppress that behavior.
|
||||
|
||||
## Scope
|
||||
|
||||
Changed only desktop core validation, repository interfaces/implementation, signature dialog, tests, and this report. Preserved the existing user change to `app/src/doctor_workstation/__init__.py`. No provider requests, real identity numbers, signing operations, or business database operations were used for this work. The live wrapper and server implementation are separate deliverables; this report does not claim an end-to-end live signature succeeded.
|
||||
@@ -0,0 +1,41 @@
|
||||
# e签宝 SDK3 身份信息返回核对
|
||||
|
||||
核对日期:2026-11-18。范围仅为官方公开文档及既有公开文档缓存;未读取凭据、调用业务 API 或访问数据库。根任务已确认当前响应为 `SUCCESS / INDIVIDUAL / indivInfo: null`,并已核对应用归属。
|
||||
|
||||
## 结论
|
||||
|
||||
**没有找到官方支持的“仅凭 identityAuthId 创建个人签署账号”或“由 SDK 根据 flowId 反查完整姓名、证件号”的接口。** 当前公开协议仍要求 `name`、`idNo`,且必须与认证信息一致。`indivInfo: null` 无法通过 JSON 解码、换子流程接口或取消一致性校验解决。
|
||||
|
||||
当前可落实的处理是:保留认证成功状态,但在取得与该流程一致的完整身份信息前阻止创建/绑定签署账号;由 e签宝技术顾问核查该应用/流程为何未返回个人基本信息及授权配置。**“平台隐私配置导致 null”目前只是待核实假设,不能写成已确认原因,也没有查到可直接添加的公开返回开关。** 不需要要求用户在聊天中发送身份证号。
|
||||
|
||||
## 已核实的协议
|
||||
|
||||
| 核对项 | 官方协议与实际意义 |
|
||||
| --- | --- |
|
||||
| `GET /v2/identity/auth/api/common/{flowId}/detail` | 请求只有路径 `flowId`。`data.indivInfo` 类型为可选 object,包含 `name`、`certNo`、`certType`;不是 JSON 字符串或密文协议。示例证件号带星号,但文档没有说明这代表真实响应的固定脱敏规则,不能用示例推出必须能拿到完整号码。[查询认证信息](https://open.esign.cn/doc/opendoc/identity_service/duoa44) |
|
||||
| 个人信息返回权限 | 查询文档对照片、视频、银行卡开户行/地明确列有额外开通条件;对 `name` / `certNo` 未说明类似开关。不能把影像权限当作个人基本信息返回权限。[查询认证信息](https://open.esign.cn/doc/opendoc/identity_service/duoa44) |
|
||||
| SDK3 `account/addPerson` | `name` 和 `idNo` 均必填。`identityAuthId` 是认证成功的 `flowId`,须在 30 分钟内使用,并保证姓名、证件号与流程一致。3.1.13 起只放宽了 `identityAuthId` 必填性,没有放宽姓名/证件号。`encrypt` 控制本接口的用户信息传输加密,不是 `/detail` 的解密开关。[创建个人签署账号](https://open.esign.cn/doc/opendoc/paas_sdk_3/feq5f4b4x450i0ya) |
|
||||
| SDK3.1.26 | 2026-11-12 变更新增部分证件类型及企业授权 `applyCert`;没有 flowId 单参数建号能力的更新。[SDK3 更新日志](https://open.esign.cn/doc/opendoc/paas_sdk_3/gt8ahfp92gd5mwkd) |
|
||||
| SDK3 `auth/queryWillingnessValidity` | 根据 `willingnessId` 查询可用性、过期时间、剩余次数;没有姓名或证件号响应字段。[查询个人认证 ID 有效性](https://open.esign.cn/doc/opendoc/paas_sdk_3/lza8ew9a1ha5xnko) |
|
||||
| 主流程与子流程 | `/outline` 返回流程、关联流程及子流程状态;`/process?subFlowId=…` 返回步骤类型、状态与时间。二者用于对账,没有个人基本信息,不能作为补取身份证号接口。[主流程](https://open.esign.cn/doc/opendoc/identity_service/dkbcel)、[子流程](https://open.esign.cn/doc/opendoc/identity_service/btvruu) |
|
||||
| 认证完成回调 | 返回 `flowId`、`success`、上下文等;明确核身认证不返回 `accountId`。没有姓名/证件号。旧版实名回调示例中的 accountId 不适用于当前核身流程。[个人认证完成通知](https://open.esign.cn/doc/opendoc/identity_service/giq1w40lx67vwofr)、[常见 QA](https://open.esign.cn/doc/opendoc/identity_service/shimingqa) |
|
||||
| 创建账号后认证 | `indivAuthUrl` 支持 `sdkAccountId`,会校验账号与用户信息一致后绑定数字证书。这适用于已合法持有完整身份信息、先建号的流程,不能解决现有 null 响应中的身份信息缺失。`usageType` 是证书发放用途,不是身份信息返回开关。[获取个人核身认证地址](https://open.esign.cn/doc/opendoc/identity_service/sg2nty) |
|
||||
|
||||
SDK3 官方接入说明仍指向身份服务的详情查询与完成回调,没有另列 SDK 专属认证信息补取接口。[个人核身认证和数字证书申领](https://open.esign.cn/doc/opendoc/paas_sdk_3/adq41ivoxu30t0kr)
|
||||
|
||||
## 供应商核查需要确认的具体问题
|
||||
|
||||
1. 在应用与流程归属一致、`status=SUCCESS`、`objectType=INDIVIDUAL` 时,`indivInfo=null` 是否由该沙箱应用配置、认证通道或流程异常导致?公开沙箱说明未记载这是模拟环境的预期行为。[身份服务沙箱说明](https://open.esign.cn/doc/opendoc/identity_service/so4gfc)
|
||||
2. 该应用是否获准通过 `/detail` 读取认证成功主体的完整 `name/certNo`;如果需要额外授权或配置,请提供官方配置名、适用环境及对应文档。
|
||||
3. SDK3 `addPerson` 必须保持实名一致性;若完整身份信息不允许返回,供应商是否提供已正式支持的服务端绑定接口或流程?需要明确接口、版本和参数,不能自行猜测。
|
||||
|
||||
通过供应商的受控支持渠道提交应用 ID、流程 ID、认证方式及脱敏状态摘要即可定位;不在研究文件或聊天中保存真实身份证号、姓名、认证链接、凭据或原始个人响应。
|
||||
|
||||
## 可复核的公开缓存
|
||||
|
||||
- `.spool/esign-docs/esign-identity-query.{txt,html}`:既有官方详情协议。
|
||||
- `.spool/esign-docs/sdk3-addperson-contract.txt`、`sdk3-auth-validity-contract.txt`:本次下载的创建账号/有效性协议。
|
||||
- `.spool/esign-docs/identity-main.txt`、`identity-child.txt`、`identity-callback.txt`、`identity-qa.txt`:替代查询路径核对。
|
||||
- `.spool/esign-docs/sdk3-auth.txt`、`sdk3-guide.txt`、`sdk3-changelog.txt`、`identity-sandbox.txt`、`sdk3-sandbox.txt`:接入、版本及环境说明。
|
||||
|
||||
说明:仓库 `.trellis/workflow.md` 不存在;本子任务仅生成研究材料,没有修改业务代码。
|
||||
@@ -0,0 +1,106 @@
|
||||
# e签宝真实沙箱联调入口
|
||||
|
||||
入口:`.spool/esign-live/harness.php`。它调用项目真实 `EsignClient`、`PrescriptionEsignService`、`PrescriptionEsignPolicy`、`PrescriptionPdf` 与 ThinkPHP ORM,不替换供应商响应。
|
||||
|
||||
本机执行请使用 `.spool/esign-live/run.ps1`,它仅为当前 PHP 子进程配置经过校验的 CA 证书集,保持 TLS 校验开启;不改全局 php.ini。
|
||||
|
||||
## 隔离范围
|
||||
|
||||
- 只创建 `.spool/esign-live/fixture.sqlite`,不初始化 ThinkPHP 应用,不加载业务数据库配置,不连接或写入现有业务数据库。
|
||||
- 仅从 `server/.env` 读取 `[ESIGN]` 段;不修改文件。内存配置 `enabled=true`,强制 `sandbox` 和 `http://127.0.0.1:8091/paas-sdk-service`。
|
||||
- SDK 初始化由已有独立运行流程负责。入口核对 `.spool/esign-runtime/` 的进程及初始化凭证,不执行 SDK initialize,也不自动重启。
|
||||
- SQLite 结构取自项目流程测试采用的方法与正式迁移。使用一个独立随机医生 ID、一条固定持久化虚构处方;后续调用复用同一记录,姓名不同的 prepare 被拒绝,不提供 reset/delete/自动恢复命令。
|
||||
- 固定合成患者为“沙箱固定虚构患者001”,药材为“测试药材”,临床诊断和医嘱明确“非诊疗、禁止服用和发药”。源 PDF 由真实项目渲染器生成。
|
||||
|
||||
## 操作
|
||||
|
||||
在项目根目录执行:
|
||||
|
||||
```powershell
|
||||
.\.spool\esign-live\run.ps1 prepare --doctor-name=医生完整实名
|
||||
.\.spool\esign-live\run.ps1 start
|
||||
.\.spool\esign-live\run.ps1 status
|
||||
.\.spool\esign-live\run.ps1 identity-status
|
||||
.\.spool\esign-live\run.ps1 complete
|
||||
.\.spool\esign-live\run.ps1 download
|
||||
.\.spool\esign-live\run.ps1 verify
|
||||
```
|
||||
|
||||
也可在 `.spool/esign-live/doctor.private.json` 放置仅含 `doctor_name` 的对象,然后运行:
|
||||
|
||||
```powershell
|
||||
php .spool/esign-live/harness.php prepare --doctor-file=.spool/esign-live/doctor.private.json
|
||||
```
|
||||
|
||||
不要在参数或 JSON 中提供证件号码。JSON 仅接受 `doctor_name` 字段。`prepare --dry-run` 使用内存 SQLite,仅检查构建与服务状态,不建立持久 fixture,也不联网。
|
||||
|
||||
| 命令 | 行为 | 供应商网络调用 |
|
||||
| --- | --- | --- |
|
||||
| prepare | 创建或核对唯一隔离 fixture,本地渲染检查 | 无 |
|
||||
| status | 真实服务只读状态、已知流水与证据摘要;SQLite query_only | 无 |
|
||||
| start | 显式创建或复用核身流程,输出可信认证 URL | 核身发起;复用状态时不重发 |
|
||||
| identity-status | 读取核身 API,仅输出 status、flow_id;SQLite query_only | 只读核身查询 |
|
||||
| complete | 核身、意愿、账号、签章、签署、归档和验签的真实服务流程 | 依服务状态执行;无自动重试 |
|
||||
| download | 获取本地归档的供应商签署原件并验证 SHA-256;SQLite query_only | 无 |
|
||||
| verify | 对已签原件重新请求真实验签,并检查本地规则 | 真实验签,不重签 |
|
||||
|
||||
`start` 只有在用户明确授权发起时执行。用户在供应商页面完成核身后,再运行 `identity-status` 与 `complete`。默认请求超时为 300 秒,可使用 `--timeout=1..300`;发生超时后先查看状态,不自动重复 complete。入口使用非阻塞独占锁,拒绝并发 CLI 命令。
|
||||
|
||||
## 输出与完成检查
|
||||
|
||||
- `status` 不输出 auth_url。仅 `start` 输出该 URL;报告与本文均不保存核身链接。
|
||||
- `identity-status` 不输出姓名、证件号、证书或供应商原始对象。服务收到的完整身份证号码仅在内存中用于绑定账号,不持久化到业务证据表或 harness 输出。
|
||||
- stdout 不输出配置、凭据、原始响应或异常堆栈。供应商异常只保留安全 operation/code;其他异常使用通用错误,已知服务提示还会进行 URL、证件格式和配置值脱敏。
|
||||
- 状态摘要保留实际状态、存储状态、flow_id、已知 sign_service_id、账号是否绑定、冻结快照摘要、源文件和签署文件摘要、归档标记与时间,以排查 failed、signing、uncertain。
|
||||
- `uncertain` 不会被本入口清空或自动恢复,不会触发自动重签。`failed` 也不自动重试,需要人工阅读诊断后显式决定后续动作。
|
||||
- `complete` 达到 signed 后自动检查:`assertSignedById` 允许审核、沙箱发药被拒绝、`assertMutable` 拒绝修改、已签 complete 重放返回 signed 且完整签署证据未变化。真实服务的 signed 分支在供应商调用前返回。
|
||||
- `download` 将原始字节保存为 `.spool/esign-live/downloaded-signed.pdf`,比较服务返回 SHA-256、内存字节 SHA-256 和落盘 SHA-256;已有不同文件拒绝覆盖。
|
||||
- `verify` 仅接受 signed,不恢复 uncertain;调用真实供应商验签后记录有效签名数量与上述本地规则结果到 `.spool/esign-live/verification-summary.json`,不保存供应商证书或章图原始响应。
|
||||
|
||||
## 本轮已执行验证
|
||||
|
||||
2026-11-18:PHP 语法检查通过;`prepare --doctor-name=本地校验医生 --dry-run` 成功使用内存 SQLite,真实服务返回 pending,当前内容与初始快照一致;随后 `status` 返回 prepared=false,确认尚未建立持久 fixture。未执行 start、identity-status、complete 或 verify,未触发核身、签署或其他供应商调用。
|
||||
|
||||
后续根代理真实联调:已按用户提供的实名准备唯一虚构处方,原 PDF 已生成并渲染检查。首次核身调用因 PHP 未配置 CA 证书集而失败(cURL 60);从 `https://curl.se/ca/cacert.pem` 下载官方 CA 集并核对官方 SHA-256,摘要为 `427c064216761a1e72a8b30f0d954d08cb6e4435a82091fb865afd20c8497285`。通过 `run.ps1` 为当前子进程设置 `curl.cainfo` 后,真实核身流程创建成功,服务状态 `authenticating`。已将供应商链接交给用户本人操作,当前核身 API 返回 `INIT`;签署与下载验签尚待核身完成。
|
||||
|
||||
同时将 `EsignClient::startIdentity` 的认证用途明确设为 `CERTAPPLY`。离线适配器 169 项、隔离流程 64 项检查通过。
|
||||
|
||||
## 覆盖边界
|
||||
|
||||
本入口覆盖真实供应商适配器与真实业务服务、ORM、文件归档和审核/发药规则的隔离联调。它没有经过网页登录、真实管理员令牌、HTTP 控制器/中间件、前端认证弹窗/轮询或实际业务 MySQL,因此不能据此宣称真实网页登录端到端验收完成。真实核身、实际签署和下载验签结果,应由后续显式调用的状态与证据确认。
|
||||
|
||||
## 系统内交互入口(2026-11-18)
|
||||
|
||||
用户明确要求系统内核身后,增加 `.spool/esign-live/launch_embedded.py`,直接实例化医生工作站实际的 `PrescriptionEsignDialog`,通过本地 PHP CLI 调用上述同一条隔离处方与真实供应商服务,不替换业务签署代码。运行方式为 `app/.venv/Scripts/pythonw.exe .spool/esign-live/launch_embedded.py`。该窗口标题明确标注“隔离沙箱联调”,不影响已打开的日常业务窗口。
|
||||
|
||||
配套 `ui-status` 返回当前医生的完整签署 DTO,`ui-identity-status` 调用真实业务的只读核身接口,仅额外返回 `identity_status` 和 `can_complete`。身份证信息不返回该窗口;签署仍须通过服务端重新校验。新的供应商核身请求限定短信三要素方式;已经存在的核身流程保留原供应商配置,不伪造其认证方式或结果。
|
||||
|
||||
后端适配器 170 项、隔离业务流程 82 项检查通过;真实沙箱核身查询返回 `INIT` / `can_complete=false`。网页内嵌组件 46 项检查通过。桌面相关 167 项及另外 2 项真实 Qt 初始化测试通过。
|
||||
|
||||
已在本机启动实际桌面组件,修复 Qt 首次创建 WebEngine 导致原窗口隐藏/重建而错误取消流程的问题。修复后重新启动,并通过桌面 UI 首次点击“核身并签署”,观察到真实 e签宝“个人实名认证”页面、姓名锁定字段、手机认证选项和证书协议均显示在工作站内部。未打开外部浏览器;未代替本人填写证件或接受协议。
|
||||
|
||||
用户随后在内嵌页面选择手机号认证并尝试继续,供应商弹窗明确返回“该认证方式余额不足”“请联系管理员进行充值后再试”。只读取错误提示,未记录用户证件或手机号。当前真实阻塞为沙箱手机号认证可用额度;处方仍为 `authenticating`,没有签署流水或签后文件。官方[沙箱 SDK 说明](https://open.esign.cn/doc/opendoc/paas_sdk_3/pndhqggzc2mar20y)要求将 App ID 与产品名称告知 e签宝工作人员申请免费调试套餐。未支付费用或发送对外消息。额度补充后继续本人核身、签署、验签和原件下载。
|
||||
|
||||
该交互入口覆盖实际桌面组件及业务服务,但仍绕过线上 HTTP 登录及真实业务 MySQL。网页 iframe 对真实供应商的完整人工认证也尚未验收。仓库整体 TypeScript 检查仍有原有 62 项诊断,本次修改文件没有新增诊断。
|
||||
|
||||
## 核身成功后的证书绑定(2026-11-18)
|
||||
|
||||
用户开通沙箱认证额度后,在系统内嵌页面以支付宝扫码完成本人核身。真实详情接口已返回 `SUCCESS / INDIVIDUAL`,流程与应用匹配,但 `indivInfo` 为 literal `null`。原实现要求完整个人信息,因此在创建账号前阻断,没有发出 PDF 签署调用。官方查询协议把个人信息标为可选对象;不能把空值报告成实际实名不匹配,也不能只凭 `SUCCESS` 跳过证书绑定。
|
||||
|
||||
官方 SDK 创建个人账号仍要求姓名、证件号码和匹配的 `identityAuthId`。系统补充步骤由医生在遮挡输入框输入证件号,使用服务端冻结姓名与现有流程交给 SDK 校验绑定。该值只经子进程 stdin 传入 `complete-with-identity`,不进入命令参数、环境变量、JSON 文件、SQLite 或响应;绑定、签署仍由真实业务服务完成。详情缺失与明确返回不匹配分别处理,不允许补充输入覆盖明确的身份不一致。
|
||||
|
||||
本机 SDK 自带日志原先可能记录业务请求。已将所有 Log4j2 appender 的消息及异常正文移除,仅保留时间、级别和日志类;60 秒配置热重载后,使用既有无身份信息的未签 PDF 验签请求验证 `default.log` 和 `error.log` 均只记录 `[SDK payload omitted for identity privacy]`。原有日志没有删除。PHP 适配器继续只输出安全操作名及错误码。
|
||||
|
||||
本节记录实施过程,最终签署、验签和下载结果以运行证据及后续验收记录为准。
|
||||
|
||||
## 当前实际验收结果
|
||||
|
||||
2026-11-18 14:01:54–14:01:55(UTC+8),本人在实际桌面组件内填写补充证件信息并显式点击绑定签署。服务端通过本地证件格式、日期、校验位及真实授权有效性检查,随后真实 `createPerson` 返回 `PROVIDER_403`,服务记录为 `failed`。没有账号绑定、签署流水或签后 PDF,冻结内容与原快照一致;因此签署、验签和下载尚未跑通。未自动重发账号创建或签署。
|
||||
|
||||
只读对照查询不存在的测试账号时,同一 SDK 返回 `331003`,证明账号查询链路可达。官方公开错误码工具对 403 有接口权限、IP 白名单及文件上传等不同解释,不能把数字等同于实名不一致。当前优先核查该应用的 SDK 创建账号接口授权,具体原因仍需供应商定位。可转交材料见 `artifacts/esign-sandbox-support-request.md`;未代发消息或工单。
|
||||
|
||||
本轮离线校验:业务流程 129 项、适配器最终 181 项、控制器/日志隐私 7 项;网页签署 63 项;桌面相关套件 191 项通过、2 项原生 opt-in 跳过,两个原生场景分别独立通过。根侧补充窗口截止时间及中性核身提示后,签署窗口 114 项回归通过;Ruff 与全局 diff 空白检查通过。组合原生测试曾在两个断言通过后异常退出,未计为干净通过;网页整体 TypeScript 保留原有 62 条诊断。
|
||||
|
||||
权限确认后的续测:原核身授权仍有效,真实服务恢复到补充证书信息状态;用户在系统中再次提交后仍为 403。随后优雅重启 SDK、重新初始化成功,再次系统内提交于 14:17:35–14:17:36 仍被拒绝。已增加严格白名单式安全原因分类,适配器 297 项离线检查通过;此次未识别到明确原因。已确认 e签宝 SDK 连接经过本机 TUN 后命中 DIRECT,国内出口查询仍为 123.14.175.249,没有修改代理设置。详见 `artifacts/esign-network-diagnosis.md`。签署、验签、下载仍未完成,不能把失败记录标成已签。
|
||||
|
||||
新版三步流程在 2026-11-18 15:13:43(北京时间)实际完成签署账号绑定,但 PDF 签署返回 `PROVIDER_10002`。该签署错误码在 e签宝公开工具中对应签署次数不足。已为签署调用补上额度提示,SDK 初始化错误沿用独立处理。当前处方仍保留原始 PDF、内容摘要和账号绑定,后续新建的核身流程已查到 `INIT`。需先补齐电子签名 SDK 3.0 沙箱签署次数,再由本人继续核身并确认签名。尚无可用于验签、下载的签后原件。
|
||||
@@ -0,0 +1,22 @@
|
||||
# e签宝沙箱出口与 403 复核
|
||||
|
||||
时间:2026-11-18,Asia/Shanghai。
|
||||
|
||||
## 实测网络路径
|
||||
|
||||
- Windows 显式代理关闭,WinHTTP 为 Direct access。当前 Java SDK JVM 没有 HTTP、HTTPS、SOCKS 或系统代理属性。
|
||||
- 本机 `Mihomo / Meta Tunnel` 网卡为 Up,存在覆盖公网的 TUN 路由;`smlopenapi.esign.cn` 解析为 `198.18.0.10`。不能仅凭系统代理开关关闭判断流量未进入代理软件。
|
||||
- 通过现有 Mihomo 本地控制管道只读查询 `/connections`,实际 SDK 连接 `smlitsm.tsign.cn` 与 `smltech.tsign.cn` 均显示 `chains=["DIRECT"]`、`rule=RuleSet`、`rulePayload=ChinaMax-NoIPv6`。这些连接经过 TUN 后最终直连,没有选择代理节点。
|
||||
- 国内公网 IP 查询返回 `123.14.175.249`,与先前提供的白名单地址一致。e签宝服务端记录的具体请求源 IP仍应由其后台日志确认。
|
||||
- 未修改代理、TUN、DNS、路由、规则、系统设置或应用白名单。控制密钥仅在内存中用于已有本地只读接口,没有输出或保存。
|
||||
|
||||
## 权限确认后的真实重试
|
||||
|
||||
- 用户确认权限与白名单后,系统内提交仍得到 `createPerson / PROVIDER_403`。
|
||||
- 本机 SDK 已优雅重启,新 JVM 沙箱初始化成功,排除了继续沿用原 JVM 配置的情况。
|
||||
- 刷新后的系统内提交在 `2026-11-18 14:17:35–14:17:36 +08:00` 仍返回 `createPerson / PROVIDER_403`。安全分类器未识别到明确的接口授权、IP 白名单或签名不匹配短语,不能依数字或默认提示认定原因。
|
||||
- 账号未绑定,`sign_service_id` 为空,签后 PDF 未生成;尚未进入 PDF 签署阶段。原件与冻结摘要不变,没有自动重发签署。
|
||||
|
||||
需要 e签宝按应用、核身流程、接口和准确时间定位服务端拒绝说明。当前不能将“代理节点 IP 不在白名单”或“接口权限未开通”作为已证实原因。
|
||||
|
||||
核查信息见 [供应商排查材料](esign-sandbox-support-request.md)。仅整理证据,未发送对外消息或工单。
|
||||
@@ -32,9 +32,9 @@ BT /F1 11 Tf 1 0 0 1 45 648 Tm <836f54c100200031ff1a752891cf0020003100300020002f
|
||||
BT /F1 11 Tf 1 0 0 1 45 630 Tm <4ee3714eff1a5426> Tj ET
|
||||
0.7 w 45 133 m 550 133 l S
|
||||
BT /F1 12 Tf 1 0 0 1 45 110 Tm <5f0065b9533b5e08ff1a6d4b8bd5533b5e08> Tj ET
|
||||
BT /F1 11 Tf 1 0 0 1 420 117 Tm <533b5e0875355b507b7e7ae0> Tj ET
|
||||
BT /F1 11 Tf 1 0 0 1 420 104 Tm <533b5e0875355b507b7e7ae0> Tj ET
|
||||
BT /F1 8 Tf 1 0 0 1 45 58 Tm <590465b95feb71670020005300480041002d003200350036> Tj ET
|
||||
BT /F1 7 Tf 1 0 0 1 45 44 Tm <0063006200660063003000640039003500630062006600620062003600360037006400620062006500300064003400390038003700320064003500350030006300660062006200360031003400310063003900650066006100640036003200370032003100320038003200620038006100340038006400650036006600650030> Tj ET
|
||||
BT /F1 7 Tf 1 0 0 1 45 44 Tm <0039003300660065006100390065006300610063003400310064003700300031003400370032006200330036003800610036006400350030003000330035003400330033003400620034006300390032003600370035006600320066006100300062003800660033003300370036006100380063006100320036003000300032> Tj ET
|
||||
BT /F1 9 Tf 1 0 0 1 515 30 Tm <00310020002f00200031> Tj ET
|
||||
endstream
|
||||
endobj
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
# e签宝本机 PaaS-SDK-Service 运行环境
|
||||
|
||||
准备日期:2026-11-17。完成便携 Java 与 Tomcat 下载、校验、解压和本机配置;本次没有取得或启动 SDK WAR,没有初始化应用或读取 `.env`。以下状态是运行环境准备完成时的快照,不代表后续 SDK 部署结果。
|
||||
安装日期:2026-11-17;最后验证:2026-11-18。官方 SDK 3.1.26 已部署并运行,沙箱初始化成功。合成未签 PDF 的真实验签接口检查通过;医生核身和处方实签尚未执行。
|
||||
|
||||
## 同日后续部署结果
|
||||
## 部署与验证结果
|
||||
|
||||
根侧已通过用户登录后的[供应商官方附件页](https://qianxiaoxia.yuque.com/opendoc/helper/venkq12cg9vxgf3f?singleDoc)下载 2026-11-11 发布的 **3.1.26** Windows All-In-One 包,159 个应用文件已部署至下述 Tomcat 的 `webapps/paas-sdk-service/`。包内是展开应用,核心依赖为 `paas-sdk-core-3.1.26.jar`。未运行包内旧版 Java;使用本文安装的 Temurin 与 Tomcat。
|
||||
|
||||
@@ -10,14 +10,17 @@
|
||||
- 本机计算的 SHA256:`f107a5f67c0ebf7e1e1e1e0d012b6111637b26ce8599445090ffb931ebcf1b8d`。供应商页面未提供独立校验值,此哈希用于记录取得的文件,不代表独立签名验证。
|
||||
- 删除分发包中的示例应用凭据;`autoInit=false`,改为沙箱 HTTPS 初始化地址,`httpRetryTimes=0`。实际凭据仅由服务端忽略的 `.env` 读取后用于初始化,不写入命令行或启动脚本。
|
||||
- 已在隐藏窗口启动并确认服务首页 HTTP **200**,标题 `PaaS-SDK-Service`;仅 `127.0.0.1:8091` 和 `127.0.0.1:8092` 监听。
|
||||
- 已通过项目真实 PHP 适配器请求初始化,SDK 联系到 e签宝云端,返回 **338005:应用 IP 白名单未配置**。尚不能宣称初始化成功或完成签署。等待用户配置云端应用的白名单。
|
||||
- 2026-11-17 首次初始化返回 `338005`(应用 IP 白名单未配置)。2026-11-18 用户完成白名单配置后,使用项目真实 PHP 适配器重试,**沙箱初始化成功**。同一进程再次执行初始化助手会直接跳过,已验证没有重复调用初始化。
|
||||
- 真实调用 `/timevale/verify/pdf` 上传新生成的虚构未签 PDF,SDK 完成解析并返回 `70003`(文件没有盖章),符合负向测试预期。该检查验证 HTTP、multipart 和 PDF 解析,不能代替已签原件的验签。
|
||||
- 初始化后的本地日志未检出应用 secret。未连接业务数据库、创建签署账号或签署处方;业务开关仍为关闭。
|
||||
- 已实际验证正常停服和再次隐藏启动,重启后首页仍为 HTTP 200;修正 PowerShell JSON 自动日期转换造成的进程时间比较问题,PID 与 Java 路径核验保持有效。
|
||||
|
||||
白名单配置完成后运行:
|
||||
SDK 每次启动后初始化;同一进程重复运行会安全跳过:
|
||||
|
||||
```powershell
|
||||
php 'D:\web\zyt\.spool\esign-runtime\initialize-sdk.php'
|
||||
# 可选:仅使用新生成的虚构未签 PDF 检查文件接口
|
||||
php 'D:\web\zyt\.spool\esign-runtime\check-sdk.php'
|
||||
```
|
||||
|
||||
此助手仅初始化本机沙箱,不启动业务框架或连接业务数据库。成功后记录当前 SDK 进程,重复执行会跳过相同进程的重复初始化;更换应用配置需先重启 SDK。SDK 每次重启后,先执行本文件的启动脚本,再执行初始化助手。该运行目录不是临时缓存,不要清理 `.spool/esign-runtime`;未设置开机自启。
|
||||
@@ -43,7 +46,7 @@ php 'D:\web\zyt\.spool\esign-runtime\initialize-sdk.php'
|
||||
|
||||
选择仍维护的 Tomcat 9,保留 Java EE / `javax.servlet` 兼容体系;不采用已结束维护的 Tomcat 8.5,也不迁移到 `jakarta.servlet`。Apache 的[版本对照](https://tomcat.apache.org/whichversion.html)确认 Tomcat 9.0.124 支持 Java 8 及以上,8.5 已结束支持。Java 使用官方 API 当日提供的 Java 8 补丁版 Temurin 8u512-b09。
|
||||
|
||||
**尚待验证:** 这个组合符合 Java 8 与 Java EE 的运行时基线,但并非供应商列出的精确测试组合。须拿到官方 WAR 后验证部署、SDK 沙箱初始化、调用及 PDF 输出,不能由 Java/Tomcat 版本检查推断业务兼容性。
|
||||
**兼容性验证范围:** 已完成官方应用部署、真实沙箱初始化和未签 PDF 解析检查。医生核身、实际签署、签后 PDF 验签与下载的完整业务闭环尚待测试医生参与验证。
|
||||
|
||||
## 官方下载和校验
|
||||
|
||||
@@ -100,4 +103,4 @@ cfe11a042e5c3acc02ca4715ef80f3de599980e46729556be08e2a4078a61c9fed625cc804b1660b
|
||||
- 通过 `org.apache.catalina.util.ServerInfo` 读取包版本成功:Tomcat `9.0.124`,构建日期 2026-11-09,APR 未加载。该命令未启动服务器。
|
||||
- 两个 PowerShell 脚本通过语法解析,XML 可解析,只有一个 HTTP connector。
|
||||
- 检查时 `webapps` 为空,8091 和 8092 都没有监听进程。
|
||||
- 未运行 Tomcat 启动、SDK 初始化、核身、签署或真实业务调用。
|
||||
- 后续已完成 Tomcat 启停、真实沙箱初始化和未签 PDF 解析,结果见本文开头;未执行核身或签署。
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
# 沙箱 SDK 创建签署账号 403 核查信息
|
||||
|
||||
可复制给现有 e签宝实施/交付顾问。本文件仅整理材料,未代为发送任何消息或工单。
|
||||
|
||||
更新:用户已确认接口权限及白名单。SDK 已重启且重新初始化成功,但 `2026-11-18 14:17:35–14:17:36 +08:00` 的系统内实际提交仍返回 `createPerson / PROVIDER_403`。Mihomo 实时连接显示 SDK 域名 `smlitsm.tsign.cn`、`smltech.tsign.cn` 都是 `DIRECT`,国内公网查询为 `123.14.175.249`;没有走代理节点。请按这次准确时间查询服务端拒绝日志、实际源 IP 和具体拒绝说明,而不只是重复确认控制台勾选状态。完整实测见 `artifacts/esign-network-diagnosis.md`。
|
||||
|
||||
---
|
||||
|
||||
请协助核查以下沙箱 SDK 3.0 接入问题:
|
||||
|
||||
- 应用 ID:`7439151893`,企业自用应用,SDK 3.0 方案。
|
||||
- 服务版本:官方 PaaS-SDK-Service / core `3.1.26`。
|
||||
- 失败时间:`2026-11-18 14:01:54–14:01:55 +08:00`。
|
||||
- 调用接口:`POST /paas-sdk-service/timevale/account/addPerson`。
|
||||
- 实际响应:HTTP `200`,JSON `errCode=403`;应用记录为 `createPerson / PROVIDER_403`。出于身份信息保护,没有保存原始响应正文,因此未记录原始 `msg`。
|
||||
- 前置状态:SDK 沙箱初始化成功;本人在系统内以支付宝扫码完成核身;认证查询为 `SUCCESS / INDIVIDUAL`,应用和流程一致;提交绑定前 `queryWillingnessValidity` 校验通过。
|
||||
- 核身流程 ID:`4868530341519822468`。
|
||||
- 核身查询补充问题:该成功流程的 `indivInfo` 返回 `null`,没有姓名和证件信息。请同时确认这是应用/通道的预期行为,还是返回配置异常。
|
||||
- 绑定参数包含服务端冻结姓名、本人在系统中补充的证件号、`idNoType=MAINLAND` 和该 `identityAuthId`。未省略核身流程来绕过认证。证件号未写入本材料或业务库。
|
||||
- 只读连通性对照:同一 SDK 的 `account/queryByAccountId` 对固定不存在的测试标识返回正常业务码 `331003`(账号信息异常或不存在),并非所有 SDK 账号接口均失败。
|
||||
- 当前没有取得账号 ID,没有发起 PDF 签署,没有签署流水或签后 PDF。
|
||||
|
||||
请核查:
|
||||
|
||||
1. 该沙箱应用是否已获准调用 SDK 3 的创建个人签署账号、证书申请及个人 PDF 签署接口,尤其是 `addPerson` 所需的接口权限。
|
||||
2. 请根据上述时间、应用、流程定位 403 的实际拒绝原因,并复核该请求所见公网出口 IP 与对应 SDK 应用白名单。
|
||||
3. 如果是接口权限缺失,请开通本次已申请的 SDK 处方签署沙箱联调能力;如果另有条件,请提供准确错误说明与操作步骤。
|
||||
|
||||
核查无需应用 Secret、身份证号码、手机验证码或完整个人信息。
|
||||
|
||||
---
|
||||
|
||||
依据:[官方错误码查询](https://open.esign.cn/tools/error-code)对 403 给出多种场景,包括“该应用无权调用此接口”和 IP 白名单不匹配。当前“接口权限优先核查”是结合现场证据的排查判断,尚未得到供应商确认。
|
||||
@@ -0,0 +1,207 @@
|
||||
from pathlib import Path
|
||||
from datetime import datetime, timezone, timedelta
|
||||
import configparser
|
||||
import hashlib
|
||||
import html
|
||||
import json
|
||||
import sys
|
||||
|
||||
import pymysql
|
||||
|
||||
sys.stdout.reconfigure(encoding='utf-8')
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
OUT = Path(__file__).resolve().parent
|
||||
TZ = timezone(timedelta(hours=8))
|
||||
ORDER_NOS = ['PO20261024092136816172', 'PO20260924112640923356', 'PO20260908142548426588']
|
||||
|
||||
|
||||
def date_time(value):
|
||||
return datetime.fromtimestamp(int(value), TZ).strftime('%Y-%m-%d %H:%M:%S') if value else '—'
|
||||
|
||||
|
||||
def add_dates(rows):
|
||||
for row in rows:
|
||||
for key, value in list(row.items()):
|
||||
if (key.endswith('_time') or key in ('created_at', 'updated_at', 'claimed_at', 'completed_at', 'failed_at')) and isinstance(value, (int, type(None))):
|
||||
row[key + '_beijing'] = date_time(value)
|
||||
return rows
|
||||
|
||||
|
||||
cfg = configparser.ConfigParser(interpolation=None, strict=False)
|
||||
cfg.read_string('[root]\n' + (ROOT / 'server/.env').read_text(encoding='utf-8-sig'))
|
||||
settings = {k: v.strip().strip(chr(34)).strip(chr(39)) for k, v in cfg['database'].items()}
|
||||
db = pymysql.connect(host=settings['hostname'], port=int(settings.get('hostport', '3306')),
|
||||
user=settings['username'], password=settings['password'], database=settings['database'],
|
||||
charset='utf8mb4', connect_timeout=8, read_timeout=30, write_timeout=5,
|
||||
cursorclass=pymysql.cursors.DictCursor)
|
||||
queries = []
|
||||
try:
|
||||
with db.cursor() as cur:
|
||||
cur.execute('START TRANSACTION READ ONLY')
|
||||
|
||||
def query(title, sql, args=None):
|
||||
queries.append('-- ' + title + '\n' + cur.mogrify(sql, args) + ';')
|
||||
cur.execute(sql, args)
|
||||
return add_dates(list(cur.fetchall()))
|
||||
|
||||
orders = query('指定三个处方业务订单(不包含收货电话与地址)', '''
|
||||
SELECT id,order_no,prescription_id,diagnosis_id,creator_id,amount,paid,fee_type,
|
||||
medication_days,dose_unit,dose_count,ship_mode,tracking_number,express_company,
|
||||
gancao_reciperl_order_no,gancao_submit_time,ej_pharmacy_order_no,ej_pharmacy_submit_time,
|
||||
ej_pharmacy_status,ej_pharmacy_review_status,ej_pharmacy_current_step,
|
||||
prescription_audit_status,prescription_audit_remark,payment_slip_audit_status,
|
||||
payment_slip_audit_remark,fulfillment_status,create_time,update_time,delete_time
|
||||
FROM zyt_tcm_prescription_order WHERE order_no IN (%s,%s,%s)''', ORDER_NOS)
|
||||
assert {o['order_no'] for o in orders} == set(ORDER_NOS), '三个订单未全部命中'
|
||||
order_ids = [o['id'] for o in orders]
|
||||
rx_ids = [o['prescription_id'] for o in orders]
|
||||
prescriptions = query('关联处方当前记录;创建时间不是独立操作日志', '''
|
||||
SELECT id,sn,patient_name,doctor_name,creator_id,assistant_id,is_system_auto,
|
||||
prescription_name,prescription_type,prescription_date,dose_count,dose_unit,
|
||||
usage_days,times_per_day,amount,create_time,update_time,
|
||||
audit_status,audit_time,audit_by,audit_by_name,audit_remark,
|
||||
void_status,void_time,void_by_name,delete_time
|
||||
FROM zyt_tcm_prescription WHERE id IN (%s,%s,%s)''', rx_ids)
|
||||
logs = query('全部订单流水,原始日志姓名保持不变', '''
|
||||
SELECT id,prescription_order_id,admin_id,admin_name,action,summary,create_time
|
||||
FROM zyt_tcm_prescription_order_log WHERE prescription_order_id IN (%s,%s,%s)
|
||||
ORDER BY prescription_order_id,create_time,id''', order_ids)
|
||||
callbacks = query('对应洛阳药房回传', '''
|
||||
SELECT id,event_id,pharmacy_order_no,source_order_no,event_type,status_version,
|
||||
payload,process_status,processed_time,error_message,create_time,update_time
|
||||
FROM zyt_ej_pharmacy_callback_inbox WHERE source_order_no IN (%s,%s,%s) ORDER BY id''', ORDER_NOS)
|
||||
payload_fields = {'status','event_id','event_type','occurred_at','review_status','source_system',
|
||||
'status_version','express_company','source_order_no','source_revision',
|
||||
'tracking_number','pharmacy_order_no','current_step','operator_name','pharmacist_name'}
|
||||
for row in callbacks:
|
||||
payload = json.loads(row.pop('payload') or '{}')
|
||||
row['payload_selected_fields'] = {k: v for k, v in payload.items() if k in payload_fields}
|
||||
ai_events = query('处方分析触发元数据,仅用于辅助核对,不等同开方日志', '''
|
||||
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 IN (%s,%s,%s) ORDER BY id''', rx_ids)
|
||||
staff_ids = sorted({v for o in orders for v in [o['creator_id']]} |
|
||||
{v for r in prescriptions for v in [r['creator_id'],r['assistant_id'],r['audit_by']]} |
|
||||
{l['admin_id'] for l in logs if l['admin_id']})
|
||||
staff = query('相关账号当前名称及角色;不覆盖历史日志署名', '''
|
||||
SELECT a.id,a.name,GROUP_CONCAT(r.name ORDER BY r.id SEPARATOR '、') AS roles
|
||||
FROM zyt_admin a LEFT JOIN zyt_admin_role ar ON ar.admin_id=a.id
|
||||
LEFT JOIN zyt_system_role r ON r.id=ar.role_id
|
||||
WHERE a.id IN (''' + ','.join(['%s']*len(staff_ids)) + ') GROUP BY a.id,a.name', staff_ids)
|
||||
coverage = query('后台操作日志表覆盖范围', '''
|
||||
SELECT COUNT(*) AS total,MIN(create_time) AS earliest_time,MAX(create_time) AS latest_time
|
||||
FROM zyt_operation_log''')[0]
|
||||
operation_candidates = query('后台处方端点的历史请求候选,只输出日志元信息与关联所需标识', '''
|
||||
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 %s ORDER BY create_time,id''', ('%tcm.prescription%',))
|
||||
operation_logs = []
|
||||
for row in operation_candidates:
|
||||
is_order = 'prescriptionorder/' in row['endpoint'].lower()
|
||||
ids = set(map(str, order_ids if is_order else rx_ids))
|
||||
if row['request_id'] in ids or row['response_id'] in ids or row['request_prescription_id'] in set(map(str,rx_ids)) or row['request_diagnosis_id'] in set(map(str,[o['diagnosis_id'] for o in orders])):
|
||||
operation_logs.append(row)
|
||||
freshness = query('当前库订单表最新创建记录的时间(不代表同步时间)', 'SELECT MAX(create_time) AS latest_order_create_time FROM zyt_tcm_prescription_order')[0]
|
||||
finally:
|
||||
db.rollback()
|
||||
db.close()
|
||||
|
||||
notes = [
|
||||
'来源:项目 server/.env 指向的本机 MySQL 数据库 zyt(127.0.0.1:3306)。未核实与生产库同步情况;本报告仅证明当前查询库中保存的记录。',
|
||||
'所有展示时间均为北京时间 UTC+08:00;JSON 同时保留 Unix 原始时间戳。查询使用只读事务,未修改业务数据。',
|
||||
'开方栏取自处方主记录 doctor_name、creator_id、create_time;它是当前处方记录,并非独立的开方保存、修改操作流水。',
|
||||
'审方日志原始 admin_name 三笔均为“药房”。本报告另列同一账号 ID 对应的处方 audit_by_name,以及同单相邻操作日志署名,保留来源差异。',
|
||||
'账号 116 当前名为“药房1”,账号 119 当前名为“药房”;当前角色为下单等。焦珂、李思佳为审核字段/历史日志署名,不据此认定实名登录人或执业资质。',
|
||||
'当前代码 server/app/adminapi/event.php 的 HttpEnd 监听器为空,关闭了通用后台操作日志写入;这不能证明历史所有时段均关闭。',
|
||||
'药房回调的日志时间为本系统落库时间;如载荷提供 occurred_at,则在回传明细中另列原值。'
|
||||
]
|
||||
if not operation_logs:
|
||||
notes.append('未检索到关联这三个订单/处方的通用后台请求日志,不能提供完整的逐次开方、修改请求历史。')
|
||||
if not ai_events:
|
||||
notes.append('处方 AI 批次表中也未检索到这三个处方的分析触发记录。')
|
||||
|
||||
data = {'export_time_beijing':datetime.now(TZ).isoformat(timespec='seconds'),
|
||||
'source':{'config':'server/.env','host':settings['hostname'],'port':int(settings.get('hostport','3306')),
|
||||
'database':settings['database'],'production_sync_verified':False},
|
||||
'requested_order_numbers':ORDER_NOS,'notes':notes,'orders':orders,'prescriptions':prescriptions,
|
||||
'order_logs':logs,'pharmacy_callbacks':callbacks,'operation_logs':operation_logs,
|
||||
'prescription_ai_events':ai_events,'staff_current':staff,'operation_log_coverage':coverage,
|
||||
'source_freshness_indicator':freshness}
|
||||
json_path = OUT / '处方订单及日志_原始字段.json'
|
||||
json_path.write_text(json.dumps(data, ensure_ascii=False, indent=2, default=str)+'\n',encoding='utf-8')
|
||||
(OUT/'只读查询.sql').write_text('SET time_zone = \'+08:00\';\nSTART TRANSACTION READ ONLY;\n\n'+'\n\n'.join(queries)+'\n\nROLLBACK;\n',encoding='utf-8')
|
||||
|
||||
by_rx = {r['id']:r for r in prescriptions}
|
||||
by_staff = {s['id']:s for s in staff}
|
||||
audit_actions = {'audit_rx_approve','audit_rx_reject','revoke_rx_audit','manual_log'}
|
||||
status_names = {1:'待双审通过',2:'履约中',3:'已完成',4:'已取消',5:'已发货',6:'已签收'}
|
||||
lines = ['三个处方业务订单:开方记录与药房操作日志', '导出时间:'+data['export_time_beijing'], '']
|
||||
lines.extend(notes)
|
||||
lines.extend(['',f"当前库订单表最新创建时间:{freshness['latest_order_create_time_beijing']}(仅供判断数据范围,不代表同步时间)",
|
||||
f"订单操作日志共 {len(logs)} 条;匹配后台请求日志 {len(operation_logs)} 条;AI 触发记录 {len(ai_events)} 条;洛阳药房原始回传 {len(callbacks)} 条。",''])
|
||||
summaries = []
|
||||
for no in ORDER_NOS:
|
||||
order = next(o for o in orders if o['order_no']==no)
|
||||
rx = by_rx[order['prescription_id']]
|
||||
own_logs = [l for l in logs if l['prescription_order_id']==order['id']]
|
||||
own_audits = [l for l in own_logs if l['action'] in audit_actions]
|
||||
summaries.append({'order_no':no,'patient_name':rx['patient_name'],'doctor_name':rx['doctor_name'],
|
||||
'prescription_create_time':rx['create_time_beijing'],'audit_by_name':rx['audit_by_name'],
|
||||
'audit_time':rx['audit_time_beijing'],'logs':len(own_logs)})
|
||||
lines.extend(['='*88,no,
|
||||
f"患者:{rx['patient_name']};诊单 ID:{order['diagnosis_id']};业务订单 ID:{order['id']}",
|
||||
f"处方:{rx['sn']}(ID {rx['id']});类型:{rx['prescription_type']};名称:{rx['prescription_name']}",
|
||||
f"处方记录医生:{rx['doctor_name']}(creator_id={rx['creator_id']});创建时间:{rx['create_time_beijing']};处方日期:{rx['prescription_date']}",
|
||||
f"业务订单创建人:{by_staff.get(order['creator_id'],{}).get('name','未知')}(ID {order['creator_id']});创建时间:{order['create_time_beijing']}",
|
||||
f"金额:{order['amount']};已付:{order['paid']};状态:{status_names.get(order['fulfillment_status'],order['fulfillment_status'])}",
|
||||
f"处方审核字段:{rx['audit_by_name']}(账号 ID {rx['audit_by']});{rx['audit_time_beijing']};audit_status={rx['audit_status']};{rx['audit_remark']}",
|
||||
f"发货方式:{order['ship_mode']};甘草订单:{order['gancao_reciperl_order_no'] or '无'};洛阳药房订单:{order['ej_pharmacy_order_no'] or '无'}",'',
|
||||
f"审方/撤审/人工补记日志({len(own_audits)} 条)"])
|
||||
for log in own_audits:
|
||||
lines.append(f"{log['create_time_beijing']} | 日志 {log['id']} | 原始署名 {log['admin_name']} / 账号 {log['admin_id']} | {log['action']} | {log['summary']}")
|
||||
lines.extend(['',f'完整订单操作流水({len(own_logs)} 条,按时间、日志 ID 升序)'])
|
||||
for log in own_logs:
|
||||
lines.append(f"{log['create_time_beijing']} | 日志 {log['id']} | {log['admin_name']} / 账号 {log['admin_id']} | {log['action']} | {log['summary']}")
|
||||
lines.append('')
|
||||
lines.extend(['='*88,'洛阳药房回传明细',json.dumps(callbacks,ensure_ascii=False,indent=2,default=str),
|
||||
'关联开方/修改后台请求日志',json.dumps(operation_logs,ensure_ascii=False,indent=2,default=str),
|
||||
'关联 AI 分析触发元数据(不等同开方日志)',json.dumps(ai_events,ensure_ascii=False,indent=2,default=str)])
|
||||
text_path = OUT/'处方订单及日志_完整明细.txt'
|
||||
text_path.write_text('\n'.join(lines)+'\n',encoding='utf-8-sig')
|
||||
|
||||
|
||||
def table(headers, rows):
|
||||
return '<table><thead><tr>'+''.join('<th>'+html.escape(str(h))+'</th>' for h in headers)+'</tr></thead><tbody>'+''.join('<tr>'+''.join('<td>'+html.escape(str(v if v is not None else '—'))+'</td>' for v in row)+'</tr>' for row in rows)+'</tbody></table>'
|
||||
|
||||
|
||||
parts = ['<!doctype html><html lang="zh-CN"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>三个处方订单日志</title>',
|
||||
'<style>body{font-family:system-ui,"Microsoft YaHei",sans-serif;color:#202733;background:#f7f8fa;margin:0;padding:32px}main{max-width:1400px;margin:auto}h1{font-size:28px}h2{margin-top:36px;font-size:22px}p,li{line-height:1.8}table{width:100%;border-collapse:collapse;background:white;margin:18px 0;font-size:14px}th,td{border:1px solid #d9dfe6;padding:10px;text-align:left;vertical-align:top}th{background:#edf1f5}pre{white-space:pre-wrap;overflow-wrap:anywhere;background:white;padding:20px;border:1px solid #d9dfe6}.note{color:#525c6d}a{color:#155c9e}@media print{body{padding:0;background:white}tr{break-inside:avoid}h2{break-before:page}}</style><main>',
|
||||
'<h1>三个处方业务订单 · 开方记录与药房日志</h1>',
|
||||
'<p>导出时间:'+html.escape(data['export_time_beijing'])+'。全部时间为北京时间。</p>',
|
||||
'<ul class="note">'+''.join('<li>'+html.escape(n)+'</li>' for n in notes)+'</ul>',
|
||||
table(['业务订单','患者','处方记录医生','处方创建时间','审核字段署名','审核时间','订单日志数'],
|
||||
[[s[k] for k in ['order_no','patient_name','doctor_name','prescription_create_time','audit_by_name','audit_time','logs']] for s in summaries]),
|
||||
'<p>订单流水共 '+str(len(logs))+' 条。<a href="处方订单及日志_完整明细.txt">完整文本</a> · <a href="处方订单及日志_原始字段.json">JSON 原始字段</a> · <a href="只读查询.sql">只读 SQL</a></p>']
|
||||
for no in ORDER_NOS:
|
||||
order=next(o for o in orders if o['order_no']==no);rx=by_rx[order['prescription_id']]
|
||||
parts.extend(['<h2>'+html.escape(no)+'</h2>',
|
||||
table(['字段','记录值'],[['业务订单 ID',order['id']],['处方号 / ID',f"{rx['sn']} / {rx['id']}"],
|
||||
['医生及处方创建时间',f"{rx['doctor_name']} / {rx['create_time_beijing']}"],
|
||||
['业务订单创建人及时间',f"{by_staff.get(order['creator_id'],{}).get('name','未知')} / {order['create_time_beijing']}"],
|
||||
['处方审核字段',f"{rx['audit_by_name']} / 账号 {rx['audit_by']} / {rx['audit_time_beijing']} / {rx['audit_remark']}"],
|
||||
['金额 / 已付 / 状态',f"{order['amount']} / {order['paid']} / {status_names.get(order['fulfillment_status'],order['fulfillment_status'])}"]]),
|
||||
table(['时间','日志 ID','原始署名','账号 ID','动作','内容'],
|
||||
[[l['create_time_beijing'],l['id'],l['admin_name'],l['admin_id'],l['action'],l['summary']] for l in logs if l['prescription_order_id']==order['id']])])
|
||||
parts.extend(['<h2>补充来源与回传记录</h2><pre>'+html.escape(json.dumps({'operation_log_coverage':coverage,'source_freshness_indicator':freshness,'pharmacy_callbacks':callbacks,'matched_operation_logs':operation_logs,'ai_trigger_events':ai_events},ensure_ascii=False,indent=2,default=str))+'</pre></main></html>'])
|
||||
html_path=OUT/'处方订单及日志_查看版.html'
|
||||
html_path.write_text('\n'.join(parts),encoding='utf-8')
|
||||
manifest={p.name:hashlib.sha256(p.read_bytes()).hexdigest() for p in [json_path,text_path,html_path,OUT/'只读查询.sql']}
|
||||
(OUT/'sha256.json').write_text(json.dumps(manifest,ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
|
||||
print(json.dumps({'summary':summaries,'order_log_count':len(logs),'operation_log_count':len(operation_logs),
|
||||
'ai_event_count':len(ai_events),'callback_count':len(callbacks),'report_path':str(html_path),
|
||||
'freshness':freshness,'coverage':coverage},ensure_ascii=False,default=str,indent=2))
|
||||
BIN
Binary file not shown.
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"处方订单及日志_原始字段.json": "b80563ad72a27cc9bb7779c669358e2e6f1a7fc5bad34c6d33f6fb793f1537eb",
|
||||
"处方订单及日志_完整明细.txt": "66d6cf807138681511e034cf35a8bbeda9fcc6cb10f2a8341c0930b72f556dec",
|
||||
"处方订单及日志_查看版.html": "1556be7f8109e2d1fefd3bed62ec96943c574a8049dfb2689df1cd872871a17e",
|
||||
"只读查询.sql": "5e925ce06a803ace2a13dadc825cf91be9746c105e81778c7cf45a11744fa262"
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
SET time_zone = '+08:00';
|
||||
START TRANSACTION READ ONLY;
|
||||
|
||||
-- 指定三个处方业务订单(不包含收货电话与地址)
|
||||
|
||||
SELECT id,order_no,prescription_id,diagnosis_id,creator_id,amount,paid,fee_type,
|
||||
medication_days,dose_unit,dose_count,ship_mode,tracking_number,express_company,
|
||||
gancao_reciperl_order_no,gancao_submit_time,ej_pharmacy_order_no,ej_pharmacy_submit_time,
|
||||
ej_pharmacy_status,ej_pharmacy_review_status,ej_pharmacy_current_step,
|
||||
prescription_audit_status,prescription_audit_remark,payment_slip_audit_status,
|
||||
payment_slip_audit_remark,fulfillment_status,create_time,update_time,delete_time
|
||||
FROM zyt_tcm_prescription_order WHERE order_no IN ('PO20261024092136816172','PO20260924112640923356','PO20260908142548426588');
|
||||
|
||||
-- 关联处方当前记录;创建时间不是独立操作日志
|
||||
|
||||
SELECT id,sn,patient_name,doctor_name,creator_id,assistant_id,is_system_auto,
|
||||
prescription_name,prescription_type,prescription_date,dose_count,dose_unit,
|
||||
usage_days,times_per_day,amount,create_time,update_time,
|
||||
audit_status,audit_time,audit_by,audit_by_name,audit_remark,
|
||||
void_status,void_time,void_by_name,delete_time
|
||||
FROM zyt_tcm_prescription WHERE id IN (9787,10615,11945);
|
||||
|
||||
-- 全部订单流水,原始日志姓名保持不变
|
||||
|
||||
SELECT id,prescription_order_id,admin_id,admin_name,action,summary,create_time
|
||||
FROM zyt_tcm_prescription_order_log WHERE prescription_order_id IN (3751,4087,4583)
|
||||
ORDER BY prescription_order_id,create_time,id;
|
||||
|
||||
-- 对应洛阳药房回传
|
||||
|
||||
SELECT id,event_id,pharmacy_order_no,source_order_no,event_type,status_version,
|
||||
payload,process_status,processed_time,error_message,create_time,update_time
|
||||
FROM zyt_ej_pharmacy_callback_inbox WHERE source_order_no IN ('PO20261024092136816172','PO20260924112640923356','PO20260908142548426588') ORDER BY id;
|
||||
|
||||
-- 处方分析触发元数据,仅用于辅助核对,不等同开方日志
|
||||
|
||||
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 IN (9787,10615,11945) ORDER BY id;
|
||||
|
||||
-- 相关账号当前名称及角色;不覆盖历史日志署名
|
||||
|
||||
SELECT a.id,a.name,GROUP_CONCAT(r.name ORDER BY r.id SEPARATOR '、') AS roles
|
||||
FROM zyt_admin a LEFT JOIN zyt_admin_role ar ON ar.admin_id=a.id
|
||||
LEFT JOIN zyt_system_role r ON r.id=ar.role_id
|
||||
WHERE a.id IN (12,28,116,119,203,204,279,284) GROUP BY a.id,a.name;
|
||||
|
||||
-- 后台操作日志表覆盖范围
|
||||
|
||||
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%' ORDER BY create_time,id;
|
||||
|
||||
-- 当前库订单表最新创建记录的时间(不代表同步时间)
|
||||
SELECT MAX(create_time) AS latest_order_create_time FROM zyt_tcm_prescription_order;
|
||||
|
||||
ROLLBACK;
|
||||
@@ -0,0 +1,896 @@
|
||||
{
|
||||
"export_time_beijing": "2026-11-18T16:50:09+08:00",
|
||||
"source": {
|
||||
"config": "server/.env",
|
||||
"host": "127.0.0.1",
|
||||
"port": 3306,
|
||||
"database": "zyt",
|
||||
"production_sync_verified": false
|
||||
},
|
||||
"requested_order_numbers": [
|
||||
"PO20261024092136816172",
|
||||
"PO20260924112640923356",
|
||||
"PO20260908142548426588"
|
||||
],
|
||||
"notes": [
|
||||
"来源:项目 server/.env 指向的本机 MySQL 数据库 zyt(127.0.0.1:3306)。未核实与生产库同步情况;本报告仅证明当前查询库中保存的记录。",
|
||||
"所有展示时间均为北京时间 UTC+08:00;JSON 同时保留 Unix 原始时间戳。查询使用只读事务,未修改业务数据。",
|
||||
"开方栏取自处方主记录 doctor_name、creator_id、create_time;它是当前处方记录,并非独立的开方保存、修改操作流水。",
|
||||
"审方日志原始 admin_name 三笔均为“药房”。本报告另列同一账号 ID 对应的处方 audit_by_name,以及同单相邻操作日志署名,保留来源差异。",
|
||||
"账号 116 当前名为“药房1”,账号 119 当前名为“药房”;当前角色为下单等。焦珂、李思佳为审核字段/历史日志署名,不据此认定实名登录人或执业资质。",
|
||||
"当前代码 server/app/adminapi/event.php 的 HttpEnd 监听器为空,关闭了通用后台操作日志写入;这不能证明历史所有时段均关闭。",
|
||||
"药房回调的日志时间为本系统落库时间;如载荷提供 occurred_at,则在回传明细中另列原值。",
|
||||
"未检索到关联这三个订单/处方的通用后台请求日志,不能提供完整的逐次开方、修改请求历史。"
|
||||
],
|
||||
"orders": [
|
||||
{
|
||||
"id": 3751,
|
||||
"order_no": "PO20260908142548426588",
|
||||
"prescription_id": 9787,
|
||||
"diagnosis_id": 12167,
|
||||
"creator_id": 279,
|
||||
"amount": "1400.00",
|
||||
"paid": "1400.00",
|
||||
"fee_type": 3,
|
||||
"medication_days": 14,
|
||||
"dose_unit": "剂",
|
||||
"dose_count": 1,
|
||||
"ship_mode": "direct",
|
||||
"tracking_number": "JDVE18948527288",
|
||||
"express_company": "auto",
|
||||
"gancao_reciperl_order_no": "",
|
||||
"gancao_submit_time": 0,
|
||||
"ej_pharmacy_order_no": null,
|
||||
"ej_pharmacy_submit_time": 0,
|
||||
"ej_pharmacy_status": "",
|
||||
"ej_pharmacy_review_status": "",
|
||||
"ej_pharmacy_current_step": "",
|
||||
"prescription_audit_status": 1,
|
||||
"prescription_audit_remark": "",
|
||||
"payment_slip_audit_status": 1,
|
||||
"payment_slip_audit_remark": "",
|
||||
"fulfillment_status": 3,
|
||||
"create_time": 1788848748,
|
||||
"update_time": 1790492528,
|
||||
"delete_time": null,
|
||||
"gancao_submit_time_beijing": "—",
|
||||
"ej_pharmacy_submit_time_beijing": "—",
|
||||
"create_time_beijing": "2026-09-08 14:25:48",
|
||||
"update_time_beijing": "2026-09-27 15:02:08",
|
||||
"delete_time_beijing": "—"
|
||||
},
|
||||
{
|
||||
"id": 4087,
|
||||
"order_no": "PO20260924112640923356",
|
||||
"prescription_id": 10615,
|
||||
"diagnosis_id": 12167,
|
||||
"creator_id": 284,
|
||||
"amount": "1800.00",
|
||||
"paid": "0.00",
|
||||
"fee_type": 7,
|
||||
"medication_days": 21,
|
||||
"dose_unit": "剂",
|
||||
"dose_count": 10,
|
||||
"ship_mode": "gancao",
|
||||
"tracking_number": "SF5155771371889",
|
||||
"express_company": "auto",
|
||||
"gancao_reciperl_order_no": "G17902378442302734",
|
||||
"gancao_submit_time": 1790237844,
|
||||
"ej_pharmacy_order_no": null,
|
||||
"ej_pharmacy_submit_time": 0,
|
||||
"ej_pharmacy_status": "",
|
||||
"ej_pharmacy_review_status": "",
|
||||
"ej_pharmacy_current_step": "",
|
||||
"prescription_audit_status": 1,
|
||||
"prescription_audit_remark": "",
|
||||
"payment_slip_audit_status": 1,
|
||||
"payment_slip_audit_remark": "",
|
||||
"fulfillment_status": 3,
|
||||
"create_time": 1790220400,
|
||||
"update_time": 1790468903,
|
||||
"delete_time": null,
|
||||
"gancao_submit_time_beijing": "2026-09-24 16:17:24",
|
||||
"ej_pharmacy_submit_time_beijing": "—",
|
||||
"create_time_beijing": "2026-09-24 11:26:40",
|
||||
"update_time_beijing": "2026-09-27 08:28:23",
|
||||
"delete_time_beijing": "—"
|
||||
},
|
||||
{
|
||||
"id": 4583,
|
||||
"order_no": "PO20261024092136816172",
|
||||
"prescription_id": 11945,
|
||||
"diagnosis_id": 12167,
|
||||
"creator_id": 284,
|
||||
"amount": "1800.00",
|
||||
"paid": "1800.00",
|
||||
"fee_type": 7,
|
||||
"medication_days": 21,
|
||||
"dose_unit": "剂",
|
||||
"dose_count": 10,
|
||||
"ship_mode": "direct",
|
||||
"tracking_number": "JDVE19405836801",
|
||||
"express_company": "auto",
|
||||
"gancao_reciperl_order_no": "",
|
||||
"gancao_submit_time": 0,
|
||||
"ej_pharmacy_order_no": "EJ202610261004182FA855",
|
||||
"ej_pharmacy_submit_time": 1792980258,
|
||||
"ej_pharmacy_status": "PENDING_REVIEW",
|
||||
"ej_pharmacy_review_status": "PENDING",
|
||||
"ej_pharmacy_current_step": "",
|
||||
"prescription_audit_status": 1,
|
||||
"prescription_audit_remark": "",
|
||||
"payment_slip_audit_status": 1,
|
||||
"payment_slip_audit_remark": "",
|
||||
"fulfillment_status": 3,
|
||||
"create_time": 1792804896,
|
||||
"update_time": 1793434806,
|
||||
"delete_time": null,
|
||||
"gancao_submit_time_beijing": "—",
|
||||
"ej_pharmacy_submit_time_beijing": "2026-10-26 10:04:18",
|
||||
"create_time_beijing": "2026-10-24 09:21:36",
|
||||
"update_time_beijing": "2026-10-31 16:20:06",
|
||||
"delete_time_beijing": "—"
|
||||
}
|
||||
],
|
||||
"prescriptions": [
|
||||
{
|
||||
"id": 9787,
|
||||
"sn": "RX202609078921",
|
||||
"patient_name": "雷柏生",
|
||||
"doctor_name": "赵俊霞",
|
||||
"creator_id": 28,
|
||||
"assistant_id": 279,
|
||||
"is_system_auto": 0,
|
||||
"prescription_name": "系统代开",
|
||||
"prescription_type": "浓缩水丸",
|
||||
"prescription_date": "2026-09-07",
|
||||
"dose_count": 14,
|
||||
"dose_unit": "剂",
|
||||
"usage_days": 14,
|
||||
"times_per_day": 3,
|
||||
"amount": "0.00",
|
||||
"create_time": 1788774166,
|
||||
"update_time": 1788925728,
|
||||
"audit_status": 1,
|
||||
"audit_time": 1788925728,
|
||||
"audit_by": 116,
|
||||
"audit_by_name": "焦珂",
|
||||
"audit_remark": "业务订单处方审核通过",
|
||||
"void_status": 0,
|
||||
"void_time": null,
|
||||
"void_by_name": "",
|
||||
"delete_time": null,
|
||||
"create_time_beijing": "2026-09-07 17:42:46",
|
||||
"update_time_beijing": "2026-09-09 11:48:48",
|
||||
"audit_time_beijing": "2026-09-09 11:48:48",
|
||||
"void_time_beijing": "—",
|
||||
"delete_time_beijing": "—"
|
||||
},
|
||||
{
|
||||
"id": 10615,
|
||||
"sn": "RX202609238774",
|
||||
"patient_name": "雷柏生",
|
||||
"doctor_name": "赵俊霞",
|
||||
"creator_id": 28,
|
||||
"assistant_id": 284,
|
||||
"is_system_auto": 0,
|
||||
"prescription_name": "系统代开",
|
||||
"prescription_type": "浓缩水丸",
|
||||
"prescription_date": "2026-09-23",
|
||||
"dose_count": 21,
|
||||
"dose_unit": "剂",
|
||||
"usage_days": 21,
|
||||
"times_per_day": 3,
|
||||
"amount": "0.00",
|
||||
"create_time": 1790156255,
|
||||
"update_time": 1790237839,
|
||||
"audit_status": 1,
|
||||
"audit_time": 1790237839,
|
||||
"audit_by": 116,
|
||||
"audit_by_name": "焦珂",
|
||||
"audit_remark": "业务订单处方审核通过",
|
||||
"void_status": 0,
|
||||
"void_time": null,
|
||||
"void_by_name": "",
|
||||
"delete_time": null,
|
||||
"create_time_beijing": "2026-09-23 17:37:35",
|
||||
"update_time_beijing": "2026-09-24 16:17:19",
|
||||
"audit_time_beijing": "2026-09-24 16:17:19",
|
||||
"void_time_beijing": "—",
|
||||
"delete_time_beijing": "—"
|
||||
},
|
||||
{
|
||||
"id": 11945,
|
||||
"sn": "RX202610233553",
|
||||
"patient_name": "雷柏生",
|
||||
"doctor_name": "霍桢毅",
|
||||
"creator_id": 12,
|
||||
"assistant_id": 284,
|
||||
"is_system_auto": 0,
|
||||
"prescription_name": "系统代开",
|
||||
"prescription_type": "浓缩水丸",
|
||||
"prescription_date": "2026-10-23",
|
||||
"dose_count": 21,
|
||||
"dose_unit": "剂",
|
||||
"usage_days": 21,
|
||||
"times_per_day": 3,
|
||||
"amount": "0.00",
|
||||
"create_time": 1792748278,
|
||||
"update_time": 1792980254,
|
||||
"audit_status": 1,
|
||||
"audit_time": 1792980254,
|
||||
"audit_by": 119,
|
||||
"audit_by_name": "李思佳",
|
||||
"audit_remark": "业务订单处方审核通过",
|
||||
"void_status": 0,
|
||||
"void_time": null,
|
||||
"void_by_name": "",
|
||||
"delete_time": null,
|
||||
"create_time_beijing": "2026-10-23 17:37:58",
|
||||
"update_time_beijing": "2026-10-26 10:04:14",
|
||||
"audit_time_beijing": "2026-10-26 10:04:14",
|
||||
"void_time_beijing": "—",
|
||||
"delete_time_beijing": "—"
|
||||
}
|
||||
],
|
||||
"order_logs": [
|
||||
{
|
||||
"id": 52702,
|
||||
"prescription_order_id": 3751,
|
||||
"admin_id": 279,
|
||||
"admin_name": "董肖妍",
|
||||
"action": "create",
|
||||
"summary": "创建业务订单",
|
||||
"create_time": 1788848748,
|
||||
"create_time_beijing": "2026-09-08 14:25:48"
|
||||
},
|
||||
{
|
||||
"id": 52953,
|
||||
"prescription_order_id": 3751,
|
||||
"admin_id": 116,
|
||||
"admin_name": "焦珂",
|
||||
"action": "set_ship_mode",
|
||||
"summary": "发货类型:甘草药房 → 洛阳药房",
|
||||
"create_time": 1788922716,
|
||||
"create_time_beijing": "2026-09-09 10:58:36"
|
||||
},
|
||||
{
|
||||
"id": 53013,
|
||||
"prescription_order_id": 3751,
|
||||
"admin_id": 116,
|
||||
"admin_name": "焦珂",
|
||||
"action": "edit",
|
||||
"summary": "编辑了业务订单及相关信息",
|
||||
"create_time": 1788925616,
|
||||
"create_time_beijing": "2026-09-09 11:46:56"
|
||||
},
|
||||
{
|
||||
"id": 53014,
|
||||
"prescription_order_id": 3751,
|
||||
"admin_id": 116,
|
||||
"admin_name": "药房",
|
||||
"action": "audit_rx_approve",
|
||||
"summary": "处方审核通过",
|
||||
"create_time": 1788925728,
|
||||
"create_time_beijing": "2026-09-09 11:48:48"
|
||||
},
|
||||
{
|
||||
"id": 53015,
|
||||
"prescription_order_id": 3751,
|
||||
"admin_id": 116,
|
||||
"admin_name": "焦珂",
|
||||
"action": "audit_pay_approve",
|
||||
"summary": "支付单审核通过",
|
||||
"create_time": 1788925731,
|
||||
"create_time_beijing": "2026-09-09 11:48:51"
|
||||
},
|
||||
{
|
||||
"id": 53255,
|
||||
"prescription_order_id": 3751,
|
||||
"admin_id": 204,
|
||||
"admin_name": "徐云云",
|
||||
"action": "ship",
|
||||
"summary": "确认发货(药房直发),运单:JDVE18948527288(auto)",
|
||||
"create_time": 1789005730,
|
||||
"create_time_beijing": "2026-09-10 10:02:10"
|
||||
},
|
||||
{
|
||||
"id": 54095,
|
||||
"prescription_order_id": 3751,
|
||||
"admin_id": 0,
|
||||
"admin_name": "系统",
|
||||
"action": "auto_sign",
|
||||
"summary": "物流签收(运单:JDVE18948527288),订单状态自动更新为「已签收」",
|
||||
"create_time": 1789183814,
|
||||
"create_time_beijing": "2026-09-12 11:30:14"
|
||||
},
|
||||
{
|
||||
"id": 58339,
|
||||
"prescription_order_id": 3751,
|
||||
"admin_id": 116,
|
||||
"admin_name": "焦珂",
|
||||
"action": "complete",
|
||||
"summary": "订单完成,状态变更为「已完成」,实付金额更新为 ¥1400",
|
||||
"create_time": 1790492528,
|
||||
"create_time_beijing": "2026-09-27 15:02:08"
|
||||
},
|
||||
{
|
||||
"id": 57681,
|
||||
"prescription_order_id": 4087,
|
||||
"admin_id": 284,
|
||||
"admin_name": "晁婷婷",
|
||||
"action": "create",
|
||||
"summary": "创建业务订单",
|
||||
"create_time": 1790220400,
|
||||
"create_time_beijing": "2026-09-24 11:26:40"
|
||||
},
|
||||
{
|
||||
"id": 57792,
|
||||
"prescription_order_id": 4087,
|
||||
"admin_id": 116,
|
||||
"admin_name": "焦珂",
|
||||
"action": "set_ship_mode",
|
||||
"summary": "发货类型:甘草药房 → 洛阳药房",
|
||||
"create_time": 1790237688,
|
||||
"create_time_beijing": "2026-09-24 16:14:48"
|
||||
},
|
||||
{
|
||||
"id": 57793,
|
||||
"prescription_order_id": 4087,
|
||||
"admin_id": 116,
|
||||
"admin_name": "焦珂",
|
||||
"action": "set_ship_mode",
|
||||
"summary": "发货类型:洛阳药房 → 甘草药房",
|
||||
"create_time": 1790237694,
|
||||
"create_time_beijing": "2026-09-24 16:14:54"
|
||||
},
|
||||
{
|
||||
"id": 57798,
|
||||
"prescription_order_id": 4087,
|
||||
"admin_id": 116,
|
||||
"admin_name": "焦珂",
|
||||
"action": "edit",
|
||||
"summary": "编辑了业务订单及相关信息",
|
||||
"create_time": 1790237811,
|
||||
"create_time_beijing": "2026-09-24 16:16:51"
|
||||
},
|
||||
{
|
||||
"id": 57799,
|
||||
"prescription_order_id": 4087,
|
||||
"admin_id": 116,
|
||||
"admin_name": "焦珂",
|
||||
"action": "edit",
|
||||
"summary": "编辑了业务订单及相关信息",
|
||||
"create_time": 1790237815,
|
||||
"create_time_beijing": "2026-09-24 16:16:55"
|
||||
},
|
||||
{
|
||||
"id": 57801,
|
||||
"prescription_order_id": 4087,
|
||||
"admin_id": 116,
|
||||
"admin_name": "药房",
|
||||
"action": "audit_rx_approve",
|
||||
"summary": "处方审核通过",
|
||||
"create_time": 1790237839,
|
||||
"create_time_beijing": "2026-09-24 16:17:19"
|
||||
},
|
||||
{
|
||||
"id": 57802,
|
||||
"prescription_order_id": 4087,
|
||||
"admin_id": 116,
|
||||
"admin_name": "焦珂",
|
||||
"action": "audit_pay_approve",
|
||||
"summary": "支付单审核通过",
|
||||
"create_time": 1790237841,
|
||||
"create_time_beijing": "2026-09-24 16:17:21"
|
||||
},
|
||||
{
|
||||
"id": 57803,
|
||||
"prescription_order_id": 4087,
|
||||
"admin_id": 116,
|
||||
"admin_name": "焦珂",
|
||||
"action": "gancao_submit",
|
||||
"summary": "上传甘草药房成功 G17902378442302734",
|
||||
"create_time": 1790237844,
|
||||
"create_time_beijing": "2026-09-24 16:17:24"
|
||||
},
|
||||
{
|
||||
"id": 57817,
|
||||
"prescription_order_id": 4087,
|
||||
"admin_id": 0,
|
||||
"admin_name": "甘草系统",
|
||||
"action": "gancao_callback",
|
||||
"summary": "甘草回调:系统审核通过",
|
||||
"create_time": 1790238558,
|
||||
"create_time_beijing": "2026-09-24 16:29:18"
|
||||
},
|
||||
{
|
||||
"id": 57818,
|
||||
"prescription_order_id": 4087,
|
||||
"admin_id": 0,
|
||||
"admin_name": "甘草系统",
|
||||
"action": "gancao_callback",
|
||||
"summary": "甘草回调:订单药房流转制作中 | 流程:派单 | 药房:G郑州调配中心",
|
||||
"create_time": 1790238558,
|
||||
"create_time_beijing": "2026-09-24 16:29:18"
|
||||
},
|
||||
{
|
||||
"id": 57829,
|
||||
"prescription_order_id": 4087,
|
||||
"admin_id": 0,
|
||||
"admin_name": "甘草系统",
|
||||
"action": "gancao_callback",
|
||||
"summary": "甘草回调:订单药房流转制作中 | 流程:打印快递 | 药房:G郑州调配中心",
|
||||
"create_time": 1790239757,
|
||||
"create_time_beijing": "2026-09-24 16:49:17"
|
||||
},
|
||||
{
|
||||
"id": 57830,
|
||||
"prescription_order_id": 4087,
|
||||
"admin_id": 0,
|
||||
"admin_name": "甘草系统",
|
||||
"action": "gancao_callback",
|
||||
"summary": "甘草回调:订单药房流转制作中 | 流程:审方 | 药房:G郑州调配中心",
|
||||
"create_time": 1790239757,
|
||||
"create_time_beijing": "2026-09-24 16:49:17"
|
||||
},
|
||||
{
|
||||
"id": 57831,
|
||||
"prescription_order_id": 4087,
|
||||
"admin_id": 0,
|
||||
"admin_name": "甘草系统",
|
||||
"action": "gancao_callback",
|
||||
"summary": "甘草回调:系统审核通过",
|
||||
"create_time": 1790239757,
|
||||
"create_time_beijing": "2026-09-24 16:49:17"
|
||||
},
|
||||
{
|
||||
"id": 57841,
|
||||
"prescription_order_id": 4087,
|
||||
"admin_id": 0,
|
||||
"admin_name": "甘草系统",
|
||||
"action": "gancao_callback",
|
||||
"summary": "甘草回调:订单药房流转制作中 | 流程:煎药调配 | 药房:G郑州调配中心",
|
||||
"create_time": 1790240210,
|
||||
"create_time_beijing": "2026-09-24 16:56:50"
|
||||
},
|
||||
{
|
||||
"id": 57850,
|
||||
"prescription_order_id": 4087,
|
||||
"admin_id": 0,
|
||||
"admin_name": "甘草系统",
|
||||
"action": "gancao_callback",
|
||||
"summary": "甘草回调:订单药房流转制作中 | 流程:打粉调配 | 药房:G郑州调配中心",
|
||||
"create_time": 1790240369,
|
||||
"create_time_beijing": "2026-09-24 16:59:29"
|
||||
},
|
||||
{
|
||||
"id": 57852,
|
||||
"prescription_order_id": 4087,
|
||||
"admin_id": 0,
|
||||
"admin_name": "甘草系统",
|
||||
"action": "gancao_callback",
|
||||
"summary": "甘草回调:订单药房流转制作中 | 流程:煎药复核 | 药房:G郑州调配中心",
|
||||
"create_time": 1790240405,
|
||||
"create_time_beijing": "2026-09-24 17:00:05"
|
||||
},
|
||||
{
|
||||
"id": 57855,
|
||||
"prescription_order_id": 4087,
|
||||
"admin_id": 0,
|
||||
"admin_name": "甘草系统",
|
||||
"action": "gancao_callback",
|
||||
"summary": "甘草回调:订单药房流转制作中 | 流程:打粉复核 | 药房:G郑州调配中心",
|
||||
"create_time": 1790240470,
|
||||
"create_time_beijing": "2026-09-24 17:01:10"
|
||||
},
|
||||
{
|
||||
"id": 57872,
|
||||
"prescription_order_id": 4087,
|
||||
"admin_id": 0,
|
||||
"admin_name": "甘草系统",
|
||||
"action": "gancao_callback",
|
||||
"summary": "甘草回调:订单药房流转制作中 | 流程:粗碎 | 药房:G郑州调配中心",
|
||||
"create_time": 1790240996,
|
||||
"create_time_beijing": "2026-09-24 17:09:56"
|
||||
},
|
||||
{
|
||||
"id": 57956,
|
||||
"prescription_order_id": 4087,
|
||||
"admin_id": 0,
|
||||
"admin_name": "甘草系统",
|
||||
"action": "gancao_callback",
|
||||
"summary": "甘草回调:订单药房流转制作中 | 流程:浸泡 | 药房:G郑州调配中心",
|
||||
"create_time": 1790242854,
|
||||
"create_time_beijing": "2026-09-24 17:40:54"
|
||||
},
|
||||
{
|
||||
"id": 57977,
|
||||
"prescription_order_id": 4087,
|
||||
"admin_id": 0,
|
||||
"admin_name": "甘草系统",
|
||||
"action": "gancao_callback",
|
||||
"summary": "甘草回调:订单药房流转制作中 | 流程:煎药开始 | 药房:G郑州调配中心",
|
||||
"create_time": 1790244547,
|
||||
"create_time_beijing": "2026-09-24 18:09:07"
|
||||
},
|
||||
{
|
||||
"id": 57995,
|
||||
"prescription_order_id": 4087,
|
||||
"admin_id": 0,
|
||||
"admin_name": "甘草系统",
|
||||
"action": "gancao_callback",
|
||||
"summary": "甘草回调:订单药房流转制作中 | 流程:煎药结束 | 药房:G郑州调配中心",
|
||||
"create_time": 1790248163,
|
||||
"create_time_beijing": "2026-09-24 19:09:23"
|
||||
},
|
||||
{
|
||||
"id": 58016,
|
||||
"prescription_order_id": 4087,
|
||||
"admin_id": 0,
|
||||
"admin_name": "甘草系统",
|
||||
"action": "gancao_callback",
|
||||
"summary": "甘草回调:订单药房流转制作中 | 流程:浓缩开始 | 药房:G郑州调配中心",
|
||||
"create_time": 1790296481,
|
||||
"create_time_beijing": "2026-09-25 08:34:41"
|
||||
},
|
||||
{
|
||||
"id": 58017,
|
||||
"prescription_order_id": 4087,
|
||||
"admin_id": 0,
|
||||
"admin_name": "甘草系统",
|
||||
"action": "gancao_callback",
|
||||
"summary": "甘草回调:订单药房流转制作中 | 流程:浓缩结束 | 药房:G郑州调配中心",
|
||||
"create_time": 1790296485,
|
||||
"create_time_beijing": "2026-09-25 08:34:45"
|
||||
},
|
||||
{
|
||||
"id": 58024,
|
||||
"prescription_order_id": 4087,
|
||||
"admin_id": 0,
|
||||
"admin_name": "甘草系统",
|
||||
"action": "gancao_callback",
|
||||
"summary": "甘草回调:订单药房流转制作中 | 流程:打粉 | 药房:G郑州调配中心",
|
||||
"create_time": 1790300804,
|
||||
"create_time_beijing": "2026-09-25 09:46:44"
|
||||
},
|
||||
{
|
||||
"id": 58030,
|
||||
"prescription_order_id": 4087,
|
||||
"admin_id": 0,
|
||||
"admin_name": "甘草系统",
|
||||
"action": "gancao_callback",
|
||||
"summary": "甘草回调:订单药房流转制作中 | 流程:拌粉开始 | 药房:G郑州调配中心",
|
||||
"create_time": 1790303162,
|
||||
"create_time_beijing": "2026-09-25 10:26:02"
|
||||
},
|
||||
{
|
||||
"id": 58034,
|
||||
"prescription_order_id": 4087,
|
||||
"admin_id": 0,
|
||||
"admin_name": "甘草系统",
|
||||
"action": "gancao_callback",
|
||||
"summary": "甘草回调:订单药房流转制作中 | 流程:拌粉 | 药房:G郑州调配中心",
|
||||
"create_time": 1790303789,
|
||||
"create_time_beijing": "2026-09-25 10:36:29"
|
||||
},
|
||||
{
|
||||
"id": 58035,
|
||||
"prescription_order_id": 4087,
|
||||
"admin_id": 0,
|
||||
"admin_name": "甘草系统",
|
||||
"action": "gancao_callback",
|
||||
"summary": "甘草回调:订单药房流转制作中 | 流程:制丸 | 药房:G郑州调配中心",
|
||||
"create_time": 1790303810,
|
||||
"create_time_beijing": "2026-09-25 10:36:50"
|
||||
},
|
||||
{
|
||||
"id": 58037,
|
||||
"prescription_order_id": 4087,
|
||||
"admin_id": 0,
|
||||
"admin_name": "甘草系统",
|
||||
"action": "gancao_callback",
|
||||
"summary": "甘草回调:订单药房流转制作中 | 流程:抛光 | 药房:G郑州调配中心",
|
||||
"create_time": 1790304415,
|
||||
"create_time_beijing": "2026-09-25 10:46:55"
|
||||
},
|
||||
{
|
||||
"id": 58074,
|
||||
"prescription_order_id": 4087,
|
||||
"admin_id": 0,
|
||||
"admin_name": "甘草系统",
|
||||
"action": "gancao_callback",
|
||||
"summary": "甘草回调:订单药房流转制作中 | 流程:烘干完成并过筛 | 药房:G郑州调配中心",
|
||||
"create_time": 1790326640,
|
||||
"create_time_beijing": "2026-09-25 16:57:20"
|
||||
},
|
||||
{
|
||||
"id": 58076,
|
||||
"prescription_order_id": 4087,
|
||||
"admin_id": 0,
|
||||
"admin_name": "甘草系统",
|
||||
"action": "gancao_callback",
|
||||
"summary": "甘草回调:订单药房流转制作中 | 流程:发货 | 药房:G郑州调配中心",
|
||||
"create_time": 1790328640,
|
||||
"create_time_beijing": "2026-09-25 17:30:40"
|
||||
},
|
||||
{
|
||||
"id": 58077,
|
||||
"prescription_order_id": 4087,
|
||||
"admin_id": 0,
|
||||
"admin_name": "甘草系统",
|
||||
"action": "gancao_callback",
|
||||
"summary": "甘草回调:订单药房流转制作中 | 流程:发货 | 药房:G郑州调配中心",
|
||||
"create_time": 1790328640,
|
||||
"create_time_beijing": "2026-09-25 17:30:40"
|
||||
},
|
||||
{
|
||||
"id": 58084,
|
||||
"prescription_order_id": 4087,
|
||||
"admin_id": 0,
|
||||
"admin_name": "甘草系统",
|
||||
"action": "gancao_callback",
|
||||
"summary": "甘草回调:物流中 | 药房:G郑州调配中心 | 物流:shunfeng | 单号:SF5155771371889",
|
||||
"create_time": 1790337614,
|
||||
"create_time_beijing": "2026-09-25 20:00:14"
|
||||
},
|
||||
{
|
||||
"id": 58085,
|
||||
"prescription_order_id": 4087,
|
||||
"admin_id": 0,
|
||||
"admin_name": "甘草系统",
|
||||
"action": "gancao_callback",
|
||||
"summary": "甘草回调:物流中 | 药房:G郑州调配中心 | 物流:shunfeng | 单号:SF5155771371889",
|
||||
"create_time": 1790338204,
|
||||
"create_time_beijing": "2026-09-25 20:10:04"
|
||||
},
|
||||
{
|
||||
"id": 58086,
|
||||
"prescription_order_id": 4087,
|
||||
"admin_id": 0,
|
||||
"admin_name": "甘草系统",
|
||||
"action": "gancao_callback",
|
||||
"summary": "甘草回调:物流中 | 药房:G郑州调配中心 | 物流:shunfeng | 单号:SF5155771371889",
|
||||
"create_time": 1790338204,
|
||||
"create_time_beijing": "2026-09-25 20:10:04"
|
||||
},
|
||||
{
|
||||
"id": 58087,
|
||||
"prescription_order_id": 4087,
|
||||
"admin_id": 0,
|
||||
"admin_name": "甘草系统",
|
||||
"action": "gancao_callback",
|
||||
"summary": "甘草回调:订单药房流转制作中 | 流程:寄出 | 药房:G郑州调配中心",
|
||||
"create_time": 1790338204,
|
||||
"create_time_beijing": "2026-09-25 20:10:04"
|
||||
},
|
||||
{
|
||||
"id": 58182,
|
||||
"prescription_order_id": 4087,
|
||||
"admin_id": 0,
|
||||
"admin_name": "甘草系统",
|
||||
"action": "gancao_callback",
|
||||
"summary": "甘草回调:完成 | 药房:G郑州调配中心 | 物流:shunfeng | 单号:SF5155771371889",
|
||||
"create_time": 1790468903,
|
||||
"create_time_beijing": "2026-09-27 08:28:23"
|
||||
},
|
||||
{
|
||||
"id": 64682,
|
||||
"prescription_order_id": 4583,
|
||||
"admin_id": 284,
|
||||
"admin_name": "晁婷婷",
|
||||
"action": "create",
|
||||
"summary": "创建业务订单",
|
||||
"create_time": 1792804896,
|
||||
"create_time_beijing": "2026-10-24 09:21:36"
|
||||
},
|
||||
{
|
||||
"id": 64957,
|
||||
"prescription_order_id": 4583,
|
||||
"admin_id": 119,
|
||||
"admin_name": "李思佳",
|
||||
"action": "set_ship_mode",
|
||||
"summary": "发货类型:甘草药房 → 洛阳药房",
|
||||
"create_time": 1792978377,
|
||||
"create_time_beijing": "2026-10-26 09:32:57"
|
||||
},
|
||||
{
|
||||
"id": 64975,
|
||||
"prescription_order_id": 4583,
|
||||
"admin_id": 119,
|
||||
"admin_name": "李思佳",
|
||||
"action": "edit",
|
||||
"summary": "编辑了业务订单及相关信息",
|
||||
"create_time": 1792980124,
|
||||
"create_time_beijing": "2026-10-26 10:02:04"
|
||||
},
|
||||
{
|
||||
"id": 64976,
|
||||
"prescription_order_id": 4583,
|
||||
"admin_id": 119,
|
||||
"admin_name": "药房",
|
||||
"action": "audit_rx_approve",
|
||||
"summary": "处方审核通过",
|
||||
"create_time": 1792980254,
|
||||
"create_time_beijing": "2026-10-26 10:04:14"
|
||||
},
|
||||
{
|
||||
"id": 64978,
|
||||
"prescription_order_id": 4583,
|
||||
"admin_id": 119,
|
||||
"admin_name": "李思佳",
|
||||
"action": "audit_pay_approve",
|
||||
"summary": "支付单审核通过",
|
||||
"create_time": 1792980256,
|
||||
"create_time_beijing": "2026-10-26 10:04:16"
|
||||
},
|
||||
{
|
||||
"id": 64979,
|
||||
"prescription_order_id": 4583,
|
||||
"admin_id": 119,
|
||||
"admin_name": "李思佳",
|
||||
"action": "ej_pharmacy_submit",
|
||||
"summary": "上传洛阳药房成功 EJ202610261004182FA855",
|
||||
"create_time": 1792980258,
|
||||
"create_time_beijing": "2026-10-26 10:04:18"
|
||||
},
|
||||
{
|
||||
"id": 64981,
|
||||
"prescription_order_id": 4583,
|
||||
"admin_id": 0,
|
||||
"admin_name": "洛阳药房ERP",
|
||||
"action": "ej_pharmacy_callback",
|
||||
"summary": "洛阳药房回传:订单已创建;远端状态:待审核;履约状态:待发货/发货与履约 → 待发货/发货与履约;(版本已处理,保留回传日志)",
|
||||
"create_time": 1792980361,
|
||||
"create_time_beijing": "2026-10-26 10:06:01"
|
||||
},
|
||||
{
|
||||
"id": 65003,
|
||||
"prescription_order_id": 4583,
|
||||
"admin_id": 203,
|
||||
"admin_name": "张卫霞",
|
||||
"action": "ship",
|
||||
"summary": "确认发货(药房直发),运单:JDVE19405836801(auto)",
|
||||
"create_time": 1792983095,
|
||||
"create_time_beijing": "2026-10-26 10:51:35"
|
||||
},
|
||||
{
|
||||
"id": 65616,
|
||||
"prescription_order_id": 4583,
|
||||
"admin_id": 0,
|
||||
"admin_name": "系统",
|
||||
"action": "auto_sign",
|
||||
"summary": "物流签收(运单:JDVE19405836801),订单状态自动更新为「已签收」",
|
||||
"create_time": 1793161807,
|
||||
"create_time_beijing": "2026-10-28 12:30:07"
|
||||
},
|
||||
{
|
||||
"id": 66872,
|
||||
"prescription_order_id": 4583,
|
||||
"admin_id": 119,
|
||||
"admin_name": "李思佳",
|
||||
"action": "complete",
|
||||
"summary": "订单完成,状态变更为「已完成」,实付金额更新为 ¥1800",
|
||||
"create_time": 1793434806,
|
||||
"create_time_beijing": "2026-10-31 16:20:06"
|
||||
}
|
||||
],
|
||||
"pharmacy_callbacks": [
|
||||
{
|
||||
"id": 913,
|
||||
"event_id": "170ed91e-3c32-4fef-841d-ad85ff39f59f",
|
||||
"pharmacy_order_no": "EJ202610261004182FA855",
|
||||
"source_order_no": "PO20261024092136816172",
|
||||
"event_type": "ORDER_CREATED",
|
||||
"status_version": 1,
|
||||
"process_status": "PROCESSED",
|
||||
"processed_time": 1792980361,
|
||||
"error_message": "",
|
||||
"create_time": 1792980361,
|
||||
"update_time": 1792980361,
|
||||
"processed_time_beijing": "2026-10-26 10:06:01",
|
||||
"create_time_beijing": "2026-10-26 10:06:01",
|
||||
"update_time_beijing": "2026-10-26 10:06:01",
|
||||
"payload_selected_fields": {
|
||||
"status": "PENDING_REVIEW",
|
||||
"event_id": "170ed91e-3c32-4fef-841d-ad85ff39f59f",
|
||||
"event_type": "ORDER_CREATED",
|
||||
"occurred_at": "2026-10-26T10:04:18+08:00",
|
||||
"review_status": "PENDING",
|
||||
"source_system": "zyt",
|
||||
"status_version": 1,
|
||||
"express_company": "",
|
||||
"source_order_no": "PO20261024092136816172",
|
||||
"source_revision": 1,
|
||||
"tracking_number": "",
|
||||
"pharmacy_order_no": "EJ202610261004182FA855"
|
||||
}
|
||||
}
|
||||
],
|
||||
"operation_logs": [],
|
||||
"prescription_ai_events": [
|
||||
{
|
||||
"id": 2952,
|
||||
"prescription_id": 10615,
|
||||
"prescription_revision": 1,
|
||||
"doctor_id": 28,
|
||||
"actor_id": 28,
|
||||
"trigger_type": "source_update",
|
||||
"reason": "患者资料或问诊转写已更新",
|
||||
"status": "partial",
|
||||
"validity": "source_updated",
|
||||
"created_at": 1792028463,
|
||||
"updated_at": 1792115017,
|
||||
"created_at_beijing": "2026-10-15 09:41:03",
|
||||
"updated_at_beijing": "2026-10-16 09:43:37"
|
||||
},
|
||||
{
|
||||
"id": 3265,
|
||||
"prescription_id": 10615,
|
||||
"prescription_revision": 1,
|
||||
"doctor_id": 28,
|
||||
"actor_id": 28,
|
||||
"trigger_type": "source_update",
|
||||
"reason": "患者资料或问诊转写已更新",
|
||||
"status": "partial",
|
||||
"validity": "current",
|
||||
"created_at": 1792204634,
|
||||
"updated_at": 1792206221,
|
||||
"created_at_beijing": "2026-10-17 10:37:14",
|
||||
"updated_at_beijing": "2026-10-17 11:03:41"
|
||||
}
|
||||
],
|
||||
"staff_current": [
|
||||
{
|
||||
"id": 12,
|
||||
"name": "霍桢毅",
|
||||
"roles": "医生"
|
||||
},
|
||||
{
|
||||
"id": 28,
|
||||
"name": "赵俊霞",
|
||||
"roles": "医生"
|
||||
},
|
||||
{
|
||||
"id": 116,
|
||||
"name": "药房1",
|
||||
"roles": "排班、下单"
|
||||
},
|
||||
{
|
||||
"id": 119,
|
||||
"name": "药房",
|
||||
"roles": "下单"
|
||||
},
|
||||
{
|
||||
"id": 203,
|
||||
"name": "张卫霞",
|
||||
"roles": "药房"
|
||||
},
|
||||
{
|
||||
"id": 204,
|
||||
"name": "徐云云",
|
||||
"roles": "药房"
|
||||
},
|
||||
{
|
||||
"id": 279,
|
||||
"name": "董肖妍",
|
||||
"roles": "医助"
|
||||
},
|
||||
{
|
||||
"id": 284,
|
||||
"name": "晁婷婷",
|
||||
"roles": "医助"
|
||||
}
|
||||
],
|
||||
"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"
|
||||
},
|
||||
"source_freshness_indicator": {
|
||||
"latest_order_create_time": 1794884824,
|
||||
"latest_order_create_time_beijing": "2026-11-17 11:07:04"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
三个处方业务订单:开方记录与药房操作日志
|
||||
导出时间:2026-11-18T16:50:09+08:00
|
||||
|
||||
来源:项目 server/.env 指向的本机 MySQL 数据库 zyt(127.0.0.1:3306)。未核实与生产库同步情况;本报告仅证明当前查询库中保存的记录。
|
||||
所有展示时间均为北京时间 UTC+08:00;JSON 同时保留 Unix 原始时间戳。查询使用只读事务,未修改业务数据。
|
||||
开方栏取自处方主记录 doctor_name、creator_id、create_time;它是当前处方记录,并非独立的开方保存、修改操作流水。
|
||||
审方日志原始 admin_name 三笔均为“药房”。本报告另列同一账号 ID 对应的处方 audit_by_name,以及同单相邻操作日志署名,保留来源差异。
|
||||
账号 116 当前名为“药房1”,账号 119 当前名为“药房”;当前角色为下单等。焦珂、李思佳为审核字段/历史日志署名,不据此认定实名登录人或执业资质。
|
||||
当前代码 server/app/adminapi/event.php 的 HttpEnd 监听器为空,关闭了通用后台操作日志写入;这不能证明历史所有时段均关闭。
|
||||
药房回调的日志时间为本系统落库时间;如载荷提供 occurred_at,则在回传明细中另列原值。
|
||||
未检索到关联这三个订单/处方的通用后台请求日志,不能提供完整的逐次开方、修改请求历史。
|
||||
|
||||
当前库订单表最新创建时间:2026-11-17 11:07:04(仅供判断数据范围,不代表同步时间)
|
||||
订单操作日志共 54 条;匹配后台请求日志 0 条;AI 触发记录 2 条;洛阳药房原始回传 1 条。
|
||||
|
||||
========================================================================================
|
||||
PO20261024092136816172
|
||||
患者:雷柏生;诊单 ID:12167;业务订单 ID:4583
|
||||
处方:RX202610233553(ID 11945);类型:浓缩水丸;名称:系统代开
|
||||
处方记录医生:霍桢毅(creator_id=12);创建时间:2026-10-23 17:37:58;处方日期:2026-10-23
|
||||
业务订单创建人:晁婷婷(ID 284);创建时间:2026-10-24 09:21:36
|
||||
金额:1800.00;已付:1800.00;状态:已完成
|
||||
处方审核字段:李思佳(账号 ID 119);2026-10-26 10:04:14;audit_status=1;业务订单处方审核通过
|
||||
发货方式:direct;甘草订单:无;洛阳药房订单:EJ202610261004182FA855
|
||||
|
||||
审方/撤审/人工补记日志(1 条)
|
||||
2026-10-26 10:04:14 | 日志 64976 | 原始署名 药房 / 账号 119 | audit_rx_approve | 处方审核通过
|
||||
|
||||
完整订单操作流水(10 条,按时间、日志 ID 升序)
|
||||
2026-10-24 09:21:36 | 日志 64682 | 晁婷婷 / 账号 284 | create | 创建业务订单
|
||||
2026-10-26 09:32:57 | 日志 64957 | 李思佳 / 账号 119 | set_ship_mode | 发货类型:甘草药房 → 洛阳药房
|
||||
2026-10-26 10:02:04 | 日志 64975 | 李思佳 / 账号 119 | edit | 编辑了业务订单及相关信息
|
||||
2026-10-26 10:04:14 | 日志 64976 | 药房 / 账号 119 | audit_rx_approve | 处方审核通过
|
||||
2026-10-26 10:04:16 | 日志 64978 | 李思佳 / 账号 119 | audit_pay_approve | 支付单审核通过
|
||||
2026-10-26 10:04:18 | 日志 64979 | 李思佳 / 账号 119 | ej_pharmacy_submit | 上传洛阳药房成功 EJ202610261004182FA855
|
||||
2026-10-26 10:06:01 | 日志 64981 | 洛阳药房ERP / 账号 0 | ej_pharmacy_callback | 洛阳药房回传:订单已创建;远端状态:待审核;履约状态:待发货/发货与履约 → 待发货/发货与履约;(版本已处理,保留回传日志)
|
||||
2026-10-26 10:51:35 | 日志 65003 | 张卫霞 / 账号 203 | ship | 确认发货(药房直发),运单:JDVE19405836801(auto)
|
||||
2026-10-28 12:30:07 | 日志 65616 | 系统 / 账号 0 | auto_sign | 物流签收(运单:JDVE19405836801),订单状态自动更新为「已签收」
|
||||
2026-10-31 16:20:06 | 日志 66872 | 李思佳 / 账号 119 | complete | 订单完成,状态变更为「已完成」,实付金额更新为 ¥1800
|
||||
|
||||
========================================================================================
|
||||
PO20260924112640923356
|
||||
患者:雷柏生;诊单 ID:12167;业务订单 ID:4087
|
||||
处方:RX202609238774(ID 10615);类型:浓缩水丸;名称:系统代开
|
||||
处方记录医生:赵俊霞(creator_id=28);创建时间:2026-09-23 17:37:35;处方日期:2026-09-23
|
||||
业务订单创建人:晁婷婷(ID 284);创建时间:2026-09-24 11:26:40
|
||||
金额:1800.00;已付:0.00;状态:已完成
|
||||
处方审核字段:焦珂(账号 ID 116);2026-09-24 16:17:19;audit_status=1;业务订单处方审核通过
|
||||
发货方式:gancao;甘草订单:G17902378442302734;洛阳药房订单:无
|
||||
|
||||
审方/撤审/人工补记日志(1 条)
|
||||
2026-09-24 16:17:19 | 日志 57801 | 原始署名 药房 / 账号 116 | audit_rx_approve | 处方审核通过
|
||||
|
||||
完整订单操作流水(36 条,按时间、日志 ID 升序)
|
||||
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:54 | 日志 57793 | 焦珂 / 账号 116 | set_ship_mode | 发货类型:洛阳药房 → 甘草药房
|
||||
2026-09-24 16:16:51 | 日志 57798 | 焦珂 / 账号 116 | edit | 编辑了业务订单及相关信息
|
||||
2026-09-24 16:16:55 | 日志 57799 | 焦珂 / 账号 116 | edit | 编辑了业务订单及相关信息
|
||||
2026-09-24 16:17:19 | 日志 57801 | 药房 / 账号 116 | audit_rx_approve | 处方审核通过
|
||||
2026-09-24 16:17:21 | 日志 57802 | 焦珂 / 账号 116 | audit_pay_approve | 支付单审核通过
|
||||
2026-09-24 16:17:24 | 日志 57803 | 焦珂 / 账号 116 | gancao_submit | 上传甘草药房成功 G17902378442302734
|
||||
2026-09-24 16:29:18 | 日志 57817 | 甘草系统 / 账号 0 | gancao_callback | 甘草回调:系统审核通过
|
||||
2026-09-24 16:29:18 | 日志 57818 | 甘草系统 / 账号 0 | gancao_callback | 甘草回调:订单药房流转制作中 | 流程:派单 | 药房:G郑州调配中心
|
||||
2026-09-24 16:49:17 | 日志 57829 | 甘草系统 / 账号 0 | gancao_callback | 甘草回调:订单药房流转制作中 | 流程:打印快递 | 药房:G郑州调配中心
|
||||
2026-09-24 16:49:17 | 日志 57830 | 甘草系统 / 账号 0 | gancao_callback | 甘草回调:订单药房流转制作中 | 流程:审方 | 药房:G郑州调配中心
|
||||
2026-09-24 16:49:17 | 日志 57831 | 甘草系统 / 账号 0 | gancao_callback | 甘草回调:系统审核通过
|
||||
2026-09-24 16:56:50 | 日志 57841 | 甘草系统 / 账号 0 | gancao_callback | 甘草回调:订单药房流转制作中 | 流程:煎药调配 | 药房:G郑州调配中心
|
||||
2026-09-24 16:59:29 | 日志 57850 | 甘草系统 / 账号 0 | gancao_callback | 甘草回调:订单药房流转制作中 | 流程:打粉调配 | 药房:G郑州调配中心
|
||||
2026-09-24 17:00:05 | 日志 57852 | 甘草系统 / 账号 0 | gancao_callback | 甘草回调:订单药房流转制作中 | 流程:煎药复核 | 药房:G郑州调配中心
|
||||
2026-09-24 17:01:10 | 日志 57855 | 甘草系统 / 账号 0 | gancao_callback | 甘草回调:订单药房流转制作中 | 流程:打粉复核 | 药房:G郑州调配中心
|
||||
2026-09-24 17:09:56 | 日志 57872 | 甘草系统 / 账号 0 | gancao_callback | 甘草回调:订单药房流转制作中 | 流程:粗碎 | 药房:G郑州调配中心
|
||||
2026-09-24 17:40:54 | 日志 57956 | 甘草系统 / 账号 0 | gancao_callback | 甘草回调:订单药房流转制作中 | 流程:浸泡 | 药房:G郑州调配中心
|
||||
2026-09-24 18:09:07 | 日志 57977 | 甘草系统 / 账号 0 | gancao_callback | 甘草回调:订单药房流转制作中 | 流程:煎药开始 | 药房:G郑州调配中心
|
||||
2026-09-24 19:09:23 | 日志 57995 | 甘草系统 / 账号 0 | gancao_callback | 甘草回调:订单药房流转制作中 | 流程:煎药结束 | 药房:G郑州调配中心
|
||||
2026-09-25 08:34:41 | 日志 58016 | 甘草系统 / 账号 0 | gancao_callback | 甘草回调:订单药房流转制作中 | 流程:浓缩开始 | 药房:G郑州调配中心
|
||||
2026-09-25 08:34:45 | 日志 58017 | 甘草系统 / 账号 0 | gancao_callback | 甘草回调:订单药房流转制作中 | 流程:浓缩结束 | 药房:G郑州调配中心
|
||||
2026-09-25 09:46:44 | 日志 58024 | 甘草系统 / 账号 0 | gancao_callback | 甘草回调:订单药房流转制作中 | 流程:打粉 | 药房:G郑州调配中心
|
||||
2026-09-25 10:26:02 | 日志 58030 | 甘草系统 / 账号 0 | gancao_callback | 甘草回调:订单药房流转制作中 | 流程:拌粉开始 | 药房:G郑州调配中心
|
||||
2026-09-25 10:36:29 | 日志 58034 | 甘草系统 / 账号 0 | gancao_callback | 甘草回调:订单药房流转制作中 | 流程:拌粉 | 药房:G郑州调配中心
|
||||
2026-09-25 10:36:50 | 日志 58035 | 甘草系统 / 账号 0 | gancao_callback | 甘草回调:订单药房流转制作中 | 流程:制丸 | 药房:G郑州调配中心
|
||||
2026-09-25 10:46:55 | 日志 58037 | 甘草系统 / 账号 0 | gancao_callback | 甘草回调:订单药房流转制作中 | 流程:抛光 | 药房:G郑州调配中心
|
||||
2026-09-25 16:57:20 | 日志 58074 | 甘草系统 / 账号 0 | gancao_callback | 甘草回调:订单药房流转制作中 | 流程:烘干完成并过筛 | 药房:G郑州调配中心
|
||||
2026-09-25 17:30:40 | 日志 58076 | 甘草系统 / 账号 0 | gancao_callback | 甘草回调:订单药房流转制作中 | 流程:发货 | 药房:G郑州调配中心
|
||||
2026-09-25 17:30:40 | 日志 58077 | 甘草系统 / 账号 0 | gancao_callback | 甘草回调:订单药房流转制作中 | 流程:发货 | 药房:G郑州调配中心
|
||||
2026-09-25 20:00:14 | 日志 58084 | 甘草系统 / 账号 0 | gancao_callback | 甘草回调:物流中 | 药房:G郑州调配中心 | 物流:shunfeng | 单号:SF5155771371889
|
||||
2026-09-25 20:10:04 | 日志 58085 | 甘草系统 / 账号 0 | gancao_callback | 甘草回调:物流中 | 药房:G郑州调配中心 | 物流:shunfeng | 单号:SF5155771371889
|
||||
2026-09-25 20:10:04 | 日志 58086 | 甘草系统 / 账号 0 | gancao_callback | 甘草回调:物流中 | 药房:G郑州调配中心 | 物流:shunfeng | 单号:SF5155771371889
|
||||
2026-09-25 20:10:04 | 日志 58087 | 甘草系统 / 账号 0 | gancao_callback | 甘草回调:订单药房流转制作中 | 流程:寄出 | 药房:G郑州调配中心
|
||||
2026-09-27 08:28:23 | 日志 58182 | 甘草系统 / 账号 0 | gancao_callback | 甘草回调:完成 | 药房:G郑州调配中心 | 物流:shunfeng | 单号:SF5155771371889
|
||||
|
||||
========================================================================================
|
||||
PO20260908142548426588
|
||||
患者:雷柏生;诊单 ID:12167;业务订单 ID:3751
|
||||
处方:RX202609078921(ID 9787);类型:浓缩水丸;名称:系统代开
|
||||
处方记录医生:赵俊霞(creator_id=28);创建时间:2026-09-07 17:42:46;处方日期:2026-09-07
|
||||
业务订单创建人:董肖妍(ID 279);创建时间:2026-09-08 14:25:48
|
||||
金额:1400.00;已付:1400.00;状态:已完成
|
||||
处方审核字段:焦珂(账号 ID 116);2026-09-09 11:48:48;audit_status=1;业务订单处方审核通过
|
||||
发货方式:direct;甘草订单:无;洛阳药房订单:无
|
||||
|
||||
审方/撤审/人工补记日志(1 条)
|
||||
2026-09-09 11:48:48 | 日志 53014 | 原始署名 药房 / 账号 116 | audit_rx_approve | 处方审核通过
|
||||
|
||||
完整订单操作流水(8 条,按时间、日志 ID 升序)
|
||||
2026-09-08 14:25:48 | 日志 52702 | 董肖妍 / 账号 279 | create | 创建业务订单
|
||||
2026-09-09 10:58:36 | 日志 52953 | 焦珂 / 账号 116 | set_ship_mode | 发货类型:甘草药房 → 洛阳药房
|
||||
2026-09-09 11:46:56 | 日志 53013 | 焦珂 / 账号 116 | edit | 编辑了业务订单及相关信息
|
||||
2026-09-09 11:48:48 | 日志 53014 | 药房 / 账号 116 | audit_rx_approve | 处方审核通过
|
||||
2026-09-09 11:48:51 | 日志 53015 | 焦珂 / 账号 116 | audit_pay_approve | 支付单审核通过
|
||||
2026-09-10 10:02:10 | 日志 53255 | 徐云云 / 账号 204 | ship | 确认发货(药房直发),运单:JDVE18948527288(auto)
|
||||
2026-09-12 11:30:14 | 日志 54095 | 系统 / 账号 0 | auto_sign | 物流签收(运单:JDVE18948527288),订单状态自动更新为「已签收」
|
||||
2026-09-27 15:02:08 | 日志 58339 | 焦珂 / 账号 116 | complete | 订单完成,状态变更为「已完成」,实付金额更新为 ¥1400
|
||||
|
||||
========================================================================================
|
||||
洛阳药房回传明细
|
||||
[
|
||||
{
|
||||
"id": 913,
|
||||
"event_id": "170ed91e-3c32-4fef-841d-ad85ff39f59f",
|
||||
"pharmacy_order_no": "EJ202610261004182FA855",
|
||||
"source_order_no": "PO20261024092136816172",
|
||||
"event_type": "ORDER_CREATED",
|
||||
"status_version": 1,
|
||||
"process_status": "PROCESSED",
|
||||
"processed_time": 1792980361,
|
||||
"error_message": "",
|
||||
"create_time": 1792980361,
|
||||
"update_time": 1792980361,
|
||||
"processed_time_beijing": "2026-10-26 10:06:01",
|
||||
"create_time_beijing": "2026-10-26 10:06:01",
|
||||
"update_time_beijing": "2026-10-26 10:06:01",
|
||||
"payload_selected_fields": {
|
||||
"status": "PENDING_REVIEW",
|
||||
"event_id": "170ed91e-3c32-4fef-841d-ad85ff39f59f",
|
||||
"event_type": "ORDER_CREATED",
|
||||
"occurred_at": "2026-10-26T10:04:18+08:00",
|
||||
"review_status": "PENDING",
|
||||
"source_system": "zyt",
|
||||
"status_version": 1,
|
||||
"express_company": "",
|
||||
"source_order_no": "PO20261024092136816172",
|
||||
"source_revision": 1,
|
||||
"tracking_number": "",
|
||||
"pharmacy_order_no": "EJ202610261004182FA855"
|
||||
}
|
||||
}
|
||||
]
|
||||
关联开方/修改后台请求日志
|
||||
[]
|
||||
关联 AI 分析触发元数据(不等同开方日志)
|
||||
[
|
||||
{
|
||||
"id": 2952,
|
||||
"prescription_id": 10615,
|
||||
"prescription_revision": 1,
|
||||
"doctor_id": 28,
|
||||
"actor_id": 28,
|
||||
"trigger_type": "source_update",
|
||||
"reason": "患者资料或问诊转写已更新",
|
||||
"status": "partial",
|
||||
"validity": "source_updated",
|
||||
"created_at": 1792028463,
|
||||
"updated_at": 1792115017,
|
||||
"created_at_beijing": "2026-10-15 09:41:03",
|
||||
"updated_at_beijing": "2026-10-16 09:43:37"
|
||||
},
|
||||
{
|
||||
"id": 3265,
|
||||
"prescription_id": 10615,
|
||||
"prescription_revision": 1,
|
||||
"doctor_id": 28,
|
||||
"actor_id": 28,
|
||||
"trigger_type": "source_update",
|
||||
"reason": "患者资料或问诊转写已更新",
|
||||
"status": "partial",
|
||||
"validity": "current",
|
||||
"created_at": 1792204634,
|
||||
"updated_at": 1792206221,
|
||||
"created_at_beijing": "2026-10-17 10:37:14",
|
||||
"updated_at_beijing": "2026-10-17 11:03:41"
|
||||
}
|
||||
]
|
||||
File diff suppressed because one or more lines are too long
@@ -1,16 +1,22 @@
|
||||
# 医生开方 e签宝 SDK 3.0 接入
|
||||
|
||||
日期:2026-11-17。用户确认使用沙箱。代码覆盖 PHP 后端、Vue 后台及 Python 医生工作站。真实沙箱核身和签署仍待 SDK 服务部署后联调。
|
||||
日期:2026-11-17;运行状态更新:2026-11-18。用户确认使用沙箱。代码覆盖 PHP 后端、Vue 后台及 Python 医生工作站。本机 SDK 已部署并成功初始化,真实医生已在系统内完成核身,正在联调证书绑定与处方签署。
|
||||
|
||||
当前进展:真实沙箱已完成本人核身和个人签署账号绑定。2026-11-18 15:13:43(北京时间),PDF 签署接口返回 `10002`,没有签署流水或签后原件。e签宝[错误码查询](https://open.esign.cn/tools/error-code)将签署接口的该返回码解释为签署次数不足。请按[SDK 3.0 沙箱说明](https://open.esign.cn/doc/opendoc/paas_sdk_3/pndhqggzc2mar20y)申请电子签名 SDK 3.0 的签署调试套餐,额度生效后继续验证、显式确认签名、验签和下载。此前的账号创建 `403` 排查见 `artifacts/esign-sandbox-support-request.md`。
|
||||
|
||||
## 医生操作
|
||||
|
||||
启用后,保存处方进入待电子签署,手写图片不再必填。医生从保存后的面板或处方详情打开 e签宝核身页面,完成认证后点击“完成核身/继续签署”。服务端主动核实认证结果、绑定医生账号,使用冻结的处方 PDF 签署并验签,成功后允许药师审核。医生与药师均可按原处方查看权限下载已签 PDF 原件。
|
||||
1. **保存处方草稿。** 填完处方后保存,进入同一张处方的签名流程。保存失败时保留表单,可重试。未完成电子签署的草稿不能审核。
|
||||
2. **验证医生身份。** 开方医生在系统内完成核验。系统查询核验结果,核验通过后显示签名步骤。核验失败或授权过期时,可在当前处方上重新验证。
|
||||
3. **确认签名并完成。** 医生核对当前处方后点击“确认签名”。若首次证书绑定所需的个人信息缺失,系统在这一步提示本人补充证件号。服务端再次核对本人授权,对冻结的 PDF 签名并验签。验签通过后,按权限下载已签 PDF 原件,处方可进入审核。
|
||||
|
||||
浏览器打开、返回或点击完成均不表示签署成功。签署主体必须是原开方医生;后台超级管理员也不能替另一名医生签署。初次认证使用账号中医师姓名,支持大陆居民身份证;需事先核实医生账号登记的实名信息。身份证完整号码只在服务端调用中短暂使用,不保存到业务库或返回客户端。
|
||||
系统通过只读接口确认核身状态,每 5 秒最多一个请求,单次窗口最长等待 10 分钟。关闭或隐藏核验窗口会停止等待。签署请求必须由开方医生显式确认;权限检查、文件冻结与原始 PDF 验签由服务端执行。身份证号仅用于本次证书绑定,不写入业务库或响应。
|
||||
|
||||
启动签署后冻结该处方内容,包括药品、诊断、患者信息和用法。修改需作废后新开;原件和签署证据保留。签署期间的迟到结果不能恢复已作废处方。签署开关关闭也不能让已经进入电子签署的处方绕过审核门禁。
|
||||
发起身份核验时冻结该处方内容,包括药品、诊断、患者信息和用法。核验前请先检查草稿内容。已冻结处方需要修改时,先作废再新开。原件和签署证据保留。签署期间的迟到结果不能恢复已作废处方。签署开关关闭也不能让已经进入电子签署的处方绕过审核门禁。
|
||||
|
||||
迁移前历史手写方保留原流程,不批量标记为电子签署。启用后新开或编辑保存的处方才进入新流程。自动生成的空白方必须由医生补全后签署。
|
||||
已审核的历史处方保留原记录。启用后,新开处方和仍待审核的旧处方都需要电子签署。旧处方由开方医生开始核验时进入签署流程,继续使用原处方编号。自动生成的空白方必须先补全。
|
||||
|
||||
从处方审核或关联订单的审核入口选择通过时,系统会检查原处方的签署状态。开方医生可继续签署;其他审核人员会看到需要医生签署的提示。验签通过后,再由有审核权限的人员确认审核。发现内容有误时仍可驳回处理。
|
||||
|
||||
## 部署步骤
|
||||
|
||||
@@ -31,15 +37,18 @@
|
||||
| 接口 | 方法 | 用途 |
|
||||
| --- | --- | --- |
|
||||
| `tcm.prescription/esignConfig` | GET | 返回开关与环境,无密钥 |
|
||||
| `tcm.prescription/esignStatus?id=...` | GET | 返回当前服务端状态、可签/可下载权限 |
|
||||
| `tcm.prescription/esignStart` | POST `{id}` | 冻结处方,返回当前医生的核身链接 |
|
||||
| `tcm.prescription/esignComplete` | POST `{id}` | 查询核身、签署、验签及归档 |
|
||||
| `tcm.prescription/esignStatus?id=...` | GET | 返回当前服务端状态,以及继续核验、重试验签和下载的能力 |
|
||||
| `tcm.prescription/esignIdentityStatus?id=...` | GET | 仅原开方医生可查询,返回核身状态、can_complete 与 identity_details_required,不创建账号或签署 |
|
||||
| `tcm.prescription/esignStart` | POST `{id, restart_identity?}` | 冻结处方并获取核身链接,显式重新核验时新建核身流程 |
|
||||
| `tcm.prescription/esignComplete` | POST `{id, identity_number?}` 或 `{id, verify_only: true}` | 本人点击确认后签署并验签;验签重试入口只读取已归档原件并验签 |
|
||||
| `tcm.prescription/esignDownload?id=...` | GET | 授权下载 PDF 原始字节的 Base64 与 SHA-256 |
|
||||
|
||||
新建/编辑响应以及详情、诊单处方、预约处方、处方列表均含 `esign` 状态对象。客户端不能提交签署状态、供应商 flowId 或 PDF 来替代服务器的原始记录。
|
||||
|
||||
使用独立核身 API `/v2/identity/auth/web/indivAuthUrl` 和 `/v2/identity/auth/api/common/{flowId}/detail`;创建账号、制章、PDF 签署、验签使用本地 SDK `/timevale/...`。签署文件从数据库权威快照生成,签章位于 A4 第 1 页底部预留区域。处方内容 SHA-256、原 PDF SHA-256、签后 PDF SHA-256、应用环境、核身流程 ID、账号 ID 与签署流水共同归档。
|
||||
|
||||
核身请求明确传入 `usageType=CERTAPPLY`,要求数字证书颁发/续期与身份核验,避免依赖应用默认用途配置;`authType` 和 `availableAuthTypes` 均限定 `PSN_TELECOM_AUTHCODE`。需开通应用手机认证能力,不自动降级为需要外跳的人脸方式。参考[SDK 核身集成说明](https://open.esign.cn/doc/opendoc/paas_sdk_3/adq41ivoxu30t0kr)和[核身地址参数](https://open.esign.cn/doc/opendoc/identity_service/sg2nty)。PHP 的 cURL 必须配置可信 CA 证书集。可以用 `[ESIGN] CA_FILE` 为电子签署 HTTPS 请求指定本机 CA 文件。若出现 `TRANSPORT_ERROR`,先排查 TLS 证书链。本机 CSS 站点和隔离联调入口均使用经过官方 SHA-256 核验的 curl CA 证书集。
|
||||
|
||||
临床审核与发药前复查签署状态及内容摘要;发药额外要求 production 环境。已签 PDF 不再通过截图、canvas 或 QPdfWriter 重绘,以免丢失数字签名。旧手写图字段可保存签章展示图,可信证据是已签 PDF 和签署流水。
|
||||
|
||||
审核、手工调整订单审核状态以及药房提交占用记录写入,均在数据库事务中锁定处方并检查签署证据。驳回作废与编辑共用药房占用锁,防止并发改动绕过已冻结的内容。通知在审核事务提交后发送。
|
||||
@@ -48,11 +57,11 @@
|
||||
|
||||
## 异常恢复
|
||||
|
||||
- 核身未完成:回到原核身链接,完成后查询/继续;不要新建重复处方。
|
||||
- 核身失败/超期或供应商明确拒绝:界面保留失败状态,可根据提示重新核身。内容仍冻结;如处方有误,作废后新开。
|
||||
- 签署调用超时、响应损坏或结果不明:置为 `uncertain`,阻止自动重签,避免重复收费或重复消费认证 ID。由管理员依据签署流水与供应商核实。
|
||||
- 已取得并归档签后文件,但验签服务暂不可用:服务恢复后运行 `php think esign:setup --recover=处方ID`。只重新验签已归档的原件,不发送第二次签署请求。没有可恢复原件时命令明确失败,不能把数据库状态手工改成已签。
|
||||
- 文件缺失或 SHA-256 不匹配:阻止审核/下载,恢复备份原件并核对证据。错误接口不返回供应商原始响应、身份证件或应用密钥。
|
||||
- 核验结果暂不可用时,点击查询结果。核验失败或过期时,点击重新验证。
|
||||
- 供应商在签署前明确拒绝时,解决界面提示的原因后,回到同一处方继续。仍有效的本人核验授权可复用。
|
||||
- 签署结果不明确时,先查询结果。无法确认结果且缺少原件时,由管理员按供应商流水核实。
|
||||
- 原件已归档但验签失败时,点击重试验签。服务端只校验原件。管理员仍可使用 `php think esign:setup --recover=处方ID` 处理归档故障。
|
||||
- 下载失败时可在已完成页面重新下载。文件缺失或 SHA-256 不匹配时,先恢复备份原件并核对证据。
|
||||
|
||||
## 验证入口
|
||||
|
||||
@@ -80,4 +89,4 @@ $env:QT_QPA_PLATFORM = 'offscreen'
|
||||
|
||||
现有 `PrescriptionOrderTrackingAuditTest.php` 和 `PrescriptionOrderReleaseAndTimeTest.php` 在 `RevisitDueHook` 的日志调用遇到 `Unable to resolve NULL driver`;将 `PrescriptionOrderLogic.php` 换为 Git HEAD 原版后,同一隔离环境也复现该错误。该两项不能报告为通过。处方 AI 写入、预约范围和桌面认证三项既有契约测试通过。
|
||||
|
||||
2026-11-17 后续安装:已取得官方 3.1.26 包并在本机部署,`http://127.0.0.1:8091/paas-sdk-service/` 返回 HTTP 200。真实沙箱初始化返回 `338005`(应用 IP 白名单未配置),需先在 e签宝后台配置当前国内出口 IP,再重试初始化。功能仍保持关闭;未执行真实医生核身、实际签署、生产库迁移或线上发布。安装与启停方法见 `artifacts/esign-runtime-install.md`。该地址仅对这台 Windows 机器有效,线上 PHP 服务器不能通过它访问本机 SDK。
|
||||
2026-11-18 运行验证:官方 3.1.26 已在本机部署,`http://127.0.0.1:8091/paas-sdk-service/` 返回 HTTP 200。用户配置白名单后,真实沙箱初始化成功;原 `338005` 阻塞已解除。真实验签接口成功解析合成未签 PDF,返回预期的 `70003`(文件没有盖章)。已在隔离 SQLite 中用虚构患者处方发起真实医生核身,实际桌面签署组件已经内嵌显示供应商身份信息表单、手机认证选项和证书协议,等待本人完成。业务配置仍保持关闭;尚未实际签署、执行生产库迁移或线上发布。隔离联调步骤见 `artifacts/esign-live-harness.md`;安装与启停方法见 `artifacts/esign-runtime-install.md`。该地址仅对这台 Windows 机器有效,线上 PHP 服务器不能通过它访问本机 SDK。
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
-- MySQL 5.7+ / Navicat。仅用于 PO20261119135253241085,处方 13377。
|
||||
-- 在新连接中运行完整文件。使用 InnoDB,并需要 CREATE ROUTINE、EXECUTE、ALTER ROUTINE 权限。
|
||||
-- 默认仅展示资料。确认以下三项后,在本文件顶部填写凭证、操作人并开启执行。
|
||||
-- 1. 甘草 G17950757789119194 已实际撤单且不会发货;患者侧收款、退款及代收金额已核对。
|
||||
-- 2. 该甘草单以后和在途的回调都已隔离(包括按原 PO 匹配和重放),或甘草已保证不再投递且在途已处理完。
|
||||
-- 3. 洛阳未接过此单,并支持此来源单首次发给洛阳时使用 source_revision=2。
|
||||
-- 截图中的甘草状态 0 本身不能证明撤单。仅在上述情况得到独立核实后才可处理该状态。
|
||||
USE zyt;
|
||||
SET NAMES utf8mb4;
|
||||
SET @apply_transfer = 0;
|
||||
SET @operator_name = '';
|
||||
SET @cancel_reference = '';
|
||||
SET @callback_and_ej_verified = 0;
|
||||
|
||||
SELECT o.order_no, o.prescription_id, o.diagnosis_id, o.ship_mode,
|
||||
o.gancao_order_state, o.fulfillment_status, o.prescription_audit_status,
|
||||
o.payment_slip_audit_status, o.amount, o.paid, o.refund_amount, o.agency_collect_amount,
|
||||
c.source_revision, c.target, c.status, c.remote_order_no
|
||||
FROM zyt_tcm_prescription_order o
|
||||
LEFT JOIN zyt_pharmacy_submission_claim c ON c.prescription_order_id = o.id
|
||||
WHERE o.order_no = 'PO20261119135253241085' AND o.delete_time IS NULL
|
||||
ORDER BY c.source_revision;
|
||||
|
||||
DELIMITER $$
|
||||
CREATE PROCEDURE ops_transfer_po_20261119135253241085()
|
||||
SQL SECURITY INVOKER
|
||||
transfer: BEGIN
|
||||
DECLARE v_rx INT UNSIGNED DEFAULT NULL;
|
||||
DECLARE v_order INT UNSIGNED DEFAULT NULL;
|
||||
DECLARE v_old_claim BIGINT UNSIGNED DEFAULT NULL;
|
||||
DECLARE v_linked_pay INT UNSIGNED DEFAULT NULL;
|
||||
DECLARE v_now INT UNSIGNED;
|
||||
DECLARE v_gc_time INT UNSIGNED;
|
||||
DECLARE v_gc_state INT;
|
||||
DECLARE v_fs INT;
|
||||
DECLARE v_note VARCHAR(500);
|
||||
DECLARE v_errno INT;
|
||||
DECLARE v_error TEXT;
|
||||
DECLARE EXIT HANDLER FOR SQLEXCEPTION
|
||||
BEGIN
|
||||
GET DIAGNOSTICS CONDITION 1 v_errno = MYSQL_ERRNO, v_error = MESSAGE_TEXT;
|
||||
ROLLBACK;
|
||||
SELECT 'ROLLED_BACK' AS result, v_errno AS mysql_errno, v_error AS reason;
|
||||
END;
|
||||
|
||||
IF COALESCE(@apply_transfer, 0) <> 1 THEN
|
||||
SELECT 'PREVIEW_ONLY' AS result;
|
||||
LEAVE transfer;
|
||||
END IF;
|
||||
IF COALESCE(@callback_and_ej_verified, 0) <> 1
|
||||
OR COALESCE(TRIM(@cancel_reference), '') = ''
|
||||
OR COALESCE(TRIM(@operator_name), '') = ''
|
||||
OR CHAR_LENGTH(TRIM(@cancel_reference)) > 200
|
||||
OR CHAR_LENGTH(TRIM(@operator_name)) > 64 THEN
|
||||
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = '请先核实撤单、旧回调隔离及洛阳 v2,填写操作人和撤单凭证';
|
||||
END IF;
|
||||
|
||||
START TRANSACTION;
|
||||
-- 与正常建单入口共用处方锁,防止撤单后同一处方已创建另一张有效单。
|
||||
SELECT id INTO v_rx FROM zyt_tcm_prescription
|
||||
WHERE id = 13377 AND delete_time IS NULL AND COALESCE(void_status, 0) = 0 FOR UPDATE;
|
||||
SELECT id, linked_pay_order_id, gancao_submit_time, gancao_order_state, fulfillment_status
|
||||
INTO v_order, v_linked_pay, v_gc_time, v_gc_state, v_fs
|
||||
FROM zyt_tcm_prescription_order
|
||||
WHERE order_no = 'PO20261119135253241085' AND prescription_id = v_rx AND delete_time IS NULL
|
||||
AND COALESCE(ship_mode, '') IN ('', 'gancao')
|
||||
AND COALESCE(TRIM(gancao_reciperl_order_no), '') IN ('', 'G17950757789119194')
|
||||
AND ((gancao_order_state IN (91, 92) AND fulfillment_status = 4)
|
||||
OR (COALESCE(gancao_order_state, 0) = 0 AND fulfillment_status = 2))
|
||||
AND COALESCE(TRIM(ej_pharmacy_order_no), '') = '' AND COALESCE(ej_pharmacy_submit_time, 0) = 0
|
||||
AND COALESCE(ej_pharmacy_status, '') = '' AND COALESCE(ej_pharmacy_review_status, '') = ''
|
||||
AND COALESCE(ej_pharmacy_status_version, 0) = 0 AND COALESCE(TRIM(tracking_number), '') = ''
|
||||
AND COALESCE(refund_amount, 0) = 0 AND prescription_audit_status = 1 AND payment_slip_audit_status = 1
|
||||
FOR UPDATE;
|
||||
IF v_order IS NULL THEN
|
||||
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = '订单、审核、退款、物流或药房状态与预期不符,或已执行过改派';
|
||||
END IF;
|
||||
SELECT id INTO v_old_claim FROM zyt_pharmacy_submission_claim
|
||||
WHERE prescription_order_id = v_order AND source_revision = 1 AND id = 1492
|
||||
AND target = 'gancao' AND status = 'SUCCESS' AND remote_order_no = 'G17950757789119194' FOR UPDATE;
|
||||
IF v_old_claim IS NULL OR EXISTS (
|
||||
SELECT 1 FROM zyt_pharmacy_submission_claim
|
||||
WHERE prescription_order_id = v_order AND source_revision <> 1
|
||||
) THEN
|
||||
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = '甘草成功记录与预期不符,或已有其他提交版本';
|
||||
END IF;
|
||||
IF EXISTS (SELECT 1 FROM zyt_tcm_prescription_order WHERE prescription_id = v_rx
|
||||
AND id <> v_order AND delete_time IS NULL AND fulfillment_status NOT IN (4, 10))
|
||||
OR EXISTS (SELECT 1 FROM zyt_ej_pharmacy_callback_inbox WHERE source_order_no = 'PO20261119135253241085')
|
||||
OR EXISTS (SELECT 1 FROM zyt_express_tracking WHERE order_type = 'prescription' AND order_id = v_order
|
||||
AND COALESCE(TRIM(tracking_number), '') <> '') THEN
|
||||
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = '另有有效业务单、洛阳回调或物流记录,请核对';
|
||||
END IF;
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM (
|
||||
SELECT v_linked_pay AS pay_id WHERE v_linked_pay > 0
|
||||
UNION SELECT pay_order_id FROM zyt_tcm_prescription_order_pay_order
|
||||
WHERE prescription_order_id = v_order
|
||||
) old_link
|
||||
LEFT JOIN zyt_order p ON p.id = old_link.pay_id
|
||||
WHERE p.id IS NULL OR p.delete_time IS NOT NULL OR p.status = 4
|
||||
OR EXISTS (SELECT 1 FROM zyt_tcm_prescription_order_pay_order l
|
||||
JOIN zyt_tcm_prescription_order a ON a.id = l.prescription_order_id
|
||||
WHERE l.pay_order_id = old_link.pay_id AND a.id <> v_order
|
||||
AND a.delete_time IS NULL AND a.fulfillment_status <> 4)
|
||||
OR EXISTS (SELECT 1 FROM zyt_tcm_prescription_order a
|
||||
WHERE a.linked_pay_order_id = old_link.pay_id AND a.id <> v_order
|
||||
AND a.delete_time IS NULL AND a.fulfillment_status <> 4)
|
||||
) THEN
|
||||
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = '关联收款已退款或已被其他业务单使用';
|
||||
END IF;
|
||||
|
||||
SET v_now = UNIX_TIMESTAMP();
|
||||
SET v_note = CONCAT('原单改派洛阳。甘草 v1 G17950757789119194 已确认撤单,凭证 ', TRIM(@cancel_reference),
|
||||
'。原履约=', v_fs, ',甘草回调=', COALESCE(v_gc_state, 0),
|
||||
',甘草提交时间=', COALESCE(v_gc_time, 0), '。已预留洛阳 v2,尚未发送。DB账号 ', USER());
|
||||
-- v1 完整保留。v2 是本地待提交记录,交回租约,允许下一次人工点击时领取并首次发送。
|
||||
INSERT INTO zyt_pharmacy_submission_claim
|
||||
(prescription_order_id, source_revision, target, status, claim_token, idempotency_key,
|
||||
operator_name, claimed_at, lease_expires_at, create_time, update_time)
|
||||
VALUES (v_order, 2, 'direct', 'PENDING', REPLACE(UUID(), '-', ''), SHA2(CONCAT(v_order, ':2:direct'), 256),
|
||||
TRIM(@operator_name), v_now, v_now, v_now, v_now);
|
||||
UPDATE zyt_tcm_prescription_order
|
||||
SET ship_mode = 'direct', fulfillment_status = 2, gancao_reciperl_order_no = '',
|
||||
gancao_submit_time = 0, update_time = v_now
|
||||
WHERE id = v_order;
|
||||
INSERT INTO zyt_tcm_prescription_order_log
|
||||
(prescription_order_id, admin_id, admin_name, action, summary, create_time)
|
||||
VALUES (v_order, 0, TRIM(@operator_name), 'pharmacy_reroute', v_note, v_now);
|
||||
COMMIT;
|
||||
SELECT 'READY_FOR_LUOYANG_UPLOAD' AS result, v_order AS business_order_id, 2 AS source_revision;
|
||||
END$$
|
||||
DELIMITER ;
|
||||
|
||||
CALL ops_transfer_po_20261119135253241085();
|
||||
DROP PROCEDURE ops_transfer_po_20261119135253241085;
|
||||
Binary file not shown.
Binary file not shown.
@@ -2,11 +2,23 @@
|
||||
# SDK 3.1.13+ is required for queryWillingnessValidity. Keep this service private.
|
||||
# Initialize the SDK once per JVM startup. Restart it before changing app or environment.
|
||||
[ESIGN]
|
||||
# Enable after deploying the SMS and doctor identity enrollment migrations.
|
||||
DOCTOR_SMS_ENABLED = false
|
||||
# Apply the doctor identity and quick-sign migrations. The eSign application must allow reusable authorization.
|
||||
DOCTOR_QUICKSIGN_ENABLED = false
|
||||
# Apply the prescription review signing migration before enabling.
|
||||
REVIEW_ENABLED = false
|
||||
ENABLED = false
|
||||
ENVIRONMENT = sandbox
|
||||
APP_ID =
|
||||
APP_SECRET =
|
||||
SDK_URL = http://127.0.0.1:8091/paas-sdk-service
|
||||
TIMEOUT = 60
|
||||
# Optional trusted CA bundle for eSign HTTPS calls when PHP has no CA bundle configured.
|
||||
# CA_FILE = /etc/ssl/certs/ca-certificates.crt
|
||||
# Sandbox only. A JSON object mapping an authorized doctor account ID to their verified legal name.
|
||||
# SANDBOX_SIGNER_NAMES = {"123":"测试实名"}
|
||||
# Match the SDK JVM timezone used for the unzoned signDate field.
|
||||
# SDK_TIMEZONE = Asia/Shanghai
|
||||
# Optional private persistent directory; default is server/storage/esign.
|
||||
# STORAGE_PATH = /srv/zyt-private/esign
|
||||
|
||||
@@ -7,7 +7,9 @@ namespace app\adminapi\controller\tcm;
|
||||
use app\adminapi\controller\BaseAdminController;
|
||||
use app\adminapi\logic\tcm\PrescriptionLogic;
|
||||
use app\adminapi\validate\tcm\PrescriptionValidate;
|
||||
use app\common\service\esign\DoctorEsignIdentityService;
|
||||
use app\common\service\esign\PrescriptionEsignService;
|
||||
use app\common\service\esign\PrescriptionReviewEsignService;
|
||||
|
||||
/**
|
||||
* 中医处方单控制器
|
||||
@@ -171,12 +173,14 @@ class PrescriptionController extends BaseAdminController
|
||||
*/
|
||||
public function void()
|
||||
{
|
||||
if (!$this->request->isPost()) {
|
||||
return $this->fail('请使用 POST 作废处方');
|
||||
}
|
||||
$id = (int)($this->request->post('id') ?? 0);
|
||||
if (!$id) {
|
||||
if ($id <= 0) {
|
||||
return $this->fail('处方ID不能为空');
|
||||
}
|
||||
$admin = $this->adminInfo;
|
||||
$ok = PrescriptionLogic::void($id, (int)$this->adminId, $admin['name'] ?? '');
|
||||
$ok = PrescriptionLogic::void($id, $this->adminId, $this->adminInfo);
|
||||
if (!$ok) {
|
||||
return $this->fail(PrescriptionLogic::getError());
|
||||
}
|
||||
@@ -193,6 +197,11 @@ class PrescriptionController extends BaseAdminController
|
||||
return $this->esignOperation('status', false);
|
||||
}
|
||||
|
||||
public function esignIdentityStatus()
|
||||
{
|
||||
return $this->esignOperation('identityStatus', false);
|
||||
}
|
||||
|
||||
public function esignStart()
|
||||
{
|
||||
return $this->esignOperation('start', true);
|
||||
@@ -203,11 +212,102 @@ class PrescriptionController extends BaseAdminController
|
||||
return $this->esignOperation('complete', true);
|
||||
}
|
||||
|
||||
/** @notes 验证处方签署短信 */
|
||||
public function esignVerifyWillingness()
|
||||
{
|
||||
return $this->esignOperation('verifyWillingness', true);
|
||||
}
|
||||
|
||||
public function esignDownload()
|
||||
{
|
||||
return $this->esignOperation('download', false);
|
||||
}
|
||||
|
||||
public function esignReviewStatus()
|
||||
{
|
||||
return $this->esignReviewOperation(false);
|
||||
}
|
||||
|
||||
public function esignReviewConfirm()
|
||||
{
|
||||
return $this->esignReviewOperation(true);
|
||||
}
|
||||
|
||||
private function esignReviewOperation(bool $confirm)
|
||||
{
|
||||
if ($confirm ? !$this->request->isPost() : !$this->request->isGet()) {
|
||||
return $this->fail($confirm ? '请使用 POST 请求' : '请使用 GET 请求');
|
||||
}
|
||||
$params = $confirm ? $this->request->post() : $this->request->get();
|
||||
$id = (int) ($params['id'] ?? 0);
|
||||
$orderId = (int) ($params['order_id'] ?? 0);
|
||||
$actor = (int) $this->adminId;
|
||||
$verifyOnly = $params['verify_only'] ?? false;
|
||||
if ($id <= 0 || $orderId < 0 || !is_bool($verifyOnly)) {
|
||||
return $this->fail('审核签署参数无效');
|
||||
}
|
||||
if ($confirm && (int) ($params['actor_id'] ?? 0) !== $actor) {
|
||||
return $this->fail('登录账号已切换,请刷新并由当前审核人确认');
|
||||
}
|
||||
try {
|
||||
if ($confirm) {
|
||||
ignore_user_abort(true);
|
||||
set_time_limit(360);
|
||||
}
|
||||
$data = $confirm
|
||||
? PrescriptionReviewEsignService::confirm($id, $orderId, $actor, $this->adminInfo, $verifyOnly)
|
||||
: PrescriptionReviewEsignService::status($id, $orderId, $actor, $this->adminInfo);
|
||||
return $this->data($data)->header(['Cache-Control' => 'private, no-store']);
|
||||
} catch (\app\common\service\esign\DoctorEsignAuthorizationRequired) {
|
||||
return $this->fail('审核人快捷签授权需要开通或续期,请在「审核签署身份」中处理');
|
||||
} catch (\Throwable $error) {
|
||||
return $this->fail($error instanceof \DomainException || $error instanceof \app\common\service\esign\EsignProviderException
|
||||
? $error->getMessage() : '审核签署暂不可用,请刷新状态后重试');
|
||||
}
|
||||
}
|
||||
|
||||
/** @notes 查询医师电子签署认证 */
|
||||
public function esignDoctorStatus()
|
||||
{
|
||||
return $this->esignDoctorOperation('status', false);
|
||||
}
|
||||
|
||||
/** @notes 发起医师电子签署认证 */
|
||||
public function esignDoctorStart()
|
||||
{
|
||||
return $this->esignDoctorOperation('start', true, 'mobile');
|
||||
}
|
||||
|
||||
/** @notes 完成医师电子签署认证 */
|
||||
public function esignDoctorComplete()
|
||||
{
|
||||
return $this->esignDoctorOperation('complete', true, 'identity_number');
|
||||
}
|
||||
|
||||
private function esignDoctorOperation(string $operation, bool $post, string $field = '')
|
||||
{
|
||||
if ($post ? !$this->request->isPost() : !$this->request->isGet()) {
|
||||
return $this->fail($post ? '请使用 POST 请求' : '请使用 GET 请求');
|
||||
}
|
||||
try {
|
||||
if (!$post) {
|
||||
return $this->data(DoctorEsignIdentityService::status((int) $this->adminId))
|
||||
->header(['Cache-Control' => 'private, no-store']);
|
||||
}
|
||||
$input = $this->request->post($field, '');
|
||||
if (!is_string($input)) {
|
||||
return $this->fail($field === 'mobile' ? '手机号格式无效' : '身份证号码格式无效');
|
||||
}
|
||||
if ($operation === 'complete') {
|
||||
ignore_user_abort(true);
|
||||
}
|
||||
return $this->data(DoctorEsignIdentityService::{$operation}((int) $this->adminId, $input))
|
||||
->header(['Cache-Control' => 'private, no-store']);
|
||||
} catch (\Throwable $error) {
|
||||
return $this->fail($error instanceof \DomainException ? $error->getMessage() : '医师认证暂不可用,请稍后重试');
|
||||
}
|
||||
}
|
||||
|
||||
private function esignOperation(string $operation, bool $post)
|
||||
{
|
||||
if ($post && !$this->request->isPost()) {
|
||||
@@ -223,6 +323,35 @@ class PrescriptionController extends BaseAdminController
|
||||
set_time_limit(300);
|
||||
}
|
||||
try {
|
||||
$body = $post ? $this->request->post(false) : [];
|
||||
if ($operation === 'verifyWillingness') {
|
||||
$code = $this->request->post('auth_code', '');
|
||||
if (!is_string($code)) {
|
||||
return $this->fail('短信验证码格式无效');
|
||||
}
|
||||
return $this->data(PrescriptionEsignService::verifyWillingness($id, (int) $this->adminId,
|
||||
$this->adminInfo, $code));
|
||||
}
|
||||
if ($operation === 'start') {
|
||||
$restartIdentity = array_key_exists('restart_identity', $body) ? $body['restart_identity'] : false;
|
||||
if (!is_bool($restartIdentity)) {
|
||||
return $this->fail('重新核身标记格式无效');
|
||||
}
|
||||
return $this->data(PrescriptionEsignService::start($id, (int) $this->adminId,
|
||||
$this->adminInfo, $restartIdentity));
|
||||
}
|
||||
if ($operation === 'complete') {
|
||||
$verifyOnly = array_key_exists('verify_only', $body) ? $body['verify_only'] : false;
|
||||
if (!is_bool($verifyOnly)) {
|
||||
return $this->fail('验签标记格式无效');
|
||||
}
|
||||
$identityNumber = $this->request->post('identity_number', '');
|
||||
if (!is_string($identityNumber)) {
|
||||
return $this->fail('身份证号码格式无效');
|
||||
}
|
||||
return $this->data(PrescriptionEsignService::complete($id, (int) $this->adminId,
|
||||
$this->adminInfo, $identityNumber, $verifyOnly));
|
||||
}
|
||||
return $this->data(PrescriptionEsignService::{$operation}($id, (int) $this->adminId, $this->adminInfo));
|
||||
} catch (\Throwable $e) {
|
||||
return $this->fail($e instanceof \DomainException ? $e->getMessage() : '电子签署暂不可用,请联系管理员');
|
||||
|
||||
@@ -17,6 +17,7 @@ declare (strict_types=1);
|
||||
namespace app\adminapi\http\middleware;
|
||||
|
||||
use app\adminapi\logic\LoginLogic;
|
||||
use app\adminapi\logic\tcm\PrescriptionLogic;
|
||||
use app\common\service\pharmacy\PharmacyUploadPermissionAlias;
|
||||
use app\common\service\qywx\QywxPromotionOperatorAccess;
|
||||
use app\common\{
|
||||
@@ -94,9 +95,18 @@ class AuthMiddleware
|
||||
$reads = array_merge($writes, ['tcm.prescription/detail', 'tcm.prescription/lists', 'cf.prescription/lists',
|
||||
'cf.prescription/detail', 'cf.prescription/audit', 'tcm.prescription/audit',
|
||||
'tcm.prescriptionorder/lists', 'tcm.prescriptionorder/detail', 'tcm.prescriptionorder/auditprescription']);
|
||||
$grants = in_array($action, ['esignstart', 'esigncomplete'], true) ? $writes : $reads;
|
||||
return in_array($action, ['esignstart', 'esigncomplete', 'esignstatus', 'esigndownload'], true)
|
||||
&& array_intersect($grants, $uris) !== []
|
||||
$audit = ['tcm.prescription/audit', 'cf.prescription/audit', 'tcm.prescriptionorder/auditprescription'];
|
||||
$writeActions = ['esignstart', 'esigncomplete', 'esignidentitystatus', 'esignverifywillingness'];
|
||||
$identityActions = ['esigndoctorstatus', 'esigndoctorstart', 'esigndoctorcomplete'];
|
||||
$grants = match (true) {
|
||||
in_array($action, $writeActions, true) => $writes,
|
||||
in_array($action, $identityActions, true) => array_merge($writes, $audit),
|
||||
$action === 'esignreviewconfirm' => $audit,
|
||||
default => $reads,
|
||||
};
|
||||
return in_array($action, array_merge($writeActions, $identityActions,
|
||||
['esignstatus', 'esigndownload', 'esignreviewstatus', 'esignreviewconfirm']), true)
|
||||
&& array_intersect($grants, $uris) !== []
|
||||
? $next($request) : JsonService::fail('权限不足,无法访问电子签署');
|
||||
}
|
||||
|
||||
@@ -264,17 +274,18 @@ class AuthMiddleware
|
||||
}
|
||||
|
||||
$prescriptionWriteAliases = [
|
||||
'tcm.prescription/add' => [
|
||||
'tcm.prescription/add', 'cf.prescription/add',
|
||||
'tcm.diagnosis/chufang', 'tcm.diagnosis/kaifang',
|
||||
],
|
||||
'tcm.prescription/add' => PrescriptionLogic::PRESCRIBE_PERMISSIONS,
|
||||
'tcm.prescription/edit' => [
|
||||
'tcm.prescription/edit', 'cf.prescription/edit',
|
||||
'tcm.diagnosis/chufang', 'tcm.diagnosis/kaifang',
|
||||
],
|
||||
'tcm.prescription/delete' => ['tcm.prescription/delete', 'cf.prescription/del'],
|
||||
'tcm.prescription/void' => ['tcm.prescription/void', 'cf.prescription/del', 'cf.prescription/audit'],
|
||||
'tcm.prescription/audit' => ['tcm.prescription/audit', 'cf.prescription/audit'],
|
||||
'tcm.prescription/void' => array_merge(
|
||||
PrescriptionLogic::PRESCRIBE_PERMISSIONS,
|
||||
PrescriptionLogic::VOID_MANAGE_PERMISSIONS,
|
||||
PrescriptionLogic::AUDIT_PERMISSIONS
|
||||
),
|
||||
'tcm.prescription/audit' => PrescriptionLogic::AUDIT_PERMISSIONS,
|
||||
];
|
||||
if (isset($prescriptionWriteAliases[$accessUri])
|
||||
&& count(array_intersect($prescriptionWriteAliases[$accessUri], $adminUris)) > 0) {
|
||||
|
||||
@@ -20,10 +20,11 @@ class OperationLog
|
||||
public function handle($response)
|
||||
{
|
||||
$request = request();
|
||||
$accessUri = strtolower($request->controller() . '/' . $request->action());
|
||||
|
||||
// Temporary visual observations and rejected upload parameters must never
|
||||
// enter the generic request/response audit log if this listener is enabled.
|
||||
if (strtolower($request->controller() . '/' . $request->action()) === 'tcm.diagnosis/aitonguescreenshot') {
|
||||
if ($accessUri === 'tcm.diagnosis/aitonguescreenshot') {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -53,6 +54,16 @@ class OperationLog
|
||||
|
||||
$params = $request->param();
|
||||
|
||||
// Signing requests can carry identity inputs, OTPs and private provider URLs.
|
||||
$esign = str_starts_with($accessUri, 'tcm.prescription/esign');
|
||||
if ($esign) {
|
||||
$recordId = in_array($accessUri, ['tcm.prescription/esignstart', 'tcm.prescription/esigncomplete',
|
||||
'tcm.prescription/esignverifywillingness', 'tcm.prescription/esignstatus',
|
||||
'tcm.prescription/esignidentitystatus', 'tcm.prescription/esigndownload'], true);
|
||||
$id = $request->isGet() ? $request->get('id', 0) : $request->post('id', 0);
|
||||
$params = $recordId ? ['id' => is_scalar($id) ? (int) $id : 0] : [];
|
||||
}
|
||||
|
||||
//过滤密码参数
|
||||
if (isset($params['password'])) {
|
||||
$params['password'] = "******";
|
||||
@@ -73,14 +84,29 @@ class OperationLog
|
||||
$systemLog->admin_name = $request->adminInfo['name'] ?? '';
|
||||
$systemLog->action = $notes;
|
||||
$systemLog->account = $request->adminInfo['account'] ?? '';
|
||||
$systemLog->url = $request->url(true);
|
||||
$systemLog->url = $esign ? strtok($request->url(true), '?') : $request->url(true);
|
||||
$systemLog->type = $request->isGet() ? 'GET' : 'POST';
|
||||
$systemLog->params = json_encode($params, true);
|
||||
$systemLog->ip = $request->ip();
|
||||
$systemLog->result = $this->shortenOperationLogResult((string) $response->getContent());
|
||||
$content = (string) $response->getContent();
|
||||
$systemLog->result = $esign ? $this->esignOperationLogResult($content) : $this->shortenOperationLogResult($content);
|
||||
return $systemLog->save();
|
||||
}
|
||||
|
||||
private function esignOperationLogResult(string $content): string
|
||||
{
|
||||
$decoded = json_decode($content, true);
|
||||
$result = [];
|
||||
if (is_int($decoded['code'] ?? null)) {
|
||||
$result['code'] = $decoded['code'];
|
||||
}
|
||||
$status = $decoded['data']['status'] ?? null;
|
||||
if (is_string($status) && preg_match('/^[a-z_]{1,32}$/D', $status)) {
|
||||
$result['status'] = $status;
|
||||
}
|
||||
return json_encode($result);
|
||||
}
|
||||
|
||||
/** MySQL TEXT 上限约 64KB,列表接口常含 base64 签名导致超长 */
|
||||
private function shortenOperationLogResult(string $content): string
|
||||
{
|
||||
@@ -100,6 +126,10 @@ class OperationLog
|
||||
private function stripLargeLogFields(array &$data): void
|
||||
{
|
||||
foreach ($data as $key => &$value) {
|
||||
if ($key === 'auth_url') {
|
||||
unset($data[$key]);
|
||||
continue;
|
||||
}
|
||||
if (is_array($value)) {
|
||||
$this->stripLargeLogFields($value);
|
||||
continue;
|
||||
@@ -112,4 +142,4 @@ class OperationLog
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ use app\adminapi\lists\BaseAdminDataLists;
|
||||
use app\common\lists\ListsSearchInterface;
|
||||
use app\common\lists\Traits\HasDataScopeFilter;
|
||||
use app\adminapi\logic\tcm\PrescriptionLogic;
|
||||
use app\adminapi\logic\tcm\PrescriptionOrderLogic;
|
||||
use app\common\model\tcm\Prescription;
|
||||
use app\common\model\tcm\PrescriptionOrder;
|
||||
|
||||
@@ -256,6 +257,7 @@ class PrescriptionLists extends BaseAdminDataLists implements ListsSearchInterfa
|
||||
$rejectedRx = [];
|
||||
$bizRejectRemark = [];
|
||||
$hasBizOrderRx = [];
|
||||
$hasReleasedOrderRx = [];
|
||||
if ($rxIds !== []) {
|
||||
$bizRejectRows = PrescriptionOrder::whereIn('prescription_id', $rxIds)
|
||||
->where('prescription_audit_status', 2)
|
||||
@@ -276,14 +278,18 @@ class PrescriptionLists extends BaseAdminDataLists implements ListsSearchInterfa
|
||||
}
|
||||
}
|
||||
|
||||
$orderRxIds = array_unique(array_map(
|
||||
'intval',
|
||||
PrescriptionOrder::whereIn('prescription_id', $rxIds)
|
||||
->whereNull('delete_time')
|
||||
->whereNotIn('fulfillment_status', PrescriptionOrder::RELEASED_PRESCRIPTION_STATUSES)
|
||||
->column('prescription_id')
|
||||
));
|
||||
$hasBizOrderRx = array_fill_keys($orderRxIds, true);
|
||||
$orders = PrescriptionOrder::whereIn('prescription_id', $rxIds)
|
||||
->whereNull('delete_time')
|
||||
->field(['prescription_id', 'fulfillment_status'])
|
||||
->select();
|
||||
foreach ($orders as $order) {
|
||||
$prescriptionId = (int) $order->prescription_id;
|
||||
if (in_array((int) $order->fulfillment_status, PrescriptionOrder::RELEASED_PRESCRIPTION_STATUSES, true)) {
|
||||
$hasReleasedOrderRx[$prescriptionId] = true;
|
||||
} else {
|
||||
$hasBizOrderRx[$prescriptionId] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 获取医助姓名
|
||||
@@ -295,7 +301,13 @@ class PrescriptionLists extends BaseAdminDataLists implements ListsSearchInterfa
|
||||
}
|
||||
|
||||
// 处理字段格式
|
||||
$voidAccess = $lists === [] ? [] : PrescriptionLogic::getVoidAccess($this->adminId, $this->adminInfo);
|
||||
foreach ($lists as &$item) {
|
||||
$rid = (int) $item['id'];
|
||||
$item['can_void'] = empty($item['void_status']) && empty($hasBizOrderRx[$rid])
|
||||
&& PrescriptionLogic::hasVoidAccess($item, $this->adminId, $this->adminInfo, $voidAccess)
|
||||
&& (empty($hasReleasedOrderRx[$rid]) || PrescriptionOrderLogic::remoteSnapshotLockErrorForPrescription($rid) === null);
|
||||
$item['can_restore_rejected'] = PrescriptionLogic::canRestoreRejected($item);
|
||||
$item['esign'] = \app\common\service\esign\PrescriptionEsignService::describe($item, (int) $this->adminId);
|
||||
// 设置默认值
|
||||
$item['usage_time'] = $item['usage_time'] ?? '饭前';
|
||||
@@ -307,7 +319,6 @@ class PrescriptionLists extends BaseAdminDataLists implements ListsSearchInterfa
|
||||
$item['audit_status'] = (int) ($item['audit_status'] ?? 1);
|
||||
$item['void_status'] = (int) ($item['void_status'] ?? 0);
|
||||
$item['visible_role_ids'] = PrescriptionLogic::visibleRoleIdsToArray((string) ($item['visible_role_ids'] ?? ''));
|
||||
$rid = (int) ($item['id'] ?? 0);
|
||||
$item['business_prescription_audit_rejected'] = !empty($rejectedRx[$rid]) ? 1 : 0;
|
||||
$item['business_prescription_audit_remark'] = (string) ($bizRejectRemark[$rid] ?? '');
|
||||
$item['has_prescription_order'] = !empty($hasBizOrderRx[$rid]) ? 1 : 0;
|
||||
|
||||
@@ -10,6 +10,7 @@ use app\common\model\doctor\Medicine as DoctorMedicine;
|
||||
use app\common\model\tcm\Prescription;
|
||||
use app\common\model\tcm\PrescriptionOrder;
|
||||
use app\common\model\tcm\Diagnosis;
|
||||
use app\common\service\DataScope\DataScopeService;
|
||||
use app\common\service\wechat\WechatWorkAppMessageService;
|
||||
use app\common\service\pharmacy\PharmacyHerbIdentityResolver;
|
||||
use app\common\service\pharmacy\LockedPharmacySnapshotMutation;
|
||||
@@ -24,6 +25,12 @@ use app\common\service\esign\PrescriptionEsignPolicy;
|
||||
|
||||
class PrescriptionLogic
|
||||
{
|
||||
public const PRESCRIBE_PERMISSIONS = [
|
||||
'tcm.prescription/add', 'cf.prescription/add', 'tcm.diagnosis/chufang', 'tcm.diagnosis/kaifang',
|
||||
];
|
||||
public const VOID_MANAGE_PERMISSIONS = ['tcm.prescription/void', 'cf.prescription/del'];
|
||||
public const AUDIT_PERMISSIONS = ['tcm.prescription/audit', 'cf.prescription/audit'];
|
||||
|
||||
private static $error = '';
|
||||
|
||||
/** @var array{ok: bool, message?: string, errcode?: int}|null 最近一次审核成功后的企微通知结果 */
|
||||
@@ -140,6 +147,70 @@ class PrescriptionLogic
|
||||
return false;
|
||||
}
|
||||
|
||||
/** @return array{own: bool, manage: bool, owner_ids: ?array} */
|
||||
public static function getVoidAccess(int $adminId, array $adminInfo): array
|
||||
{
|
||||
if ((int) ($adminInfo['root'] ?? 0) === 1) {
|
||||
return ['own' => true, 'manage' => true, 'owner_ids' => null];
|
||||
}
|
||||
|
||||
$uris = array_map('strtolower', AuthLogic::getAuthByAdminId($adminId));
|
||||
$hasVoidGrant = array_intersect(self::VOID_MANAGE_PERMISSIONS, $uris) !== [];
|
||||
$manage = ($hasVoidGrant || array_intersect(self::AUDIT_PERMISSIONS, $uris) !== [])
|
||||
&& self::canAuditPrescription($adminId, $adminInfo);
|
||||
$own = $hasVoidGrant || array_intersect(self::PRESCRIBE_PERMISSIONS, $uris) !== [];
|
||||
|
||||
return [
|
||||
'own' => $own,
|
||||
'manage' => $manage,
|
||||
'owner_ids' => ($own || $manage) ? DataScopeService::getVisibleAdminIds($adminId, $adminInfo) : [],
|
||||
];
|
||||
}
|
||||
|
||||
public static function hasVoidAccess(array $row, int $adminId, array $adminInfo, array $access): bool
|
||||
{
|
||||
$creator = (int) ($row['creator_id'] ?? 0);
|
||||
$assistant = (int) ($row['assistant_id'] ?? 0);
|
||||
$ownerIds = $access['owner_ids'];
|
||||
if ($adminId <= 0 || !empty($row['delete_time']) || ($ownerIds !== null
|
||||
&& !in_array($creator, $ownerIds, true) && !in_array($assistant, $ownerIds, true))) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return ($access['own'] && $creator === $adminId)
|
||||
|| ($access['manage'] && self::canViewPrescription($row, $adminId, $adminInfo));
|
||||
}
|
||||
|
||||
public static function canRestoreRejected(array $row): bool
|
||||
{
|
||||
return (int) ($row['audit_status'] ?? 0) === 2 && (int) ($row['void_status'] ?? 0) === 1
|
||||
&& (int) ($row['audit_time'] ?? 0) > 0 && (int) $row['audit_time'] === (int) ($row['void_time'] ?? 0)
|
||||
&& (int) ($row['audit_by'] ?? 0) > 0 && (int) $row['audit_by'] === (int) ($row['void_by'] ?? 0)
|
||||
&& (empty($row['esign_required']) || ($row['esign_status'] ?? 'pending') === 'pending');
|
||||
}
|
||||
|
||||
private static function withActionAvailability(array $row, int $viewerAdminId, array $viewerAdminInfo): array
|
||||
{
|
||||
$id = (int) $row['id'];
|
||||
// 与列表和创建校验一致:已取消 / 已退款的订单保留历史关联,但不再占用处方。
|
||||
$hasBizOrder = PrescriptionOrder::where('prescription_id', $id)
|
||||
->whereNull('delete_time')
|
||||
->whereNotIn('fulfillment_status', PrescriptionOrder::RELEASED_PRESCRIPTION_STATUSES)
|
||||
->count() > 0;
|
||||
$row['has_prescription_order'] = $hasBizOrder ? 1 : 0;
|
||||
$row['can_restore_rejected'] = self::canRestoreRejected($row);
|
||||
$row['can_void'] = !$hasBizOrder && empty($row['void_status'])
|
||||
&& self::hasVoidAccess(
|
||||
$row,
|
||||
$viewerAdminId,
|
||||
$viewerAdminInfo,
|
||||
self::getVoidAccess($viewerAdminId, $viewerAdminInfo)
|
||||
)
|
||||
&& PrescriptionOrderLogic::remoteSnapshotLockErrorForPrescription($id) === null;
|
||||
|
||||
return $row;
|
||||
}
|
||||
|
||||
private static function generateSn(): string
|
||||
{
|
||||
return 'RX' . date('Ymd') . str_pad((string)mt_rand(1, 9999), 4, '0', STR_PAD_LEFT);
|
||||
@@ -463,7 +534,12 @@ class PrescriptionLogic
|
||||
}
|
||||
|
||||
// 已通过且未作废:不可编辑
|
||||
PrescriptionEsignPolicy::assertMutable($prescription->toArray());
|
||||
$current = $prescription->toArray();
|
||||
PrescriptionEsignPolicy::assertMutable($current);
|
||||
if (!empty($prescription->void_status) && !self::canRestoreRejected($current)) {
|
||||
self::setError('该处方已作废,请重新开方');
|
||||
return false;
|
||||
}
|
||||
if ((int) ($prescription->audit_status ?? 1) === 1 && (int) ($prescription->void_status ?? 0) === 0) {
|
||||
self::setError('该处方已通过审核,不可编辑');
|
||||
return false;
|
||||
@@ -807,7 +883,6 @@ class PrescriptionLogic
|
||||
$arr = $row->toArray();
|
||||
$arr['esign'] = PrescriptionEsignService::describe($arr, $viewerAdminId);
|
||||
$arr['gender_desc'] = $arr['gender'] == 1 ? '男' : '女';
|
||||
$arr['visible_role_ids'] = self::visibleRoleIdsToArray($arr['visible_role_ids'] ?? '');
|
||||
|
||||
$bizPo = PrescriptionOrder::where('prescription_id', $id)
|
||||
->where('prescription_audit_status', 2)
|
||||
@@ -818,12 +893,8 @@ class PrescriptionLogic
|
||||
$arr['business_prescription_audit_rejected'] = $bizPo ? 1 : 0;
|
||||
$arr['business_prescription_audit_remark'] = $bizPo ? (string) ($bizPo->prescription_audit_remark ?? '') : '';
|
||||
|
||||
// 与列表和创建校验一致:已取消 / 已退款的订单保留历史关联,但不再占用处方。
|
||||
$hasBizOrder = PrescriptionOrder::where('prescription_id', $id)
|
||||
->whereNull('delete_time')
|
||||
->whereNotIn('fulfillment_status', PrescriptionOrder::RELEASED_PRESCRIPTION_STATUSES)
|
||||
->count() > 0;
|
||||
$arr['has_prescription_order'] = $hasBizOrder ? 1 : 0;
|
||||
$arr = self::withActionAvailability($arr, $viewerAdminId, $viewerAdminInfo);
|
||||
$arr['visible_role_ids'] = self::visibleRoleIdsToArray($arr['visible_role_ids'] ?? '');
|
||||
|
||||
/**
|
||||
* 处方笺展示所需的"收件信息/订单号/合计"等字段,
|
||||
@@ -871,7 +942,7 @@ class PrescriptionLogic
|
||||
if (!$row || (int) ($row->void_status ?? 0) === 1 || (int) ($row->audit_status ?? 1) !== 0) {
|
||||
return null;
|
||||
}
|
||||
PrescriptionEsignService::assertSignedById($prescriptionId);
|
||||
PrescriptionEsignService::assertSignedById($prescriptionId, false, $adminId);
|
||||
$row->audit_status = 1;
|
||||
$row->audit_time = time();
|
||||
$row->audit_by = $adminId;
|
||||
@@ -879,7 +950,7 @@ class PrescriptionLogic
|
||||
$row->audit_remark = $finalRemark;
|
||||
return $row->save() ? $row : null;
|
||||
});
|
||||
if ($row) {
|
||||
if ($row && (empty($row->esign_required) || !PrescriptionEsignService::isSandboxTest($prescriptionId))) {
|
||||
self::$lastAuditWecomNotify = self::notifyCreatorAuditResult($row, 'approve', $finalRemark, $adminInfo);
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
@@ -928,7 +999,9 @@ class PrescriptionLogic
|
||||
if (!$row) {
|
||||
return false;
|
||||
}
|
||||
self::$lastAuditWecomNotify = self::notifyCreatorAuditResult($row, $action, $remark, $adminInfo);
|
||||
if (empty($row->esign_required) || !PrescriptionEsignService::isSandboxTest($id)) {
|
||||
self::$lastAuditWecomNotify = self::notifyCreatorAuditResult($row, $action, $remark, $adminInfo);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -958,7 +1031,7 @@ class PrescriptionLogic
|
||||
|
||||
if ($action === 'approve') {
|
||||
try {
|
||||
PrescriptionEsignService::assertSignedById($id);
|
||||
PrescriptionEsignService::assertSignedById($id, false, $adminId);
|
||||
} catch (\DomainException $e) {
|
||||
self::setError($e->getMessage());
|
||||
return false;
|
||||
@@ -1135,7 +1208,7 @@ class PrescriptionLogic
|
||||
|
||||
$result = $row->toArray();
|
||||
$result['esign'] = PrescriptionEsignService::describe($result, $viewerAdminId);
|
||||
return $result;
|
||||
return self::withActionAvailability($result, $viewerAdminId, $viewerAdminInfo);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1275,13 +1348,21 @@ class PrescriptionLogic
|
||||
/**
|
||||
* 作废处方
|
||||
*/
|
||||
public static function void(int $id, int $adminId, string $adminName): bool
|
||||
public static function void(int $id, int $adminId, array $adminInfo): bool
|
||||
{
|
||||
self::setError('');
|
||||
try {
|
||||
// Check visibility before taking pharmacy locks or reporting order state.
|
||||
$access = self::getVoidAccess($adminId, $adminInfo);
|
||||
$row = Prescription::where('id', $id)->whereNull('delete_time')->find();
|
||||
if (!$row || !self::hasVoidAccess($row->toArray(), $adminId, $adminInfo, $access)) {
|
||||
self::setError('处方不存在或无权作废');
|
||||
return false;
|
||||
}
|
||||
|
||||
return (bool) LockedPharmacySnapshotMutation::executeForPrescription(
|
||||
$id,
|
||||
static fn (): bool => self::voidLocked($id, $adminId, $adminName)
|
||||
static fn (): bool => self::voidLocked($id, $adminId, $adminInfo, $access)
|
||||
);
|
||||
} catch (\Throwable $exception) {
|
||||
if (self::getError() === '') {
|
||||
@@ -1291,11 +1372,11 @@ class PrescriptionLogic
|
||||
}
|
||||
}
|
||||
|
||||
private static function voidLocked(int $id, int $adminId, string $adminName): bool
|
||||
private static function voidLocked(int $id, int $adminId, array $adminInfo, array $access): bool
|
||||
{
|
||||
$row = Prescription::where('id', $id)->lock(true)->find();
|
||||
if (!$row) {
|
||||
self::setError('处方不存在');
|
||||
$row = Prescription::where('id', $id)->whereNull('delete_time')->lock(true)->find();
|
||||
if (!$row || !self::hasVoidAccess($row->toArray(), $adminId, $adminInfo, $access)) {
|
||||
self::setError('处方不存在或无权作废');
|
||||
return false;
|
||||
}
|
||||
if ((int)($row->void_status ?? 0) === 1) {
|
||||
@@ -1315,7 +1396,7 @@ class PrescriptionLogic
|
||||
$row->void_status = 1;
|
||||
$row->void_time = time();
|
||||
$row->void_by = $adminId;
|
||||
$row->void_by_name = $adminName;
|
||||
$row->void_by_name = (string) ($adminInfo['name'] ?? '');
|
||||
$saved = (bool) $row->save();
|
||||
if ($saved) {
|
||||
PrescriptionAiStore::invalidate($id, 'voided');
|
||||
|
||||
@@ -60,10 +60,10 @@ class PrescriptionOrderLogic
|
||||
return self::$error;
|
||||
}
|
||||
|
||||
private static function assertEsignApproved(PrescriptionOrder $order, bool $forDispensing = false): bool
|
||||
private static function assertEsignApproved(PrescriptionOrder $order, bool $forDispensing = false, ?int $reviewer = null): bool
|
||||
{
|
||||
try {
|
||||
PrescriptionEsignService::assertSignedById((int) $order->prescription_id, $forDispensing);
|
||||
PrescriptionEsignService::assertSignedById((int) $order->prescription_id, $forDispensing, $reviewer);
|
||||
return true;
|
||||
} catch (\DomainException $e) {
|
||||
self::$error = $e->getMessage();
|
||||
@@ -2397,7 +2397,7 @@ class PrescriptionOrderLogic
|
||||
|
||||
return false;
|
||||
}
|
||||
if (!self::canAuditPrescriptionOrder($adminInfo)) {
|
||||
if (!self::canAuditPrescriptionOrder($adminInfo) || !self::canAccessOrder($order, $adminId, $adminInfo)) {
|
||||
self::$error = '无处方审核权限';
|
||||
|
||||
return false;
|
||||
@@ -2424,7 +2424,7 @@ class PrescriptionOrderLogic
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($action === 'approve' && !self::assertEsignApproved($order)) {
|
||||
if ($action === 'approve' && !self::assertEsignApproved($order, false, $adminId)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -2870,10 +2870,10 @@ class PrescriptionOrderLogic
|
||||
|
||||
return false;
|
||||
}
|
||||
if ($newRx === 1 && !self::assertEsignApproved($order)) {
|
||||
$oldRx = (int) $order->prescription_audit_status;
|
||||
if ($newRx === 1 && $newRx !== $oldRx && !self::assertEsignApproved($order, false, $adminId)) {
|
||||
return false;
|
||||
}
|
||||
$oldRx = (int) $order->prescription_audit_status;
|
||||
if ($newRx !== $oldRx) {
|
||||
$order->prescription_audit_status = $newRx;
|
||||
$changeParts[] = '处方审核:' . self::auditStatusLabelForLog($oldRx)
|
||||
|
||||
@@ -10,6 +10,7 @@ use think\console\Input;
|
||||
use think\console\Output;
|
||||
use think\console\input\Option;
|
||||
use think\facade\Config;
|
||||
use think\facade\Db;
|
||||
|
||||
final class EsignSetup extends Command
|
||||
{
|
||||
@@ -17,7 +18,8 @@ final class EsignSetup extends Command
|
||||
{
|
||||
$this->setName('esign:setup')->setDescription('检查 e签宝配置、初始化内网 SDK 或恢复已归档签署结果')
|
||||
->addOption('initialize', null, Option::VALUE_NONE, '初始化已部署的 SDK;不创建医生、认证或处方签署')
|
||||
->addOption('recover', null, Option::VALUE_REQUIRED, '重新验签已归档的处方 ID;不会再次签署');
|
||||
->addOption('recover', null, Option::VALUE_REQUIRED, '重新验签已归档的处方 ID;不会再次签署')
|
||||
->addOption('backfill-signature-times', null, Option::VALUE_NONE, '从当前签署环境及应用的已验签原件补录签署时间');
|
||||
}
|
||||
|
||||
protected function execute(Input $input, Output $output): int
|
||||
@@ -34,6 +36,9 @@ final class EsignSetup extends Command
|
||||
}
|
||||
PrescriptionEsignService::recover($id);
|
||||
$output->writeln('原件验签及状态恢复完成;未发送新的签署请求');
|
||||
} elseif ($input->getOption('backfill-signature-times')) {
|
||||
(new EsignClient())->assertConfigured();
|
||||
return $this->backfillSignatureTimes($config, $output);
|
||||
} elseif ($input->getOption('initialize')) {
|
||||
// Deployment may initialize before enabling the new clinical workflow.
|
||||
$client = new EsignClient(array_merge($config, ['enabled' => true]));
|
||||
@@ -49,4 +54,28 @@ final class EsignSetup extends Command
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
private function backfillSignatureTimes(array $config, Output $output): int
|
||||
{
|
||||
$filled = 0;
|
||||
$failed = 0;
|
||||
Db::name('prescription_esign')
|
||||
->where('environment', $config['environment'])->where('app_id', $config['app_id'])
|
||||
->where('signed_at', '>', 0)->where('signature_time', 0)->field('prescription_id')
|
||||
->chunk(100, static function ($rows) use ($output, &$filled, &$failed): void {
|
||||
foreach ($rows as $row) {
|
||||
$id = (int) $row['prescription_id'];
|
||||
try {
|
||||
PrescriptionEsignService::recover($id);
|
||||
$filled++;
|
||||
} catch (\Throwable $error) {
|
||||
$failed++;
|
||||
$message = $error instanceof \DomainException ? $error->getMessage() : '暂时无法验签,请检查 SDK 服务';
|
||||
$output->writeln("处方 {$id} 的签署时间待核实({$message})");
|
||||
}
|
||||
}
|
||||
}, 'prescription_id');
|
||||
$output->writeln("签署时间补录完成 {$filled} 张,待核实 {$failed} 张");
|
||||
return $failed === 0 ? 0 : 1;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\common\service\esign;
|
||||
|
||||
final class DoctorEsignAuthorizationRequired extends \DomainException
|
||||
{
|
||||
public function __construct(public readonly string $reason)
|
||||
{
|
||||
parent::__construct(match ($reason) {
|
||||
'exhausted' => '医生实名和证书已保存。e签宝签署授权次数已用完,请在账号菜单查看快捷签授权',
|
||||
'expired' => '医生实名和证书已保存。快捷签授权已到期,请在账号菜单续期',
|
||||
'invalid' => '医生实名和证书已保存。e签宝签署授权已失效,请在账号菜单检查授权',
|
||||
default => '医生实名和证书已保存。请在账号菜单的「医生电子签署身份」中授权快捷签',
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\common\service\esign;
|
||||
|
||||
final class DoctorEsignIdentityRequired extends \DomainException
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,625 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\common\service\esign;
|
||||
|
||||
use DateTimeImmutable;
|
||||
use DateTimeZone;
|
||||
use DomainException;
|
||||
use think\facade\Config;
|
||||
use think\facade\Db;
|
||||
|
||||
final class DoctorEsignIdentityService
|
||||
{
|
||||
private const DOCTOR_ROLE_ID = 1;
|
||||
private const FLOW_LIFETIME = 30 * 86400;
|
||||
private const ACCOUNT_BINDING_PROOF_LIFETIME = 30 * 60;
|
||||
private const QUICK_LIFETIME = 86400;
|
||||
private const IDENTITY_FLOW_TABLE = 'doctor_esign_identity';
|
||||
private const QUICK_FLOW_TABLE = 'doctor_esign_quicksign';
|
||||
private const STATE_CHANGED = '医师认证状态已变化,请重新查询';
|
||||
|
||||
public static function enabled(): bool
|
||||
{
|
||||
return PrescriptionEsignService::enabled()
|
||||
&& (filter_var(Config::get('esign.doctor_sms_enabled', false), FILTER_VALIDATE_BOOLEAN) || self::quickEnabled());
|
||||
}
|
||||
|
||||
public static function quickEnabled(): bool
|
||||
{
|
||||
return PrescriptionEsignService::enabled()
|
||||
&& filter_var(Config::get('esign.doctor_quicksign_enabled', false), FILTER_VALIDATE_BOOLEAN);
|
||||
}
|
||||
|
||||
public static function status(int $actor): array
|
||||
{
|
||||
if (!self::enabled()) {
|
||||
return ['enabled' => false] + self::state('unbound', '医师电子签署认证尚未启用');
|
||||
}
|
||||
$scope = self::scope($actor);
|
||||
$snapshot = self::snapshot($scope);
|
||||
if (self::hasLease($snapshot['flow'])) {
|
||||
return self::processing();
|
||||
}
|
||||
|
||||
$client = new EsignClient();
|
||||
if (self::hasCurrentFlow($snapshot)) {
|
||||
[$status, $person] = self::identityResult($client, $snapshot);
|
||||
if ($pending = self::pendingState($snapshot, $status, ($person['idNo'] ?? null) === null)) {
|
||||
self::assertUnchanged($scope, $snapshot);
|
||||
return $pending;
|
||||
}
|
||||
}
|
||||
$quick = self::quickEnabled() ? self::snapshot($scope, false, self::QUICK_FLOW_TABLE) : null;
|
||||
if ($quick !== null && self::hasLease($quick['flow'])) {
|
||||
return self::processing(true);
|
||||
}
|
||||
if ($quick !== null && self::hasPendingQuickFlow($quick)) {
|
||||
[$quickStatus] = self::identityResult($client, $quick);
|
||||
if ($pending = self::pendingState($quick, $quickStatus, false)) {
|
||||
self::assertUnchanged($scope, $quick);
|
||||
return $pending;
|
||||
}
|
||||
}
|
||||
$state = self::readiness($client, $snapshot, true, $quick === null)['state'];
|
||||
if (isset($status) && $state['status'] !== 'ready') {
|
||||
$state['message'] = $status === 'FAIL' ? '认证未通过,请重新发起认证' : '认证已过期,请重新发起认证';
|
||||
}
|
||||
if ($quick !== null && $state['status'] === 'ready') {
|
||||
$state = self::withQuickValidity($state, self::quickValidity($client, $quick));
|
||||
if (($quickStatus ?? '') === 'FAIL') {
|
||||
$state['message'] = '快捷签认证未通过,请重新发起授权';
|
||||
}
|
||||
}
|
||||
if ($quick !== null) {
|
||||
self::assertUnchanged($scope, $quick);
|
||||
}
|
||||
self::assertUnchanged($scope, $snapshot);
|
||||
return $state;
|
||||
}
|
||||
|
||||
public static function start(int $actor, string $mobile): array
|
||||
{
|
||||
$scope = self::scope($actor);
|
||||
$mobile = trim($mobile);
|
||||
if (self::quickEnabled() && $mobile === '') {
|
||||
return self::startQuick($scope);
|
||||
}
|
||||
if (!self::validMobile($mobile)) {
|
||||
throw new DomainException('请输入有效的大陆手机号');
|
||||
}
|
||||
$mobileHash = self::mobileHash($scope, $mobile);
|
||||
$snapshot = self::snapshot($scope);
|
||||
if (self::hasLease($snapshot['flow'])) {
|
||||
return self::processing();
|
||||
}
|
||||
$client = new EsignClient();
|
||||
if (self::hasCurrentFlow($snapshot) && hash_equals($snapshot['flow']['mobile_hash'], $mobileHash)) {
|
||||
[$status, $person] = self::identityResult($client, $snapshot);
|
||||
if ($pending = self::pendingState($snapshot, $status, ($person['idNo'] ?? null) === null)) {
|
||||
self::assertUnchanged($scope, $snapshot);
|
||||
return $pending;
|
||||
}
|
||||
}
|
||||
$state = self::readiness($client, $snapshot, true, !self::quickEnabled())['state'];
|
||||
if ($state['status'] === 'ready') {
|
||||
self::assertUnchanged($scope, $snapshot);
|
||||
return self::quickEnabled() ? self::status($actor) : $state;
|
||||
}
|
||||
|
||||
$token = self::claim($scope, $snapshot);
|
||||
try {
|
||||
$accountId = $snapshot['account']['account_id'] ?? null;
|
||||
$flow = $client->startDoctorIdentity($snapshot['name'], 'doctor-enrollment-' . $token, $mobile, $accountId);
|
||||
self::finish($scope, $snapshot, $token, [
|
||||
'doctor_name' => $snapshot['name'],
|
||||
'account_id' => $accountId ?? '',
|
||||
'flow_id' => $flow['flow_id'],
|
||||
'auth_url' => $flow['auth_url'],
|
||||
'mobile_hash' => $mobileHash,
|
||||
'flow_started_at' => time(),
|
||||
]);
|
||||
return self::state('authenticating', '请完成医师实名认证') + ['auth_url' => $flow['auth_url']];
|
||||
} catch (\Throwable $error) {
|
||||
self::release($scope, $snapshot, $token);
|
||||
throw $error;
|
||||
}
|
||||
}
|
||||
|
||||
public static function complete(int $actor, string $identityNumber = ''): array
|
||||
{
|
||||
$scope = self::scope($actor);
|
||||
$snapshot = self::snapshot($scope);
|
||||
if (self::hasLease($snapshot['flow'])) {
|
||||
return self::processing();
|
||||
}
|
||||
if (!self::hasCurrentFlow($snapshot)) {
|
||||
if (self::quickEnabled()) {
|
||||
return self::completeQuick($scope);
|
||||
}
|
||||
return self::status($actor);
|
||||
}
|
||||
|
||||
$token = self::claim($scope, $snapshot);
|
||||
try {
|
||||
$client = new EsignClient();
|
||||
[$status, $person] = self::identityResult($client, $snapshot);
|
||||
if ($status === 'FAIL' || $status === 'EXPIRED') {
|
||||
self::finish($scope, $snapshot, $token, null);
|
||||
$state = self::status($actor);
|
||||
if ($state['status'] !== 'ready') {
|
||||
$state['message'] = $status === 'FAIL' ? '认证未通过,请重新发起认证' : '认证已过期,请重新发起认证';
|
||||
}
|
||||
return $state;
|
||||
}
|
||||
if ($status !== 'SUCCESS') {
|
||||
self::finish($scope, $snapshot, $token, []);
|
||||
return self::pendingState($snapshot, $status, false);
|
||||
}
|
||||
|
||||
if ($person && self::validMobile($person['mobile'])
|
||||
&& !hash_equals($snapshot['flow']['mobile_hash'], self::mobileHash($scope, $person['mobile']))) {
|
||||
self::finish($scope, $snapshot, $token, null);
|
||||
throw new DomainException('认证手机号与本次发起的手机号不一致,请重新发起认证');
|
||||
}
|
||||
$newAccountId = null;
|
||||
if ($snapshot['account']) {
|
||||
$document = self::accountDocument($client, $snapshot);
|
||||
if ($person && $person['idNo'] !== null && !hash_equals($document, $person['idNo'])) {
|
||||
throw new DomainException('认证证件与签署账号不一致,请联系管理员核实');
|
||||
}
|
||||
} else {
|
||||
$document = $person['idNo'] ?? null;
|
||||
if ($document === null) {
|
||||
$document = strtoupper(trim($identityNumber));
|
||||
if (!PrescriptionEsignService::validMainlandIdentityNumber($document)) {
|
||||
self::finish($scope, $snapshot, $token, []);
|
||||
$state = self::pendingState($snapshot, 'SUCCESS', true);
|
||||
if ($document !== '') {
|
||||
$state['message'] = '请输入本次认证使用的有效大陆身份证号码';
|
||||
}
|
||||
return $state;
|
||||
}
|
||||
}
|
||||
// eSign matches the document and name against the authenticated identity before issuing the account.
|
||||
$newAccountId = $client->createPerson($snapshot['name'], $document, $snapshot['flow']['flow_id']);
|
||||
}
|
||||
unset($identityNumber, $person, $document);
|
||||
self::finish($scope, $snapshot, $token, null, $newAccountId);
|
||||
} catch (\Throwable $error) {
|
||||
self::release($scope, $snapshot, $token);
|
||||
throw $error;
|
||||
}
|
||||
return self::status($actor);
|
||||
}
|
||||
|
||||
/** Returns the current doctor-scoped proof for the provider call only. */
|
||||
public static function quickAuthorization(int $actor, string $signerName, string $accountId): string
|
||||
{
|
||||
if (!self::quickEnabled()) {
|
||||
throw new DomainException('快捷签设置已变化,请重新查询处方');
|
||||
}
|
||||
$scope = self::scope($actor);
|
||||
$snapshot = self::snapshot($scope, false, self::QUICK_FLOW_TABLE);
|
||||
if (!$snapshot['account']) {
|
||||
throw new DoctorEsignIdentityRequired('请先在医师电子签署设置中完成实名认证');
|
||||
}
|
||||
if ($snapshot['name'] !== $signerName || $snapshot['account']['doctor_name'] !== $signerName
|
||||
|| $snapshot['account']['account_id'] !== $accountId) {
|
||||
throw new DomainException('处方签署账号已变化,请重试');
|
||||
}
|
||||
$client = new EsignClient();
|
||||
[$certStart, $certEnd] = self::certificatePeriod($client, $accountId);
|
||||
if (!$certStart || $certStart > time() || $certEnd <= time()) {
|
||||
throw new DoctorEsignIdentityRequired('医师签署证书需要续期,请在账号菜单中处理');
|
||||
}
|
||||
$validity = self::quickValidity($client, $snapshot);
|
||||
self::assertUnchanged($scope, $snapshot);
|
||||
if ($certEnd <= time()) {
|
||||
throw new DoctorEsignIdentityRequired('医师签署证书需要续期,请在账号菜单中处理');
|
||||
}
|
||||
if ($validity['state'] !== 'valid') {
|
||||
throw new DoctorEsignAuthorizationRequired($validity['state']);
|
||||
}
|
||||
if ($validity['expires_at'] <= time()) {
|
||||
throw new DoctorEsignAuthorizationRequired('expired');
|
||||
}
|
||||
return $snapshot['flow']['flow_id'];
|
||||
}
|
||||
|
||||
private static function startQuick(array $scope): array
|
||||
{
|
||||
$snapshot = self::snapshot($scope, false, self::QUICK_FLOW_TABLE);
|
||||
if (self::hasLease($snapshot['flow'])) {
|
||||
return self::processing(true);
|
||||
}
|
||||
$client = new EsignClient();
|
||||
if (self::hasPendingQuickFlow($snapshot)) {
|
||||
[$status] = self::identityResult($client, $snapshot);
|
||||
if ($pending = self::pendingState($snapshot, $status, false)) {
|
||||
self::assertUnchanged($scope, $snapshot);
|
||||
return $pending;
|
||||
}
|
||||
}
|
||||
$ready = self::readiness($client, $snapshot, true, false);
|
||||
$state = $ready['state'];
|
||||
if ($state['status'] !== 'ready') {
|
||||
self::assertUnchanged($scope, $snapshot);
|
||||
return $state;
|
||||
}
|
||||
$state = self::withQuickValidity($state, self::quickValidity($client, $snapshot));
|
||||
if ($state['quicksign_expires_at'] > time()) {
|
||||
self::assertUnchanged($scope, $snapshot);
|
||||
return $state;
|
||||
}
|
||||
|
||||
$token = self::claim($scope, $snapshot);
|
||||
try {
|
||||
$accountId = $snapshot['account']['account_id'];
|
||||
$flow = $client->startDoctorQuickAuthorization($snapshot['name'], $ready['idNo'], 'doctor-quicksign-' . $token, $accountId);
|
||||
self::finish($scope, $snapshot, $token, [
|
||||
'doctor_name' => $snapshot['name'], 'account_id' => $accountId, 'flow_id' => $flow['flow_id'],
|
||||
'auth_url' => $flow['auth_url'], 'flow_started_at' => time(), 'expires_at' => 0,
|
||||
]);
|
||||
return self::state('authenticating', '请完成快捷签人脸认证', 0, true) + ['auth_url' => $flow['auth_url']];
|
||||
} catch (\Throwable $error) {
|
||||
self::release($scope, $snapshot, $token);
|
||||
throw $error;
|
||||
}
|
||||
}
|
||||
|
||||
private static function completeQuick(array $scope): array
|
||||
{
|
||||
$snapshot = self::snapshot($scope, false, self::QUICK_FLOW_TABLE);
|
||||
if (self::hasLease($snapshot['flow'])) {
|
||||
return self::processing(true);
|
||||
}
|
||||
if (!self::hasPendingQuickFlow($snapshot)) {
|
||||
return self::status($scope['doctor_id']);
|
||||
}
|
||||
|
||||
$token = self::claim($scope, $snapshot);
|
||||
try {
|
||||
$client = new EsignClient();
|
||||
[$status, $person, $completedAt] = self::identityResult($client, $snapshot);
|
||||
if ($status === 'INIT' || $status === 'ING') {
|
||||
self::finish($scope, $snapshot, $token, []);
|
||||
return self::pendingState($snapshot, $status, false);
|
||||
}
|
||||
$expires = 0;
|
||||
if ($status === 'SUCCESS') {
|
||||
$document = self::accountDocument($client, $snapshot);
|
||||
if ($person && $person['idNo'] !== null && !hash_equals($document, $person['idNo'])) {
|
||||
self::finish($scope, $snapshot, $token, null);
|
||||
throw new DomainException('认证证件与签署账号不一致,请联系管理员核实');
|
||||
}
|
||||
$providerExpiry = intdiv($client->willingnessValidity($snapshot['flow']['flow_id'])['expires_at'], 1000);
|
||||
$expires = min($providerExpiry, min(time(), $completedAt) + self::QUICK_LIFETIME);
|
||||
}
|
||||
if ($expires <= time()) {
|
||||
self::finish($scope, $snapshot, $token, null);
|
||||
$state = self::status($scope['doctor_id']);
|
||||
$state['message'] = $status === 'FAIL' ? '快捷签认证未通过,请重新发起授权' : '快捷签授权已失效,请重新发起授权';
|
||||
return $state;
|
||||
}
|
||||
self::finish($scope, $snapshot, $token, ['auth_url' => null, 'expires_at' => $expires]);
|
||||
} catch (\Throwable $error) {
|
||||
self::release($scope, $snapshot, $token);
|
||||
throw $error;
|
||||
}
|
||||
return self::status($scope['doctor_id']);
|
||||
}
|
||||
|
||||
/** @return array{state:string,expires_at:int,remaining_times:int} Expiration is in Unix seconds. */
|
||||
private static function quickValidity(EsignClient $client, array $snapshot): array
|
||||
{
|
||||
$flow = $snapshot['flow'];
|
||||
$localExpiry = (int) ($flow['expires_at'] ?? 0);
|
||||
$missing = ['state' => 'missing', 'expires_at' => 0, 'remaining_times' => 0];
|
||||
if (!$localExpiry || empty($flow['flow_id']) || self::hasLease($flow)) {
|
||||
return $missing;
|
||||
}
|
||||
if (!$snapshot['account'] || $snapshot['account']['doctor_name'] !== $snapshot['name']
|
||||
|| $flow['doctor_name'] !== $snapshot['name'] || $flow['account_id'] !== $snapshot['account']['account_id']) {
|
||||
return ['state' => 'invalid'] + $missing;
|
||||
}
|
||||
if ($localExpiry <= time()) {
|
||||
return ['state' => 'expired'] + $missing;
|
||||
}
|
||||
$validity = $client->willingnessValidity($flow['flow_id']);
|
||||
if ($validity['state'] !== 'valid') {
|
||||
return $validity;
|
||||
}
|
||||
$validity['expires_at'] = min($localExpiry, intdiv($validity['expires_at'], 1000));
|
||||
return $validity['expires_at'] > time() ? $validity : ['state' => 'expired'] + $missing;
|
||||
}
|
||||
|
||||
private static function withQuickValidity(array $state, array $validity): array
|
||||
{
|
||||
$state['quicksign_expires_at'] = $validity['expires_at'];
|
||||
$state['quicksign_remaining_times'] = $validity['remaining_times'];
|
||||
$state['quicksign_unavailable_reason'] = $validity['state'] === 'valid' ? '' : $validity['state'];
|
||||
return $state;
|
||||
}
|
||||
|
||||
/** @return array{name:string,idNo:string,mobile:string} For the provider call only. */
|
||||
public static function willingnessRecipient(int $actor, string $signerName, string $accountId): array
|
||||
{
|
||||
$scope = self::scope($actor);
|
||||
$snapshot = self::snapshot($scope);
|
||||
if (!$snapshot['account']) {
|
||||
throw new DoctorEsignIdentityRequired('请先在医师电子签署设置中完成实名认证');
|
||||
}
|
||||
if ($snapshot['name'] !== $signerName || $snapshot['account']['account_id'] !== $accountId) {
|
||||
throw new DomainException('处方签署账号已变化,请重试');
|
||||
}
|
||||
$ready = self::readiness(new EsignClient(), $snapshot);
|
||||
$current = self::snapshot($scope);
|
||||
if ($current['name'] !== $snapshot['name'] || $current['account'] !== $snapshot['account']) {
|
||||
throw new DomainException(self::STATE_CHANGED);
|
||||
}
|
||||
if ($ready['state']['status'] !== 'ready') {
|
||||
throw new DoctorEsignIdentityRequired($ready['state']['message']);
|
||||
}
|
||||
if ($ready['state']['cert_expires_at'] <= time()) {
|
||||
throw new DoctorEsignIdentityRequired('医师签署证书已过期,请重新认证');
|
||||
}
|
||||
return ['name' => $signerName, 'idNo' => $ready['idNo'], 'mobile' => $ready['mobile']];
|
||||
}
|
||||
|
||||
private static function readiness(EsignClient $client, array $snapshot, bool $allowCertificateRecovery = false, bool $requireMobile = true): array
|
||||
{
|
||||
if (!$snapshot['account']) {
|
||||
return ['state' => self::state('unbound', '请先完成医师实名认证')];
|
||||
}
|
||||
$idNo = self::accountDocument($client, $snapshot);
|
||||
try {
|
||||
[$start, $end] = self::certificatePeriod($client, $snapshot['account']['account_id']);
|
||||
} catch (EsignProviderException $error) {
|
||||
// The SDK does not define a distinct response code for no available certificate.
|
||||
if (!$allowCertificateRecovery || !str_starts_with($error->providerCode, 'PROVIDER_')) {
|
||||
throw $error;
|
||||
}
|
||||
return ['state' => self::state('renewal_required', '暂时无法确认签署证书有效期,可重新查询或发起续期')];
|
||||
}
|
||||
if ($start === 0 || $start > time() || $end <= time()) {
|
||||
return ['state' => self::state('renewal_required', '医师签署证书需要续期,请重新认证', $end)];
|
||||
}
|
||||
$mobile = $requireMobile ? $client->authorizedMobile($snapshot['name'], $idNo) : null;
|
||||
if ($requireMobile && !self::validMobile($mobile)) {
|
||||
return ['state' => self::state('needs_mobile', '请完成实名手机号认证', $end)];
|
||||
}
|
||||
if ($end <= time()) {
|
||||
return ['state' => self::state('renewal_required', '医师签署证书需要续期,请重新认证', $end)];
|
||||
}
|
||||
return ['state' => self::state('ready', '医师电子签署已就绪', $end), 'idNo' => $idNo, 'mobile' => $mobile];
|
||||
}
|
||||
|
||||
private static function accountDocument(EsignClient $client, array $snapshot): string
|
||||
{
|
||||
$account = $snapshot['account'];
|
||||
if ($account['doctor_name'] !== $snapshot['name']) {
|
||||
throw new DomainException('签署账号实名信息已变化,请联系管理员核实');
|
||||
}
|
||||
$details = $client->signingAccount($account['account_id']);
|
||||
$idNo = $details['idNo'] ?? '';
|
||||
if (($details['accountId'] ?? '') !== $account['account_id'] || ($details['name'] ?? '') !== $snapshot['name']
|
||||
|| ($details['accountType'] ?? '') !== 'PERSON' || ($details['idNoType'] ?? '') !== 'MAINLAND'
|
||||
|| !is_string($idNo) || !preg_match('/^(?:[0-9]{15}|[0-9]{17}[0-9Xx])$/D', $idNo)) {
|
||||
throw new DomainException('签署账号实名信息不一致,请联系管理员核实');
|
||||
}
|
||||
return strtoupper($idNo);
|
||||
}
|
||||
|
||||
/** @return array{int,int} */
|
||||
private static function certificatePeriod(EsignClient $client, string $accountId): array
|
||||
{
|
||||
$dates = $client->certificateValidity($accountId);
|
||||
return [self::certificateTime($dates['startDate'] ?? ''), self::certificateTime($dates['endDate'] ?? '')];
|
||||
}
|
||||
|
||||
/** SDK validity timestamps are local to the configured SDK timezone. */
|
||||
private static function certificateTime(string $value): int
|
||||
{
|
||||
if ($value === '') {
|
||||
return 0;
|
||||
}
|
||||
$zone = new DateTimeZone((string) Config::get('esign.sdk_timezone', 'Asia/Shanghai'));
|
||||
$time = DateTimeImmutable::createFromFormat('!Y-m-d H:i:s', $value, $zone);
|
||||
if (!$time || $time->format('Y-m-d H:i:s') !== $value) {
|
||||
throw new DomainException('暂时无法确认医师签署证书有效期,请稍后重试');
|
||||
}
|
||||
return $time->getTimestamp();
|
||||
}
|
||||
|
||||
private static function identityResult(EsignClient $client, array $snapshot): array
|
||||
{
|
||||
$flow = $snapshot['flow'];
|
||||
$detail = $client->identityDetail($flow['flow_id']);
|
||||
$status = $detail['status'] ?? '';
|
||||
if (($detail['flowId'] ?? '') !== $flow['flow_id']
|
||||
|| (isset($detail['appId']) && (string) $detail['appId'] !== $flow['app_id'])
|
||||
|| !in_array($status, ['INIT', 'ING', 'SUCCESS', 'FAIL'], true)) {
|
||||
throw new DomainException('暂时无法确认本次医师认证,请稍后重试');
|
||||
}
|
||||
if ($status !== 'SUCCESS') {
|
||||
return [$status, null, 0];
|
||||
}
|
||||
if (($detail['objectType'] ?? '') !== 'INDIVIDUAL') {
|
||||
throw new DomainException('认证对象与医师个人签署不一致');
|
||||
}
|
||||
$completedAt = isset($detail['endTime']) && is_int($detail['endTime']) && $detail['endTime'] > 0
|
||||
? intdiv($detail['endTime'], 1000) : (int) $flow['flow_started_at'];
|
||||
if (!$snapshot['account'] && $completedAt + self::ACCOUNT_BINDING_PROOF_LIFETIME <= time()) {
|
||||
return ['EXPIRED', null, $completedAt];
|
||||
}
|
||||
if (array_key_exists('indivInfo', $detail) && $detail['indivInfo'] === null) {
|
||||
return [$status, null, $completedAt];
|
||||
}
|
||||
$person = $detail['indivInfo'] ?? null;
|
||||
if (!is_array($person) || ($person['name'] ?? '') !== $snapshot['name']
|
||||
|| ($person['certType'] ?? '') !== 'INDIVIDUAL_CH_IDCARD' || !is_string($person['certNo'] ?? null)) {
|
||||
throw new DomainException('认证实名信息与医师账号不一致或证件类型不支持');
|
||||
}
|
||||
$idNo = strtoupper($person['certNo']);
|
||||
if (str_contains($idNo, '*') && preg_match('/^(?:[0-9*]{15}|[0-9*]{17}[0-9X*])$/D', $idNo)) {
|
||||
$idNo = null; // addPerson validates any supplemental number against the provider flow.
|
||||
} elseif (!preg_match('/^(?:[0-9]{15}|[0-9]{17}[0-9X])$/D', $idNo)) {
|
||||
throw new DomainException('认证证件号码格式无效,请重新认证');
|
||||
}
|
||||
$mobile = is_string($person['authMobileNo'] ?? null) ? $person['authMobileNo'] : null;
|
||||
return [$status, ['idNo' => $idNo, 'mobile' => $mobile], $completedAt];
|
||||
}
|
||||
|
||||
private static function pendingState(array $snapshot, string $status, bool $documentMissing): ?array
|
||||
{
|
||||
$quick = $snapshot['flow_table'] === self::QUICK_FLOW_TABLE;
|
||||
if ($status === 'INIT' || $status === 'ING') {
|
||||
$message = $quick ? '请完成快捷签人脸认证' : '请完成医师实名认证';
|
||||
return self::state('authenticating', $message, 0, $quick) + ['auth_url' => $snapshot['flow']['auth_url']];
|
||||
}
|
||||
if ($status === 'SUCCESS') {
|
||||
$needed = !$snapshot['account'] && $documentMissing;
|
||||
$message = match (true) {
|
||||
$quick => '人脸认证已通过,请确认快捷签授权',
|
||||
$needed => '认证已通过,请补充本次认证使用的身份证号码以绑定签署账号',
|
||||
default => '认证已通过,请确认完成医师电子签署认证',
|
||||
};
|
||||
return self::state('binding_required', $message, 0, $quick) + ['identity_details_required' => $needed];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static function scope(int $actor): array
|
||||
{
|
||||
if (!self::enabled()) {
|
||||
throw new DomainException('医师电子签署认证尚未启用');
|
||||
}
|
||||
return ['doctor_id' => $actor, 'environment' => (string) Config::get('esign.environment', 'sandbox'),
|
||||
'app_id' => (string) Config::get('esign.app_id', '')];
|
||||
}
|
||||
|
||||
private static function snapshot(array $scope, bool $lock = false, string $flowTable = self::IDENTITY_FLOW_TABLE): array
|
||||
{
|
||||
$actor = $scope['doctor_id'];
|
||||
$name = trim((string) Db::name('admin')->where('id', $actor)->where('disable', 0)
|
||||
->whereNull('delete_time')->lock($lock)->value('name'));
|
||||
$doctor = $actor > 0 && Db::name('admin_role')->where('admin_id', $actor)
|
||||
->where('role_id', self::DOCTOR_ROLE_ID)->lock($lock)->value('admin_id');
|
||||
if ($name === '' || (!$doctor && !(PrescriptionReviewEsignService::enabled()
|
||||
&& PrescriptionReviewEsignService::canEnrollReviewer($actor)))) {
|
||||
throw new DomainException('仅当前医师本人可使用医师电子签署认证');
|
||||
}
|
||||
return [
|
||||
'name' => PrescriptionEsignService::configuredSignerName(['doctor_name' => $name], $actor),
|
||||
'account' => Db::name('doctor_esign_account')->where($scope)->lock($lock)->find(),
|
||||
'flow' => Db::name($flowTable)->where($scope)->lock($lock)->find(),
|
||||
'flow_table' => $flowTable,
|
||||
];
|
||||
}
|
||||
|
||||
private static function hasCurrentFlow(array $snapshot): bool
|
||||
{
|
||||
$flow = $snapshot['flow'];
|
||||
return !empty($flow['flow_id']) && $flow['doctor_name'] === $snapshot['name']
|
||||
&& $flow['account_id'] === ($snapshot['account']['account_id'] ?? '')
|
||||
&& (int) $flow['flow_started_at'] + self::FLOW_LIFETIME > time();
|
||||
}
|
||||
|
||||
private static function hasLease(?array $flow): bool
|
||||
{
|
||||
return !empty($flow['operation_token']) && (int) $flow['operation_expires_at'] > time();
|
||||
}
|
||||
|
||||
private static function hasPendingQuickFlow(array $snapshot): bool
|
||||
{
|
||||
return $snapshot['account'] && self::hasCurrentFlow($snapshot)
|
||||
&& (int) $snapshot['flow']['expires_at'] === 0
|
||||
&& (int) $snapshot['flow']['flow_started_at'] + self::QUICK_LIFETIME > time();
|
||||
}
|
||||
|
||||
private static function assertUnchanged(array $scope, array $snapshot, bool $lock = false): void
|
||||
{
|
||||
if (self::snapshot($scope, $lock, $snapshot['flow_table']) !== $snapshot) {
|
||||
throw new DomainException(self::STATE_CHANGED);
|
||||
}
|
||||
}
|
||||
|
||||
private static function claim(array $scope, array $snapshot): string
|
||||
{
|
||||
$token = bin2hex(random_bytes(16));
|
||||
// Quick-sign completion may make three sequential provider requests before committing.
|
||||
$timeout = max(1, min(300, (int) Config::get('esign.timeout', 60)));
|
||||
$claim = ['operation_token' => $token, 'operation_expires_at' => time() + 3 * $timeout + 30];
|
||||
Db::transaction(static function () use ($scope, $snapshot, $claim): void {
|
||||
self::assertUnchanged($scope, $snapshot, true);
|
||||
$query = Db::name($snapshot['flow_table']);
|
||||
if ($snapshot['flow']) {
|
||||
$query->where($scope)->update($claim);
|
||||
} else {
|
||||
$query->insert($scope + $claim);
|
||||
}
|
||||
});
|
||||
return $token;
|
||||
}
|
||||
|
||||
private static function finish(array $scope, array $snapshot, string $token, ?array $nextFlow, ?string $newAccountId = null): void
|
||||
{
|
||||
Db::transaction(static function () use ($scope, $snapshot, $token, $nextFlow, $newAccountId): void {
|
||||
$current = self::snapshot($scope, true, $snapshot['flow_table']);
|
||||
if ($current['name'] !== $snapshot['name'] || $current['account'] !== $snapshot['account']
|
||||
|| !self::hasLease($current['flow']) || $current['flow']['operation_token'] !== $token) {
|
||||
throw new DomainException(self::STATE_CHANGED);
|
||||
}
|
||||
if ($newAccountId !== null) {
|
||||
$owner = Db::name('doctor_esign_account')->where('environment', $scope['environment'])
|
||||
->where('app_id', $scope['app_id'])->where('account_id', $newAccountId)->lock(true)->value('doctor_id');
|
||||
if ($owner !== null) {
|
||||
throw new DomainException('签署账号绑定冲突,请联系管理员核实');
|
||||
}
|
||||
Db::name('doctor_esign_account')->insert($scope + [
|
||||
'account_id' => $newAccountId, 'doctor_name' => $snapshot['name'], 'create_time' => time(),
|
||||
]);
|
||||
}
|
||||
$query = Db::name($snapshot['flow_table'])->where($scope)->where('operation_token', $token);
|
||||
if ($nextFlow === null) {
|
||||
$query->delete();
|
||||
} else {
|
||||
$query->update($nextFlow + ['operation_token' => '', 'operation_expires_at' => 0]);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static function release(array $scope, array $snapshot, string $token): void
|
||||
{
|
||||
Db::name($snapshot['flow_table'])->where($scope)->where('operation_token', $token)
|
||||
->update(['operation_token' => '', 'operation_expires_at' => 0]);
|
||||
}
|
||||
|
||||
private static function mobileHash(array $scope, string $mobile): string
|
||||
{
|
||||
$secret = (string) Config::get('esign.app_secret', '');
|
||||
if ($secret === '') {
|
||||
throw new DomainException('医师认证配置不完整,请联系管理员');
|
||||
}
|
||||
return hash_hmac('sha256', json_encode(['doctor-enrollment', $scope, $mobile], JSON_THROW_ON_ERROR), $secret);
|
||||
}
|
||||
|
||||
private static function validMobile(?string $mobile): bool
|
||||
{
|
||||
return $mobile !== null && preg_match('/^1[3-9][0-9]{9}$/D', $mobile) === 1;
|
||||
}
|
||||
|
||||
private static function processing(bool $quick = false): array
|
||||
{
|
||||
return self::state('authenticating', '医师认证请求处理中,请稍后查询', 0, $quick);
|
||||
}
|
||||
|
||||
private static function state(string $status, string $message, int $certExpiresAt = 0, bool $quickAuthorizing = false): array
|
||||
{
|
||||
return [
|
||||
'enabled' => true, 'status' => $status, 'cert_expires_at' => $certExpiresAt, 'message' => $message,
|
||||
'quicksign_enabled' => self::quickEnabled(), 'quicksign_expires_at' => 0, 'quicksign_authorizing' => $quickAuthorizing,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -11,9 +11,45 @@ use Throwable;
|
||||
/** Safe public errors deliberately omit provider messages, bodies and transport diagnostics. */
|
||||
class EsignProviderException extends RuntimeException
|
||||
{
|
||||
public function __construct(public string $operation, public string $providerCode)
|
||||
public const APPLICATION_ACCESS_DENIED = 'APPLICATION_ACCESS_DENIED';
|
||||
public const IP_WHITELIST_MISMATCH = 'IP_WHITELIST_MISMATCH';
|
||||
public const SIGNATURE_MISMATCH = 'SIGNATURE_MISMATCH';
|
||||
public const IDENTITY_NAME_REJECTED = 'IDENTITY_NAME_REJECTED';
|
||||
public const IDENTITY_METHOD_REJECTED = 'IDENTITY_METHOD_REJECTED';
|
||||
public const IDENTITY_DOCUMENT_REJECTED = 'IDENTITY_DOCUMENT_REJECTED';
|
||||
public const IDENTITY_QUOTA_REJECTED = 'IDENTITY_QUOTA_REJECTED';
|
||||
|
||||
/** Nullable allowlisted enum; never contains a provider message or identifier. */
|
||||
public ?string $reason;
|
||||
|
||||
public function __construct(public string $operation, public string $providerCode, ?string $reason = null)
|
||||
{
|
||||
parent::__construct('e签宝 ' . $operation . ' 失败(' . $providerCode . ')');
|
||||
$hints = [
|
||||
self::APPLICATION_ACCESS_DENIED => '该应用无权调用此接口,请管理员核查应用的接口授权',
|
||||
self::IP_WHITELIST_MISMATCH => '请求 IP 未通过白名单校验,请管理员核查出口 IP 与应用白名单',
|
||||
self::SIGNATURE_MISMATCH => '请求签名不匹配,请管理员核查签名配置',
|
||||
self::IDENTITY_NAME_REJECTED => '开方医生姓名未通过核身校验,请管理员核对账号登记的证件实名',
|
||||
self::IDENTITY_METHOD_REJECTED => '核身方式不可用,请管理员核对应用开通的认证方式',
|
||||
self::IDENTITY_DOCUMENT_REJECTED => '证件信息未通过核身校验,请核对认证设置',
|
||||
self::IDENTITY_QUOTA_REJECTED => '核身额度不足,请补充认证调试额度',
|
||||
];
|
||||
$validReason = match ($providerCode) {
|
||||
'PROVIDER_403' => in_array($reason, [self::APPLICATION_ACCESS_DENIED, self::IP_WHITELIST_MISMATCH, self::SIGNATURE_MISMATCH], true),
|
||||
'PROVIDER_30500121' => in_array($operation, ['startIdentity', 'startDoctorIdentity', 'startDoctorQuickAuthorization'], true) && in_array($reason, [self::IDENTITY_NAME_REJECTED,
|
||||
self::IDENTITY_METHOD_REJECTED, self::IDENTITY_DOCUMENT_REJECTED, self::IDENTITY_QUOTA_REJECTED], true),
|
||||
default => false,
|
||||
};
|
||||
$this->reason = $validReason ? $reason : null;
|
||||
$message = 'e签宝 ' . $operation . ' 失败(' . $providerCode . ')';
|
||||
if ($this->reason !== null) {
|
||||
$message .= ':' . $hints[$this->reason];
|
||||
} elseif ($operation === 'createPerson' && $providerCode === 'PROVIDER_403') {
|
||||
$message .= ':创建签署账号被拒绝,请管理员核查该应用的接口权限及 IP 白名单';
|
||||
} elseif ($operation === 'signPdf' && $providerCode === 'PROVIDER_10002') {
|
||||
// The signing service and local initialization reuse this numeric code for different errors.
|
||||
$message = 'e签宝签署次数不足(10002),请为当前应用补充电子签名 SDK 3.0 签署额度后重试';
|
||||
}
|
||||
parent::__construct($message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,13 +66,16 @@ class EsignOutcomeUnknownException extends EsignProviderException
|
||||
* SDK 3.x PaaS HTTP adapter. Identity uses the independent v2 identity service.
|
||||
*
|
||||
* Transport receives {method,url,headers,body,timeout} and returns
|
||||
* {status:int,body:string,errno?:int}. It must not log request bodies or credentials.
|
||||
* {status:int,body:string,errno?:int}. HTTPS requests can include a local ca_file.
|
||||
* It must not log request bodies or credentials.
|
||||
* No method retries a request. initialize() is an explicit deployment operation:
|
||||
* an initialized JVM must be restarted before changing app/environment.
|
||||
*/
|
||||
final class EsignClient
|
||||
{
|
||||
private const JSON_TYPE = 'application/json; charset=UTF-8';
|
||||
private const MAINLAND_CERT_TYPE = 'INDIVIDUAL_CH_IDCARD';
|
||||
private const WILLINGNESS_PATH = '/v2/identity/willingness/api/individual';
|
||||
private const MAX_PDF_BYTES = 20971520;
|
||||
private const ENVIRONMENTS = [
|
||||
'sandbox' => [
|
||||
@@ -91,6 +130,10 @@ final class EsignClient
|
||||
if (filter_var($timeout, FILTER_VALIDATE_INT) === false || (int) $timeout < 1 || (int) $timeout > 300) {
|
||||
throw new EsignProviderException('configuration', 'TIMEOUT_INVALID');
|
||||
}
|
||||
$caFile = $this->configuration['ca_file'] ?? '';
|
||||
if (!is_string($caFile) || ($caFile !== '' && (!stream_is_local($caFile) || !is_file($caFile) || !is_readable($caFile)))) {
|
||||
throw new EsignProviderException('configuration', 'CA_FILE_INVALID');
|
||||
}
|
||||
$url = (string) ($this->configuration['sdk_url'] ?? '');
|
||||
$parts = parse_url($url);
|
||||
if (!is_array($parts) || !isset($parts['host'])
|
||||
@@ -124,27 +167,58 @@ final class EsignClient
|
||||
/** @return array{flow_id:string,auth_url:string} */
|
||||
public function startIdentity(string $name, string $contextId, ?string $accountId = null): array
|
||||
{
|
||||
$this->requireText($name, 'startIdentity');
|
||||
$this->requireText($contextId, 'startIdentity');
|
||||
$person = ['name' => $name, 'certType' => 'INDIVIDUAL_CH_IDCARD'];
|
||||
return $this->hostedIdentity('startIdentity', ['name' => $name, 'certType' => self::MAINLAND_CERT_TYPE],
|
||||
$contextId, 'PSN_TELECOM_AUTHCODE', $accountId);
|
||||
}
|
||||
|
||||
/** @return array{flow_id:string,auth_url:string} */
|
||||
public function startDoctorIdentity(string $name, string $contextId, string $mobile, ?string $accountId = null): array
|
||||
{
|
||||
$this->requireMobile($mobile, 'startDoctorIdentity');
|
||||
// The provider binds the authorized number only after successful face authentication.
|
||||
return $this->hostedIdentity('startDoctorIdentity', [
|
||||
'name' => $name, 'certType' => self::MAINLAND_CERT_TYPE, 'authMobileNo' => $mobile,
|
||||
], $contextId, 'PSN_FACEAUTH_BYURL_ZHIMA', $accountId);
|
||||
}
|
||||
|
||||
/** @return array{flow_id:string,auth_url:string} */
|
||||
public function startDoctorQuickAuthorization(string $name, string $idNo, string $contextId, string $accountId): array
|
||||
{
|
||||
$this->requireText($idNo, 'startDoctorQuickAuthorization');
|
||||
return $this->hostedIdentity('startDoctorQuickAuthorization', [
|
||||
'name' => $name, 'certType' => self::MAINLAND_CERT_TYPE, 'certNo' => $idNo,
|
||||
], $contextId, 'PSN_FACEAUTH_BYURL_ZHIMA', $accountId, 'PUREVERIFY');
|
||||
}
|
||||
|
||||
/** @return array{flow_id:string,auth_url:string} */
|
||||
private function hostedIdentity(
|
||||
string $operation, array $person, string $contextId, string $authType, ?string $accountId, string $usageType = 'CERTAPPLY'
|
||||
): array {
|
||||
$this->requireText($person['name'], $operation);
|
||||
$this->requireText($contextId, $operation);
|
||||
if ($accountId !== null) {
|
||||
$this->requireText($accountId, 'startIdentity');
|
||||
$this->requireText($accountId, $operation);
|
||||
$person['sdkAccountId'] = $accountId;
|
||||
}
|
||||
$response = $this->identityJson('startIdentity', 'POST', '/v2/identity/auth/web/indivAuthUrl', [
|
||||
$uneditable = ['name', 'certType'];
|
||||
if (isset($person['certNo'])) {
|
||||
$uneditable[] = 'certNo';
|
||||
}
|
||||
$response = $this->identityJson($operation, 'POST', '/v2/identity/auth/web/indivAuthUrl', [
|
||||
'indivInfo' => $person,
|
||||
'configParams' => ['indivUneditableInfo' => ['name', 'certType']],
|
||||
'usageType' => $usageType,
|
||||
'authType' => $authType,
|
||||
'availableAuthTypes' => [$authType],
|
||||
'configParams' => ['indivUneditableInfo' => $uneditable],
|
||||
'contextInfo' => ['contextId' => $contextId, 'showResultPage' => true],
|
||||
]);
|
||||
$data = $response['data'] ?? null;
|
||||
if (!is_array($data) || !is_string($data['flowId'] ?? null) || trim($data['flowId']) === '') {
|
||||
throw new EsignProviderException('startIdentity', 'RESPONSE_INVALID');
|
||||
}
|
||||
$data = is_array($response['data'] ?? null) ? $response['data'] : [];
|
||||
$flowId = $this->requiredResponseText($data, 'flowId', $operation);
|
||||
$url = !empty($data['shortLink']) ? $data['shortLink'] : ($data['url'] ?? '');
|
||||
if (!is_string($url) || !$this->isTrustedAuthUrl($url)) {
|
||||
throw new EsignProviderException('startIdentity', 'AUTH_URL_INVALID');
|
||||
throw new EsignProviderException($operation, 'AUTH_URL_INVALID');
|
||||
}
|
||||
return ['flow_id' => $data['flowId'], 'auth_url' => $url];
|
||||
return ['flow_id' => $flowId, 'auth_url' => $url];
|
||||
}
|
||||
|
||||
public function identityDetail(string $flowId): array
|
||||
@@ -159,13 +233,125 @@ final class EsignClient
|
||||
|
||||
public function checkWillingness(string $flowId): void
|
||||
{
|
||||
$this->requireText($flowId, 'checkWillingness');
|
||||
$data = $this->sdkJson('checkWillingness', '/timevale/auth/queryWillingnessValidity', ['willingnessId' => $flowId]);
|
||||
if (($data['status'] ?? null) !== 1
|
||||
|| !is_int($data['remainingTimes'] ?? null) || $data['remainingTimes'] < 1
|
||||
|| !is_int($data['expireAt'] ?? null) || $data['expireAt'] <= ($this->clock)()) {
|
||||
$this->willingnessExpiresAt($flowId);
|
||||
}
|
||||
|
||||
/** Returns the provider's current expiration in Unix milliseconds. */
|
||||
public function willingnessExpiresAt(string $flowId): int
|
||||
{
|
||||
$validity = $this->willingnessValidity($flowId);
|
||||
if ($validity['state'] !== 'valid') {
|
||||
throw new EsignProviderException('checkWillingness', 'WILLINGNESS_INVALID');
|
||||
}
|
||||
return $validity['expires_at'];
|
||||
}
|
||||
|
||||
/** @return array{state:string,expires_at:int,remaining_times:int} Expiration is in Unix milliseconds. */
|
||||
public function willingnessValidity(string $flowId): array
|
||||
{
|
||||
$this->requireText($flowId, 'checkWillingness');
|
||||
$data = $this->sdkJson('checkWillingness', '/timevale/auth/queryWillingnessValidity', ['willingnessId' => $flowId]);
|
||||
$status = $data['status'] ?? null;
|
||||
$expiresAt = $data['expireAt'] ?? null;
|
||||
$remaining = $data['remainingTimes'] ?? null;
|
||||
$state = match (true) {
|
||||
!in_array($status, [0, 1], true), !is_int($expiresAt), $expiresAt <= 0 => 'invalid',
|
||||
$expiresAt <= ($this->clock)() => 'expired',
|
||||
$remaining === 0 => 'exhausted',
|
||||
$status === 1 && is_int($remaining) && $remaining > 0 => 'valid',
|
||||
default => 'invalid',
|
||||
};
|
||||
return [
|
||||
'state' => $state,
|
||||
'expires_at' => $state === 'valid' ? $expiresAt : 0,
|
||||
'remaining_times' => $state === 'valid' ? $remaining : 0,
|
||||
];
|
||||
}
|
||||
|
||||
public function authorizedMobile(string $name, string $idNo): ?string
|
||||
{
|
||||
$this->requireText($name, 'authorizedMobile');
|
||||
$this->requireText($idNo, 'authorizedMobile');
|
||||
$response = $this->identityJson('authorizedMobile', 'POST', self::WILLINGNESS_PATH . '/get-individual-info', [
|
||||
'name' => $name, 'idNo' => $idNo, 'certType' => self::MAINLAND_CERT_TYPE,
|
||||
]);
|
||||
$data = $response['data'] ?? null;
|
||||
if ($data !== null && !is_array($data)) {
|
||||
throw new EsignProviderException('authorizedMobile', 'RESPONSE_INVALID');
|
||||
}
|
||||
$mobile = $data['mobileNo'] ?? null;
|
||||
if ($mobile === null || $mobile === '') {
|
||||
return null;
|
||||
}
|
||||
if (!is_string($mobile) || !preg_match('/^1[3-9][0-9]{9}$/D', $mobile)) {
|
||||
throw new EsignProviderException('authorizedMobile', 'RESPONSE_INVALID');
|
||||
}
|
||||
return $mobile;
|
||||
}
|
||||
|
||||
public function sendWillingnessCode(string $name, string $idNo, string $mobile): string
|
||||
{
|
||||
$this->requireText($name, 'sendWillingnessCode');
|
||||
$this->requireText($idNo, 'sendWillingnessCode');
|
||||
$this->requireMobile($mobile, 'sendWillingnessCode');
|
||||
$response = $this->identityJson('sendWillingnessCode', 'POST', self::WILLINGNESS_PATH . '/send-code', [
|
||||
'mobileNo' => $mobile, 'name' => $name, 'idNo' => $idNo, 'certType' => self::MAINLAND_CERT_TYPE,
|
||||
]);
|
||||
$data = is_array($response['data'] ?? null) ? $response['data'] : [];
|
||||
return $this->requiredResponseText($data, 'flowId', 'sendWillingnessCode');
|
||||
}
|
||||
|
||||
public function verifyWillingnessCode(string $flowId, string $code): void
|
||||
{
|
||||
$this->requireText($flowId, 'verifyWillingnessCode');
|
||||
if (!preg_match('/^[0-9]{6}$/D', $code)) {
|
||||
throw new EsignProviderException('verifyWillingnessCode', 'INPUT_INVALID');
|
||||
}
|
||||
$this->identityJson('verifyWillingnessCode', 'POST',
|
||||
self::WILLINGNESS_PATH . '/' . rawurlencode($flowId) . '/verify-send-code', ['authCode' => $code]);
|
||||
}
|
||||
|
||||
/** @return array{accountId:string,name:string,idNo:string,idNoType:string,accountType:string} */
|
||||
public function signingAccount(string $accountId): array
|
||||
{
|
||||
$this->requireText($accountId, 'signingAccount');
|
||||
$data = $this->sdkJson('signingAccount', '/timevale/account/queryByAccountId', ['accountId' => $accountId]);
|
||||
$returnedId = $this->requiredResponseText($data, 'accountId', 'signingAccount');
|
||||
if ($returnedId !== $accountId) {
|
||||
throw new EsignProviderException('signingAccount', 'RESPONSE_INVALID');
|
||||
}
|
||||
return [
|
||||
'accountId' => $returnedId,
|
||||
'name' => $this->requiredResponseText($data, 'name', 'signingAccount'),
|
||||
'idNo' => $this->requiredResponseText($data, 'idNo', 'signingAccount'),
|
||||
'idNoType' => $this->requiredResponseText($data, 'idNoType', 'signingAccount'),
|
||||
'accountType' => $this->requiredResponseText($data, 'accountType', 'signingAccount'),
|
||||
];
|
||||
}
|
||||
|
||||
/** @return array{startDate:string,endDate:string} */
|
||||
public function certificateValidity(string $accountId): array
|
||||
{
|
||||
$data = $this->latestCertificate($accountId);
|
||||
return [
|
||||
'startDate' => $this->requiredResponseText($data, 'startDate', 'certificateValidity'),
|
||||
'endDate' => $this->requiredResponseText($data, 'endDate', 'certificateValidity'),
|
||||
];
|
||||
}
|
||||
|
||||
private function latestCertificate(string $accountId): array
|
||||
{
|
||||
$this->requireText($accountId, 'certificateValidity');
|
||||
return $this->sdkJson('certificateValidity', '/timevale/user/cert/queryLatestAvailableCert', ['accountId' => $accountId]);
|
||||
}
|
||||
|
||||
public function certificateIdentity(string $accountId): array
|
||||
{
|
||||
$data = $this->latestCertificate($accountId);
|
||||
return [
|
||||
'issuerCN' => $this->requiredResponseText($data, 'issuerCN', 'certificateValidity'),
|
||||
'sn' => $this->requiredResponseText($data, 'sn', 'certificateValidity'),
|
||||
];
|
||||
}
|
||||
|
||||
public function createPerson(string $name, string $idNo, string $flowId): string
|
||||
@@ -194,6 +380,16 @@ final class EsignClient
|
||||
|
||||
/** @return array{sign_service_id:string,pdf:string} */
|
||||
public function signPdf(string $accountId, string $flowId, string $sealData, string $pdfBytes, string $fileName): array
|
||||
{
|
||||
return $this->signAt($accountId, $flowId, $sealData, $pdfBytes, $fileName, 520, 108);
|
||||
}
|
||||
|
||||
public function signReviewPdf(string $accountId, string $flowId, string $sealData, string $pdfBytes, string $fileName): array
|
||||
{
|
||||
return $this->signAt($accountId, $flowId, $sealData, $pdfBytes, $fileName, 520, 63);
|
||||
}
|
||||
|
||||
private function signAt(string $accountId, string $flowId, string $sealData, string $pdfBytes, string $fileName, int $x, int $y): array
|
||||
{
|
||||
foreach ([$accountId, $flowId, $sealData, $fileName] as $value) {
|
||||
$this->requireText($value, 'signPdf');
|
||||
@@ -205,7 +401,7 @@ final class EsignClient
|
||||
$data = $this->sdkMultipart('signPdf', '/timevale/user/sign/personSign', 'personSignParam', [
|
||||
'accountId' => $accountId, 'willingnessId' => $flowId, 'sealData' => $sealData,
|
||||
'signType' => 'Single', 'fileBean' => ['fileName' => $fileName],
|
||||
'posBeans' => [['posPage' => '1', 'posX' => 420, 'posY' => 70, 'width' => 100]],
|
||||
'posBeans' => [['posPage' => '1', 'posX' => $x, 'posY' => $y, 'width' => 48]],
|
||||
], $pdfBytes, true);
|
||||
$serviceId = is_string($data['signServiceId'] ?? null) && trim($data['signServiceId']) !== '' ? $data['signServiceId'] : null;
|
||||
$pdf = is_string($data['stream'] ?? null) ? base64_decode($data['stream'], true) : false;
|
||||
@@ -274,10 +470,15 @@ final class EsignClient
|
||||
private function request(string $operation, string $method, string $url, array $headers, string $body, string $codeKey, bool $signing = false): array
|
||||
{
|
||||
try {
|
||||
$response = ($this->transport)([
|
||||
$request = [
|
||||
'method' => $method, 'url' => $url, 'headers' => $headers, 'body' => $body,
|
||||
'timeout' => (int) ($this->configuration['timeout'] ?? 60),
|
||||
]);
|
||||
];
|
||||
$caFile = $this->configuration['ca_file'] ?? '';
|
||||
if ($caFile !== '' && str_starts_with($url, 'https://')) {
|
||||
$request['ca_file'] = $caFile;
|
||||
}
|
||||
$response = ($this->transport)($request);
|
||||
} catch (Throwable $exception) {
|
||||
// Never attach the original exception: its URL/body may contain identity or secret data.
|
||||
$this->fail($operation, 'TRANSPORT_ERROR', $signing);
|
||||
@@ -302,11 +503,56 @@ final class EsignClient
|
||||
$this->fail($operation, 'RESPONSE_INVALID', $signing);
|
||||
}
|
||||
if ($data[$codeKey] !== 0) {
|
||||
throw new EsignProviderException($operation, 'PROVIDER_' . $data[$codeKey]);
|
||||
$reason = match (true) {
|
||||
$data[$codeKey] === 403 => $this->forbiddenReason($data),
|
||||
in_array($operation, ['startIdentity', 'startDoctorIdentity', 'startDoctorQuickAuthorization'], true) && $data[$codeKey] === 30500121
|
||||
=> $this->identityStartReason($data['message'] ?? $data['msg'] ?? null),
|
||||
default => null,
|
||||
};
|
||||
throw new EsignProviderException($operation, 'PROVIDER_' . $data[$codeKey],
|
||||
$reason);
|
||||
}
|
||||
return $data;
|
||||
}
|
||||
|
||||
private function forbiddenReason(array $data): ?string
|
||||
{
|
||||
$message = $data['msg'] ?? null;
|
||||
if (!is_string($message)) {
|
||||
return null;
|
||||
}
|
||||
// Translate recognized phrases to fixed codes; do not retain or echo vendor text.
|
||||
if (str_contains($message, '该应用无权调用此接口')) {
|
||||
return EsignProviderException::APPLICATION_ACCESS_DENIED;
|
||||
}
|
||||
foreach (['IP不在白名单', 'IP地址不在白名单', 'IP 不在白名单', 'IP 地址不在白名单',
|
||||
'IP白名单不匹配', 'IP 白名单不匹配', 'IP白名单校验失败', 'IP 白名单校验失败'] as $phrase) {
|
||||
if (str_contains($message, $phrase)) {
|
||||
return EsignProviderException::IP_WHITELIST_MISMATCH;
|
||||
}
|
||||
}
|
||||
if (preg_match('/(?<![A-Za-z0-9_])SignatureDoesNotMatch(?![A-Za-z0-9_])/', $message) === 1) {
|
||||
return EsignProviderException::SIGNATURE_MISMATCH;
|
||||
}
|
||||
// FORBIDDEN alone does not distinguish application permissions from an IP rejection.
|
||||
return null;
|
||||
}
|
||||
|
||||
private function identityStartReason(mixed $message): ?string
|
||||
{
|
||||
if (!is_string($message)) {
|
||||
return null;
|
||||
}
|
||||
// Translate provider detail into fixed hints. Do not return identity data from the supplier.
|
||||
return match (true) {
|
||||
str_contains($message, '姓名') => EsignProviderException::IDENTITY_NAME_REJECTED,
|
||||
str_contains($message, '余额不足') || str_contains($message, '次数不足') => EsignProviderException::IDENTITY_QUOTA_REJECTED,
|
||||
str_contains($message, '认证方式') => EsignProviderException::IDENTITY_METHOD_REJECTED,
|
||||
str_contains($message, '证件') || str_contains($message, '身份证') => EsignProviderException::IDENTITY_DOCUMENT_REJECTED,
|
||||
default => null,
|
||||
};
|
||||
}
|
||||
|
||||
private function fail(string $operation, string $code, bool $signing): void
|
||||
{
|
||||
if ($signing) {
|
||||
@@ -331,6 +577,13 @@ final class EsignClient
|
||||
}
|
||||
}
|
||||
|
||||
private function requireMobile(string $mobile, string $operation): void
|
||||
{
|
||||
if (!preg_match('/^1[3-9][0-9]{9}$/D', $mobile)) {
|
||||
throw new EsignProviderException($operation, 'INPUT_INVALID');
|
||||
}
|
||||
}
|
||||
|
||||
private function requirePdf(string $bytes, string $operation): void
|
||||
{
|
||||
if (!str_starts_with($bytes, '%PDF-') || strlen($bytes) > self::MAX_PDF_BYTES) {
|
||||
@@ -398,6 +651,9 @@ final class EsignClient
|
||||
return strlen($chunk);
|
||||
},
|
||||
]);
|
||||
if (isset($request['ca_file'])) {
|
||||
curl_setopt($handle, CURLOPT_CAINFO, $request['ca_file']);
|
||||
}
|
||||
if ($request['method'] !== 'GET') {
|
||||
curl_setopt($handle, CURLOPT_POSTFIELDS, $request['body']);
|
||||
}
|
||||
|
||||
@@ -99,5 +99,10 @@ final class PrescriptionEsignPolicy
|
||||
if ($forDispensing && ($evidence['environment'] ?? '') !== 'production') {
|
||||
throw new DomainException('沙箱签署处方仅供测试,不能用于正式发药');
|
||||
}
|
||||
$issuedAt = (int) ($evidence['issued_at'] ?? 0);
|
||||
if ($issuedAt > 0 && (($evidence['signature_time_source'] ?? '') !== 'tsa'
|
||||
|| (int) ($evidence['signature_time'] ?? 0) < $issuedAt)) {
|
||||
throw new DomainException('处方开具和签署时间的验签证据不完整');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -6,7 +6,7 @@ namespace app\common\service\esign;
|
||||
/** Deterministic, text based A4 prescription; fixed first-page signature area. */
|
||||
final class PrescriptionPdf
|
||||
{
|
||||
public static function render(array $row, string $environment): string
|
||||
public static function render(array $row, string $environment, int $issuedAt = 0, bool $review = false): string
|
||||
{
|
||||
$row = PrescriptionEsignPolicy::snapshot($row);
|
||||
$lines = [];
|
||||
@@ -32,6 +32,10 @@ final class PrescriptionPdf
|
||||
};
|
||||
$add('处方编号', $row['sn']);
|
||||
$add('日期', $row['prescription_date']);
|
||||
if ($issuedAt > 0) {
|
||||
$time = (new \DateTimeImmutable('@' . $issuedAt))->setTimezone(new \DateTimeZone('Asia/Shanghai'));
|
||||
$add('开具确认时间(北京时间)', $time->format('Y-m-d H:i:s'));
|
||||
}
|
||||
$add('患者', $row['patient_name'] . ' 性别:' . ($row['gender'] === '1' ? '男' : '女') . ' 年龄:' . $row['age']);
|
||||
$add('联系电话', $row['phone']);
|
||||
$add('门诊号', $row['visit_no']);
|
||||
@@ -93,7 +97,10 @@ final class PrescriptionPdf
|
||||
$stream .= "0.7 w 45 133 m 550 133 l S\n";
|
||||
$stream .= self::text('开方医师:' . $row['doctor_name'], 45, 110, 12);
|
||||
if ($index === 0) {
|
||||
$stream .= self::text('医师电子签章', 420, 117, 11);
|
||||
$stream .= self::text('医师电子签章', 420, 104, 11);
|
||||
if ($review) {
|
||||
$stream .= self::text('审核电子签章', 420, 59, 11);
|
||||
}
|
||||
}
|
||||
$stream .= self::text('处方快照 SHA-256', 45, 58, 8);
|
||||
$stream .= self::text(PrescriptionEsignPolicy::hash($row), 45, 44, 7);
|
||||
|
||||
@@ -0,0 +1,342 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\common\service\esign;
|
||||
|
||||
use app\adminapi\logic\auth\AuthLogic;
|
||||
use app\adminapi\logic\tcm\PrescriptionLogic;
|
||||
use app\adminapi\logic\tcm\PrescriptionOrderLogic;
|
||||
use app\common\model\tcm\PrescriptionOrder;
|
||||
use DomainException;
|
||||
use think\facade\Config;
|
||||
use think\facade\Db;
|
||||
|
||||
final class PrescriptionReviewEsignService
|
||||
{
|
||||
public const ORDER_PERMISSION = 'tcm.prescriptionOrder/auditPrescription';
|
||||
private const TABLE = 'prescription_review_esign';
|
||||
private const VERIFY_LEASE_SECONDS = 360;
|
||||
|
||||
public static function enabled(): bool
|
||||
{
|
||||
return filter_var(Config::get('esign.review_enabled', false), FILTER_VALIDATE_BOOLEAN);
|
||||
}
|
||||
|
||||
/** Recheck the live personnel record and grants, including for an existing binding. */
|
||||
public static function reviewerAccess(int $actor): array
|
||||
{
|
||||
$admin = Db::name('admin')->where('id', $actor)->where('disable', 0)->whereNull('delete_time')
|
||||
->field('id,name,root')->find();
|
||||
if (!$admin) {
|
||||
return [];
|
||||
}
|
||||
$admin['admin_id'] = $actor;
|
||||
$admin['role_id'] = Db::name('admin_role')->where('admin_id', $actor)->column('role_id');
|
||||
$admin['permissions'] = (int) $admin['root'] === 1 ? ['*'] : AuthLogic::getAuthByAdminId($actor);
|
||||
if (!PrescriptionLogic::canAuditPrescription($actor, $admin)) {
|
||||
return [];
|
||||
}
|
||||
return $admin;
|
||||
}
|
||||
|
||||
public static function canEnrollReviewer(int $actor): bool
|
||||
{
|
||||
$admin = self::reviewerAccess($actor);
|
||||
return $admin && self::hasGrant($admin, array_merge(PrescriptionLogic::AUDIT_PERMISSIONS, [self::ORDER_PERMISSION]));
|
||||
}
|
||||
|
||||
private static function hasGrant(array $admin, array $grants): bool
|
||||
{
|
||||
return (int) ($admin['root'] ?? 0) === 1 || array_intersect($admin['permissions'] ?? [], $grants) !== [];
|
||||
}
|
||||
|
||||
private static function review(int $id): ?array
|
||||
{
|
||||
return Db::name(self::TABLE)->where('prescription_id', $id)->find() ?: null;
|
||||
}
|
||||
|
||||
private static function path(array $doctor): string
|
||||
{
|
||||
return $doctor['prescription_id'] . '-' . $doctor['snapshot_hash'] . '/review-signed.pdf';
|
||||
}
|
||||
|
||||
/** Called under the same prescription lock as approval or dispatch. */
|
||||
public static function assertVerified(array $row, array $doctor, ?int $actor): void
|
||||
{
|
||||
// Previously approved single-signature records retain their archived evidence.
|
||||
if (empty($doctor['review_required']) && !($actor !== null && self::enabled())) {
|
||||
return;
|
||||
}
|
||||
$review = self::review((int) $row['id']);
|
||||
if (!self::hasVerifiedReview($doctor, $review)) {
|
||||
throw new DomainException('请由另一位有审核权限的人员完成处方审核电子签署');
|
||||
}
|
||||
if ($actor !== null && ($actor !== (int) $review['reviewer_id'] || !self::canEnrollReviewer($actor))) {
|
||||
throw new DomainException('请由已签署此处方且仍有审核权限的审核人本人提交审核');
|
||||
}
|
||||
PrescriptionEsignService::readPdf(self::path($doctor), $review['signed_hash']);
|
||||
}
|
||||
|
||||
private static function hasVerifiedReview(array $doctor, ?array $review): bool
|
||||
{
|
||||
return $review && $review['state'] === 'signed' && (int) $review['reviewer_id'] > 0
|
||||
&& (int) $review['reviewer_id'] !== (int) $doctor['doctor_id']
|
||||
&& $review['account_id'] !== '' && $review['account_id'] !== $doctor['account_id']
|
||||
&& $review['environment'] === $doctor['environment'] && $review['app_id'] === $doctor['app_id']
|
||||
&& hash_equals($doctor['signed_hash'], $review['doctor_pdf_hash'])
|
||||
&& $review['sign_service_id'] !== '' && $review['signed_hash'] !== ''
|
||||
&& (int) $review['signature_time'] > 0
|
||||
&& (int) $review['signature_time'] >= (int) $doctor['signature_time'];
|
||||
}
|
||||
|
||||
public static function describe(?array $doctor): array
|
||||
{
|
||||
if (empty($doctor['review_required']) || !($review = self::review((int) $doctor['prescription_id']))
|
||||
|| !self::hasVerifiedReview($doctor, $review)) {
|
||||
return [];
|
||||
}
|
||||
return ['review_signer_name' => $review['signer_name'], 'review_signature_time' => (int) $review['signature_time']];
|
||||
}
|
||||
|
||||
public static function download(array $doctor): ?array
|
||||
{
|
||||
if (empty($doctor['review_required'])) {
|
||||
return null;
|
||||
}
|
||||
$review = self::review((int) $doctor['prescription_id']);
|
||||
if (!self::hasVerifiedReview($doctor, $review)) {
|
||||
return null;
|
||||
}
|
||||
$pdf = PrescriptionEsignService::readPdf(self::path($doctor), $review['signed_hash']);
|
||||
return ['filename' => 'prescription-' . $doctor['prescription_id'] . '-dual-signed.pdf',
|
||||
'sha256' => $review['signed_hash'], 'content_base64' => base64_encode($pdf)];
|
||||
}
|
||||
|
||||
public static function status(int $id, int $orderId, int $actor, array $adminInfo): array
|
||||
{
|
||||
$context = self::context($id, $orderId, $actor, $adminInfo);
|
||||
return self::describeContext($context, $actor);
|
||||
}
|
||||
|
||||
private static function context(int $id, int $orderId, int $actor, array $adminInfo, bool $lock = false): array
|
||||
{
|
||||
$order = $orderId > 0 ? PrescriptionOrder::where('id', $orderId)->whereNull('delete_time')->lock($lock)->find() : null;
|
||||
if ($orderId > 0 && (!$order || (int) $order->prescription_id !== $id
|
||||
|| !PrescriptionOrderLogic::canAccessOrder($order, $actor, $adminInfo))) {
|
||||
throw new DomainException('业务订单不存在或无权查看');
|
||||
}
|
||||
$row = Db::name('tcm_prescription')->where('id', $id)->whereNull('delete_time')->lock($lock)->find();
|
||||
if (!$row || (!$order && !PrescriptionLogic::canViewPrescription($row, $actor, $adminInfo))) {
|
||||
throw new DomainException('处方不存在或无权查看');
|
||||
}
|
||||
$doctor = empty($row['esign_required']) ? null : Db::name('prescription_esign')->where('prescription_id', $id)->find();
|
||||
$required = !empty($row['esign_required']) && (self::enabled() || !empty($doctor['review_required']));
|
||||
$review = $required && !empty($doctor['review_required']) ? self::review($id) : null;
|
||||
$pending = empty($row['void_status']) && ($order
|
||||
? (int) $order->prescription_audit_status === 0 && !in_array((int) $order->fulfillment_status, [3, 4], true)
|
||||
: (int) $row['audit_status'] === 0);
|
||||
$reviewer = $required && $pending ? self::reviewerAccess($actor) : [];
|
||||
$grants = $order ? [self::ORDER_PERMISSION] : PrescriptionLogic::AUDIT_PERMISSIONS;
|
||||
return ['row' => $row, 'doctor' => $doctor, 'review' => $review, 'required' => $required,
|
||||
'can_audit' => $pending && $reviewer && self::hasGrant($reviewer, $grants),
|
||||
'reviewer' => $reviewer];
|
||||
}
|
||||
|
||||
private static function describeContext(array $context, int $actor): array
|
||||
{
|
||||
['row' => $row, 'doctor' => $doctor, 'review' => $review, 'required' => $required, 'can_audit' => $canAudit,
|
||||
'reviewer' => $reviewer] = $context;
|
||||
$differentPerson = $actor !== (int) $row['creator_id'];
|
||||
$signed = $doctor && self::hasVerifiedReview($doctor, $review);
|
||||
$own = (int) ($review['reviewer_id'] ?? 0) === $actor;
|
||||
$active = $doctor && PrescriptionEsignService::matchesEnvironment($doctor);
|
||||
$state = (string) ($review['state'] ?? 'pending');
|
||||
$canWork = $canAudit && $differentPerson && $active && self::enabled()
|
||||
&& DoctorEsignIdentityService::quickEnabled() && ($row['esign_status'] ?? '') === 'signed';
|
||||
$account = $canWork ? PrescriptionEsignService::account($actor) : null;
|
||||
$stale = time() - (int) ($review['update_time'] ?? 0) >= self::VERIFY_LEASE_SECONDS;
|
||||
$canRetry = $canAudit && $own && $active && PrescriptionEsignService::enabled() && !empty($review['signed_hash'])
|
||||
&& ($state === 'uncertain' || (in_array($state, ['signing', 'verifying'], true) && $stale));
|
||||
$message = match (true) {
|
||||
!$required => '',
|
||||
$signed => $own ? '审核签章已验签,可以提交通过。' : '请由已签署此处方的审核人本人提交审核。',
|
||||
!$differentPerson => '请切换到另一位有权限的审核人账号。',
|
||||
!$canAudit => '当前账号或处方状态不允许审核签署。',
|
||||
($row['esign_status'] ?? '') !== 'signed' => '请开方医生先完成电子签署。',
|
||||
$state === 'uncertain' => (string) $review['error_message'],
|
||||
in_array($state, ['signing', 'verifying'], true) && !$stale => '正在处理审核签署,请稍后刷新。',
|
||||
in_array($state, ['signing', 'verifying'], true) => '审核签署结果待核实,请查询状态或重试验签。',
|
||||
!$canWork => '当前签署环境或快捷签配置不可用。',
|
||||
!$account => '请先完成审核人本人的实名和快捷签授权。',
|
||||
default => (string) (($review['error_message'] ?? '') ?: '核对处方后,请审核人本人确认追加签章。'),
|
||||
};
|
||||
return [
|
||||
'required' => $required, 'state' => $signed ? 'signed' : $state,
|
||||
'can_confirm' => $canWork && $account !== null && !$signed && in_array($state, ['pending', 'failed'], true),
|
||||
'can_retry_verify' => $canRetry, 'can_approve' => !$required || ($signed && $own && $canAudit),
|
||||
'can_setup' => $canWork,
|
||||
'actor_id' => $actor, 'actor_name' => (string) ($account['doctor_name'] ?? $reviewer['name'] ?? ''),
|
||||
'signer_name' => $signed ? $review['signer_name'] : '',
|
||||
'signature_time' => $signed ? (int) $review['signature_time'] : 0,
|
||||
'message' => $message,
|
||||
];
|
||||
}
|
||||
|
||||
public static function confirm(int $id, int $orderId, int $actor, array $adminInfo, bool $verifyOnly): array
|
||||
{
|
||||
$client = new EsignClient();
|
||||
$context = self::context($id, $orderId, $actor, $adminInfo);
|
||||
$status = self::describeContext($context, $actor);
|
||||
$doctor = $context['doctor'];
|
||||
if ($status['required'] && $status['can_approve']) {
|
||||
return $status;
|
||||
}
|
||||
if (!($verifyOnly ? $status['can_retry_verify'] : $status['can_confirm'])) {
|
||||
throw new DomainException($status['message'] ?: '当前处方无需审核签署');
|
||||
}
|
||||
PrescriptionEsignPolicy::assertSigned($context['row'], $doctor);
|
||||
$source = PrescriptionEsignService::readPdf($doctor['signed_path'], $doctor['signed_hash']);
|
||||
$token = bin2hex(random_bytes(16));
|
||||
if ($verifyOnly) {
|
||||
$newProof = [];
|
||||
} else {
|
||||
$account = PrescriptionEsignService::account($actor);
|
||||
if (!$account || $account['account_id'] === $doctor['account_id']) {
|
||||
throw new DomainException('审核人必须使用自己的签署账号,并与开方医生不同');
|
||||
}
|
||||
$name = (string) $account['doctor_name'];
|
||||
$accountId = (string) $account['account_id'];
|
||||
$doctorName = ($doctor['signer_name'] ?? '') ?: (string) $context['row']['doctor_name'];
|
||||
$before = self::doctorSignature($client->verifyPdf($source), $doctorName, (int) $doctor['signature_time']);
|
||||
$certificate = self::certificateKey($client->certificateIdentity($accountId));
|
||||
if ($certificate === $before['certificate']) {
|
||||
throw new DomainException('审核证书必须与开方医生的证书不同');
|
||||
}
|
||||
$seal = $client->createSeal($accountId);
|
||||
// Verify consent and certificate validity immediately before taking the signing lease.
|
||||
$flow = DoctorEsignIdentityService::quickAuthorization($actor, $name, $accountId);
|
||||
$newProof = [
|
||||
'reviewer_id' => $actor, 'signer_name' => $name, 'account_id' => $accountId,
|
||||
'environment' => $doctor['environment'], 'app_id' => $doctor['app_id'],
|
||||
'reviewer_certificate' => $certificate, 'doctor_signature' => $before['key'],
|
||||
'doctor_pdf_hash' => $doctor['signed_hash'], 'confirmed_at' => time(),
|
||||
'signed_hash' => '', 'signature_time' => 0, 'sign_service_id' => '',
|
||||
];
|
||||
}
|
||||
$work = Db::transaction(static function () use ($id, $orderId, $actor, $adminInfo, $verifyOnly, $doctor, $newProof, $token): array {
|
||||
$current = self::context($id, $orderId, $actor, $adminInfo, true);
|
||||
$checked = self::describeContext($current, $actor);
|
||||
if (!($verifyOnly ? $checked['can_retry_verify'] : $checked['can_confirm'])
|
||||
|| $current['doctor']['signed_hash'] !== $doctor['signed_hash']) {
|
||||
throw new DomainException('处方或审核签署状态已变化,请刷新');
|
||||
}
|
||||
PrescriptionEsignPolicy::assertSigned($current['row'], $current['doctor']);
|
||||
if (!$verifyOnly && (PrescriptionEsignService::account($actor)['account_id'] ?? '') !== $newProof['account_id']) {
|
||||
throw new DomainException('审核签署账号已变化,请重新确认');
|
||||
}
|
||||
$data = $newProof + ['state' => $verifyOnly ? 'verifying' : 'signing', 'operation_token' => $token,
|
||||
'update_time' => time(), 'error_message' => ''];
|
||||
if ($current['review']) {
|
||||
Db::name(self::TABLE)->where('prescription_id', $id)->update($data);
|
||||
} else {
|
||||
Db::name(self::TABLE)->insert($data + ['prescription_id' => $id]);
|
||||
}
|
||||
if (empty($current['doctor']['review_required'])) {
|
||||
Db::name('prescription_esign')->where('prescription_id', $id)->update(['review_required' => 1]);
|
||||
}
|
||||
return $data + ($current['review'] ?? []);
|
||||
});
|
||||
|
||||
$received = $verifyOnly;
|
||||
try {
|
||||
if ($verifyOnly) {
|
||||
$dual = PrescriptionEsignService::readPdf(self::path($doctor), $work['signed_hash']);
|
||||
} else {
|
||||
$signed = $client->signReviewPdf($accountId, $flow, $seal, $source, 'prescription-' . $id . '.pdf');
|
||||
$received = true;
|
||||
self::save($id, $token, ['sign_service_id' => $signed['sign_service_id']]);
|
||||
$dual = $signed['pdf'];
|
||||
PrescriptionEsignService::writePdf(self::path($doctor), $dual);
|
||||
self::save($id, $token, ['signed_hash' => hash('sha256', $dual), 'state' => 'verifying']);
|
||||
}
|
||||
$time = self::verifyReview($source, $dual, $client->verifyPdf($dual), $doctor, $work);
|
||||
self::save($id, $token, ['state' => 'signed', 'signature_time' => $time, 'error_message' => '']);
|
||||
} catch (\Throwable $error) {
|
||||
$definiteRejection = !$received && $error instanceof EsignProviderException && !($error instanceof EsignOutcomeUnknownException);
|
||||
$details = $definiteRejection || $error instanceof DomainException ? $error->getMessage()
|
||||
: '审核签署结果待核实,请刷新状态或重试验签';
|
||||
$fields = ['state' => $definiteRejection ? 'failed' : 'uncertain', 'error_message' => mb_substr($details, 0, 240)];
|
||||
if ($error instanceof EsignOutcomeUnknownException && $error->signServiceId !== null) {
|
||||
$fields['sign_service_id'] = $error->signServiceId;
|
||||
}
|
||||
self::save($id, $token, $fields);
|
||||
}
|
||||
return self::status($id, $orderId, $actor, $adminInfo);
|
||||
}
|
||||
|
||||
private static function save(int $id, string $token, array $fields): void
|
||||
{
|
||||
// One lease protects any provider request. Only verification can resume an archived result.
|
||||
Db::name(self::TABLE)->where('prescription_id', $id)->where('operation_token', $token)
|
||||
->update($fields + ['update_time' => time()]);
|
||||
}
|
||||
|
||||
private static function certificateKey(array $cert): string
|
||||
{
|
||||
$issuer = trim((string) ($cert['issuerCN'] ?? ''));
|
||||
$serial = ltrim(strtolower(trim((string) ($cert['sn'] ?? ''))), '0');
|
||||
if ($issuer === '' || !preg_match('/^[a-f0-9]+$/D', $serial)) {
|
||||
throw new DomainException('e签宝未返回可核对的签署证书信息');
|
||||
}
|
||||
return hash('sha256', $issuer . "\0" . $serial);
|
||||
}
|
||||
|
||||
private static function signature(array $entry): array
|
||||
{
|
||||
$signature = $entry['signature'] ?? [];
|
||||
$cert = $entry['cert'] ?? [];
|
||||
$field = (string) ($signature['signatureName'] ?? '');
|
||||
$timing = PrescriptionEsignService::verifiedSigningTime($signature);
|
||||
if (($signature['validate'] ?? null) !== true || $field === '' || ($timing['signature_time_source'] ?? '') !== 'tsa') {
|
||||
throw new DomainException('原件签章或可信时间戳未通过核验');
|
||||
}
|
||||
$name = (string) ($cert['cn'] ?? '');
|
||||
$time = $timing['signature_time'];
|
||||
$certificate = self::certificateKey($cert);
|
||||
$key = hash('sha256', json_encode([$field, $certificate, $name, $time], JSON_THROW_ON_ERROR));
|
||||
return compact('field', 'name', 'time', 'certificate', 'key');
|
||||
}
|
||||
|
||||
private static function doctorSignature(array $verified, string $doctorName, int $recordedTime): array
|
||||
{
|
||||
$entries = $verified['signatures'] ?? [];
|
||||
if (count($entries) !== 1 || $doctorName === '') {
|
||||
throw new DomainException('开方原件须有且仅有一枚医生签章');
|
||||
}
|
||||
$signature = self::signature($entries[0]);
|
||||
if ($signature['name'] !== $doctorName || ($recordedTime > 0 && $signature['time'] !== $recordedTime)) {
|
||||
throw new DomainException('医生签章与归档签署记录不一致');
|
||||
}
|
||||
return $signature;
|
||||
}
|
||||
|
||||
public static function verifyReview(string $source, string $dual, array $verified, array $doctor, array $proof): int
|
||||
{
|
||||
if (strlen($dual) <= strlen($source) || !str_starts_with($dual, $source)) {
|
||||
throw new DomainException('双签原件未保留医生已签的原始文档,请联系管理员');
|
||||
}
|
||||
$entries = $verified['signatures'] ?? [];
|
||||
if (count($entries) !== 2) {
|
||||
throw new DomainException('双签原件须包含两枚有效签章');
|
||||
}
|
||||
[$first, $second] = array_map([self::class, 'signature'], $entries);
|
||||
[$original, $review] = $first['key'] === $proof['doctor_signature'] ? [$first, $second] : [$second, $first];
|
||||
if ($original['key'] !== $proof['doctor_signature'] || $original['field'] === $review['field']
|
||||
|| $original['certificate'] === $review['certificate']
|
||||
|| $review['certificate'] !== $proof['reviewer_certificate'] || $review['name'] !== $proof['signer_name']
|
||||
|| $review['time'] < max((int) $doctor['issued_at'], $original['time'])) {
|
||||
throw new DomainException('医生与审核人签章、证书或时间顺序未通过核验');
|
||||
}
|
||||
return $review['time'];
|
||||
}
|
||||
}
|
||||
@@ -75,7 +75,7 @@ final class LockedPharmacySnapshotMutation
|
||||
foreach ($orders as $order) {
|
||||
$claim = Db::name('pharmacy_submission_claim')
|
||||
->where('prescription_order_id', (int) $order['id'])
|
||||
->where('source_revision', 1)
|
||||
->order('source_revision', 'desc')
|
||||
->lock(true)
|
||||
->find();
|
||||
PharmacyRemoteSnapshotPolicy::assertMutable($order, $claim ?: null);
|
||||
|
||||
@@ -5,10 +5,16 @@ declare(strict_types=1);
|
||||
// Secrets remain server-side. Identity/API initialization hosts are fixed by environment in EsignClient.
|
||||
return [
|
||||
'enabled' => env('esign.enabled', false),
|
||||
'doctor_sms_enabled' => env('esign.doctor_sms_enabled', false),
|
||||
'doctor_quicksign_enabled' => env('esign.doctor_quicksign_enabled', false),
|
||||
'review_enabled' => env('esign.review_enabled', false),
|
||||
'environment' => env('esign.environment', 'sandbox'),
|
||||
'app_id' => env('esign.app_id', ''),
|
||||
'app_secret' => env('esign.app_secret', ''),
|
||||
'sdk_url' => env('esign.sdk_url', 'http://127.0.0.1:8091/paas-sdk-service'),
|
||||
'ca_file' => env('esign.ca_file', ''),
|
||||
'sandbox_signer_names' => env('esign.sandbox_signer_names', ''),
|
||||
'sdk_timezone' => env('esign.sdk_timezone', 'Asia/Shanghai'),
|
||||
'timeout' => env('esign.timeout', 60),
|
||||
'storage_path' => env('esign.storage_path', dirname(__DIR__) . '/storage/esign'),
|
||||
];
|
||||
|
||||
@@ -8,6 +8,7 @@ DEALLOCATE PREPARE stmt;
|
||||
CREATE TABLE IF NOT EXISTS `zyt_prescription_esign` (
|
||||
`prescription_id` int unsigned NOT NULL,
|
||||
`doctor_id` int unsigned NOT NULL,
|
||||
`signer_name` varchar(100) NOT NULL DEFAULT '',
|
||||
`environment` varchar(16) NOT NULL,
|
||||
`app_id` varchar(64) NOT NULL,
|
||||
`snapshot_hash` char(64) NOT NULL,
|
||||
@@ -17,18 +18,57 @@ CREATE TABLE IF NOT EXISTS `zyt_prescription_esign` (
|
||||
`signed_hash` char(64) NOT NULL DEFAULT '',
|
||||
`flow_id` varchar(128) NOT NULL DEFAULT '',
|
||||
`auth_url` text,
|
||||
`auth_method` varchar(8) NOT NULL DEFAULT '',
|
||||
`sms_sent_at` int unsigned NOT NULL DEFAULT 0,
|
||||
`sms_verified_at` int unsigned NOT NULL DEFAULT 0,
|
||||
`sms_attempts` tinyint unsigned NOT NULL DEFAULT 0,
|
||||
`doctor_setup_required` tinyint unsigned NOT NULL DEFAULT 0,
|
||||
`account_id` varchar(128) NOT NULL DEFAULT '',
|
||||
`sign_service_id` varchar(128) NOT NULL DEFAULT '',
|
||||
`operation_token` char(32) NOT NULL DEFAULT '',
|
||||
`error_message` varchar(255) NOT NULL DEFAULT '',
|
||||
`started_at` int unsigned NOT NULL DEFAULT 0,
|
||||
`issued_at` bigint unsigned NOT NULL DEFAULT 0,
|
||||
`signed_at` int unsigned NOT NULL DEFAULT 0,
|
||||
`signature_time` bigint unsigned NOT NULL DEFAULT 0,
|
||||
`signature_time_source` varchar(16) NOT NULL DEFAULT '',
|
||||
`create_time` int unsigned NOT NULL,
|
||||
`update_time` int unsigned NOT NULL,
|
||||
PRIMARY KEY (`prescription_id`),
|
||||
UNIQUE KEY `uk_flow` (`environment`,`app_id`,`flow_id`,`prescription_id`)
|
||||
UNIQUE KEY `uk_flow` (`environment`,`app_id`,`flow_id`,`prescription_id`),
|
||||
KEY `idx_esign_doctor_sms` (`doctor_id`,`environment`,`app_id`,`sms_sent_at`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='冻结处方原文及签署证据,文件保存于私有存储';
|
||||
|
||||
SET @exists_column = (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='zyt_prescription_esign' AND COLUMN_NAME='signer_name');
|
||||
SET @ddl = IF(@exists_column=0, 'ALTER TABLE zyt_prescription_esign ADD signer_name varchar(100) NOT NULL DEFAULT ''''', 'SELECT 1');
|
||||
PREPARE stmt FROM @ddl;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
SET @exists_column = (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='zyt_prescription_esign' AND COLUMN_NAME='signature_time');
|
||||
SET @ddl = IF(@exists_column=0, 'ALTER TABLE zyt_prescription_esign ADD signature_time bigint unsigned NOT NULL DEFAULT 0', 'SELECT 1');
|
||||
PREPARE stmt FROM @ddl;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
SET @exists_column = (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='zyt_prescription_esign' AND COLUMN_NAME='signature_time_source');
|
||||
SET @ddl = IF(@exists_column=0, 'ALTER TABLE zyt_prescription_esign ADD signature_time_source varchar(16) NOT NULL DEFAULT ''''', 'SELECT 1');
|
||||
PREPARE stmt FROM @ddl;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
SET @exists_column = (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='zyt_prescription_esign' AND COLUMN_NAME='issued_at');
|
||||
SET @ddl = IF(@exists_column=0, 'ALTER TABLE zyt_prescription_esign ADD issued_at bigint unsigned NOT NULL DEFAULT 0', 'SELECT 1');
|
||||
PREPARE stmt FROM @ddl;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
SET @exists_column = (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='zyt_prescription_esign' AND COLUMN_NAME='auth_method');
|
||||
SET @ddl = IF(@exists_column=0, 'ALTER TABLE zyt_prescription_esign ADD auth_method varchar(8) NOT NULL DEFAULT '''', ADD sms_sent_at int unsigned NOT NULL DEFAULT 0, ADD sms_verified_at int unsigned NOT NULL DEFAULT 0, ADD sms_attempts tinyint unsigned NOT NULL DEFAULT 0, ADD doctor_setup_required tinyint unsigned NOT NULL DEFAULT 0, ADD INDEX idx_esign_doctor_sms (doctor_id,environment,app_id,sms_sent_at)', 'SELECT 1');
|
||||
PREPARE stmt FROM @ddl;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `zyt_doctor_esign_account` (
|
||||
`id` int unsigned NOT NULL AUTO_INCREMENT,
|
||||
`doctor_id` int unsigned NOT NULL,
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
-- Apply before enabling ESIGN_DOCTOR_SMS_ENABLED. Existing doctor accounts are reused.
|
||||
CREATE TABLE IF NOT EXISTS `zyt_doctor_esign_identity` (
|
||||
`doctor_id` int unsigned NOT NULL,
|
||||
`environment` varchar(16) NOT NULL,
|
||||
`app_id` varchar(64) NOT NULL,
|
||||
`doctor_name` varchar(100) NOT NULL DEFAULT '',
|
||||
`account_id` varchar(128) NOT NULL DEFAULT '',
|
||||
`flow_id` varchar(128) NOT NULL DEFAULT '',
|
||||
`auth_url` text,
|
||||
`mobile_hash` char(64) NOT NULL DEFAULT '',
|
||||
`flow_started_at` int unsigned NOT NULL DEFAULT 0,
|
||||
`operation_token` char(32) NOT NULL DEFAULT '',
|
||||
`operation_expires_at` int unsigned NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (`doctor_id`,`environment`,`app_id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='医师实名在途流程,不保存原始证件号、手机号或验证码';
|
||||
@@ -0,0 +1,15 @@
|
||||
-- Apply before enabling ESIGN_DOCTOR_QUICKSIGN_ENABLED.
|
||||
CREATE TABLE IF NOT EXISTS `zyt_doctor_esign_quicksign` (
|
||||
`doctor_id` int unsigned NOT NULL,
|
||||
`environment` varchar(16) NOT NULL,
|
||||
`app_id` varchar(64) NOT NULL,
|
||||
`doctor_name` varchar(100) NOT NULL DEFAULT '',
|
||||
`account_id` varchar(128) NOT NULL DEFAULT '',
|
||||
`flow_id` varchar(128) NOT NULL DEFAULT '',
|
||||
`auth_url` text,
|
||||
`flow_started_at` int unsigned NOT NULL DEFAULT 0,
|
||||
`expires_at` int unsigned NOT NULL DEFAULT 0,
|
||||
`operation_token` char(32) NOT NULL DEFAULT '',
|
||||
`operation_expires_at` int unsigned NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (`doctor_id`,`environment`,`app_id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='医师快捷签意愿授权';
|
||||
@@ -0,0 +1,29 @@
|
||||
SET @has_review_required = (
|
||||
SELECT COUNT(*) FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='zyt_prescription_esign' AND COLUMN_NAME='review_required'
|
||||
);
|
||||
SET @ddl = IF(@has_review_required=0, 'ALTER TABLE zyt_prescription_esign ADD review_required tinyint NOT NULL DEFAULT 0', 'SELECT 1');
|
||||
PREPARE stmt FROM @ddl;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `zyt_prescription_review_esign` (
|
||||
`prescription_id` int unsigned NOT NULL,
|
||||
`reviewer_id` int unsigned NOT NULL,
|
||||
`signer_name` varchar(100) NOT NULL,
|
||||
`environment` varchar(16) NOT NULL,
|
||||
`app_id` varchar(64) NOT NULL,
|
||||
`account_id` varchar(128) NOT NULL,
|
||||
`reviewer_certificate` char(64) NOT NULL,
|
||||
`doctor_signature` char(64) NOT NULL,
|
||||
`doctor_pdf_hash` char(64) NOT NULL,
|
||||
`state` varchar(16) NOT NULL,
|
||||
`operation_token` char(32) NOT NULL,
|
||||
`confirmed_at` bigint unsigned NOT NULL,
|
||||
`update_time` bigint unsigned NOT NULL,
|
||||
`sign_service_id` varchar(128) NOT NULL DEFAULT '',
|
||||
`signed_hash` char(64) NOT NULL DEFAULT '',
|
||||
`signature_time` bigint unsigned NOT NULL DEFAULT 0,
|
||||
`error_message` varchar(255) NOT NULL DEFAULT '',
|
||||
PRIMARY KEY (`prescription_id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='处方复核电子签署证据';
|
||||
@@ -0,0 +1,295 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\common\service\esign {
|
||||
class EsignProviderException extends \RuntimeException
|
||||
{
|
||||
public function __construct(public string $operation, public string $providerCode) {}
|
||||
}
|
||||
|
||||
final class EsignClient
|
||||
{
|
||||
public const NAME = '测试医师';
|
||||
public const DOCUMENT = '110101199001011237';
|
||||
public static array $identity = ['status' => 'INIT'];
|
||||
public static int $starts = 0;
|
||||
public static int $creates = 0;
|
||||
public static ?string $mobile = null;
|
||||
public static bool $expired = false;
|
||||
public static ?\Closure $duringStart = null;
|
||||
public static ?\Closure $duringRecipientLookup = null;
|
||||
public static ?string $account = null;
|
||||
public static int $quickStarts = 0;
|
||||
public static int $willingnessChecks = 0;
|
||||
public static int $willingnessExpiry = 0;
|
||||
public static bool $willingnessValid = true;
|
||||
public static ?\Closure $duringWillingnessCheck = null;
|
||||
|
||||
public function startDoctorIdentity(string $name, string $contextId, string $mobile, ?string $accountId): array
|
||||
{
|
||||
++self::$starts;
|
||||
self::$account = $accountId;
|
||||
if (self::$duringStart) {
|
||||
(self::$duringStart)();
|
||||
}
|
||||
return ['flow_id' => 'flow-' . self::$starts, 'auth_url' => 'https://smlt.esign.cn/example/' . self::$starts];
|
||||
}
|
||||
|
||||
public function identityDetail(string $flowId): array
|
||||
{
|
||||
return self::$identity + ['flowId' => $flowId, 'appId' => 'fixture', 'objectType' => 'INDIVIDUAL'];
|
||||
}
|
||||
|
||||
public function startDoctorQuickAuthorization(string $name, string $document, string $contextId, string $accountId): array
|
||||
{
|
||||
if ($name !== self::NAME || $document !== self::DOCUMENT || $accountId !== 'bound-account'
|
||||
|| !str_starts_with($contextId, 'doctor-quicksign-')) {
|
||||
throw new \RuntimeException('Wrong quick-sign authorization subject or context');
|
||||
}
|
||||
++self::$quickStarts;
|
||||
if (self::$duringStart) {
|
||||
(self::$duringStart)();
|
||||
}
|
||||
return ['flow_id' => 'quick-proof-' . self::$quickStarts, 'auth_url' => 'https://smlt.esign.cn/quick/' . self::$quickStarts];
|
||||
}
|
||||
|
||||
public function willingnessValidity(string $flowId): array
|
||||
{
|
||||
++self::$willingnessChecks;
|
||||
if (self::$duringWillingnessCheck) {
|
||||
(self::$duringWillingnessCheck)();
|
||||
}
|
||||
if ($flowId !== 'quick-proof-' . self::$quickStarts || !self::$willingnessValid) {
|
||||
return ['state' => 'exhausted', 'expires_at' => 0, 'remaining_times' => 0];
|
||||
}
|
||||
return ['state' => 'valid', 'expires_at' => self::$willingnessExpiry, 'remaining_times' => 2];
|
||||
}
|
||||
|
||||
public function createPerson(string $name, string $document, string $flowId): string
|
||||
{
|
||||
if ($name !== self::NAME || $document !== self::DOCUMENT || $flowId !== 'flow-' . self::$starts) {
|
||||
throw new \RuntimeException('Identity proof mismatch');
|
||||
}
|
||||
++self::$creates;
|
||||
return 'bound-account';
|
||||
}
|
||||
|
||||
public function signingAccount(string $accountId): array
|
||||
{
|
||||
return ['accountId' => $accountId, 'name' => self::NAME, 'idNo' => self::DOCUMENT,
|
||||
'accountType' => 'PERSON', 'idNoType' => 'MAINLAND'];
|
||||
}
|
||||
|
||||
public function certificateValidity(string $accountId): array
|
||||
{
|
||||
return ['startDate' => '2024-01-01 08:00:00',
|
||||
'endDate' => self::$expired ? '2024-02-01 08:00:00' : '2099-01-01 08:00:00'];
|
||||
}
|
||||
|
||||
public function authorizedMobile(string $name, string $document): ?string
|
||||
{
|
||||
if ($name !== self::NAME || $document !== self::DOCUMENT) {
|
||||
throw new \RuntimeException('Wrong provider subject');
|
||||
}
|
||||
if (self::$duringRecipientLookup) {
|
||||
(self::$duringRecipientLookup)();
|
||||
}
|
||||
return self::$mobile;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace {
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
require dirname(__DIR__) . '/vendor/topthink/framework/src/helper.php';
|
||||
|
||||
use app\common\service\esign\DoctorEsignIdentityRequired;
|
||||
use app\common\service\esign\DoctorEsignAuthorizationRequired;
|
||||
use app\common\service\esign\DoctorEsignIdentityService as Enrollment;
|
||||
use app\common\service\esign\EsignClient as Provider;
|
||||
use think\facade\Db;
|
||||
use think\Container;
|
||||
|
||||
$app = new think\App();
|
||||
$app->instance('log', new Psr\Log\NullLogger());
|
||||
$manager = new think\DbManager();
|
||||
$manager->setConfig(['default' => 'test', 'connections' => ['test' => [
|
||||
'type' => 'sqlite', 'database' => ':memory:', 'prefix' => 'zyt_', 'fields_strict' => true,
|
||||
]]]);
|
||||
Container::getInstance()->instance('think\DbManager', $manager);
|
||||
$config = new think\Config();
|
||||
$settings = ['enabled' => true, 'environment' => 'sandbox', 'app_id' => 'fixture', 'app_secret' => 'fixture-secret'];
|
||||
$config->set($settings, 'esign');
|
||||
Container::getInstance()->instance('config', $config);
|
||||
|
||||
foreach (['identity', 'quicksign'] as $migration) {
|
||||
$sql = file_get_contents(dirname(__DIR__) . '/database/migrations/2026_11_19_doctor_esign_' . $migration . '.sql');
|
||||
$sql = preg_replace('/\) ENGINE=.*;/u', ');', $sql);
|
||||
Db::execute($sql);
|
||||
Db::execute($sql);
|
||||
}
|
||||
Db::execute('CREATE TABLE zyt_admin (id INTEGER PRIMARY KEY,name TEXT,disable INTEGER DEFAULT 0,delete_time INTEGER)');
|
||||
Db::execute('CREATE TABLE zyt_admin_role (admin_id INTEGER,role_id INTEGER)');
|
||||
Db::execute('CREATE TABLE zyt_doctor_esign_account (doctor_id INTEGER,environment TEXT,app_id TEXT,account_id TEXT,
|
||||
doctor_name TEXT,create_time INTEGER,UNIQUE(doctor_id,environment,app_id))');
|
||||
Db::name('admin')->insertAll([['id' => 1, 'name' => Provider::NAME], ['id' => 2, 'name' => '另一位医师'], ['id' => 3, 'name' => '客服']]);
|
||||
Db::name('admin_role')->insertAll([['admin_id' => 1, 'role_id' => 1], ['admin_id' => 2, 'role_id' => 1], ['admin_id' => 3, 'role_id' => 2]]);
|
||||
|
||||
$checks = 0;
|
||||
$assert = static function (bool $condition, string $message) use (&$checks): void {
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
++$checks;
|
||||
};
|
||||
$throws = static function (callable $operation, string $expected, string $message) use ($assert): void {
|
||||
try {
|
||||
$operation();
|
||||
} catch (DomainException $error) {
|
||||
$assert(is_a($error, $expected), $message);
|
||||
return;
|
||||
}
|
||||
$assert(false, $message);
|
||||
};
|
||||
|
||||
$phone = '13800000000';
|
||||
$assert(Enrollment::status(1)['enabled'] === false, 'SMS enrollment defaults off');
|
||||
$config->set(['doctor_sms_enabled' => true], 'esign');
|
||||
$assert(Enrollment::status(1)['status'] === 'unbound', 'doctor starts unbound');
|
||||
$throws(static fn () => Enrollment::status(3), DomainException::class, 'non-physician denied');
|
||||
$throws(static fn () => Enrollment::willingnessRecipient(1, Provider::NAME, ''), DoctorEsignIdentityRequired::class, 'setup-required reason distinguishes an unbound doctor');
|
||||
|
||||
Provider::$duringStart = static function () use ($assert, $phone): void {
|
||||
$duplicate = Enrollment::start(1, $phone);
|
||||
$assert($duplicate['status'] === 'authenticating' && !isset($duplicate['auth_url']), 'concurrent start is held by the operation lease');
|
||||
};
|
||||
$first = Enrollment::start(1, $phone);
|
||||
Provider::$duringStart = null;
|
||||
$assert($first['status'] === 'authenticating' && Enrollment::start(1, $phone) === $first && Provider::$starts === 1,
|
||||
'explicit repeat resumes the hosted flow');
|
||||
$assert(Enrollment::status(2)['status'] === 'unbound', 'another physician cannot see this URL');
|
||||
$config->set(['app_id' => 'other-app'], 'esign');
|
||||
$assert(Enrollment::status(1)['status'] === 'unbound', 'another eSign application cannot see this URL');
|
||||
$config->set(['app_id' => 'fixture'], 'esign');
|
||||
$assert(!str_contains(json_encode(Db::name('doctor_esign_identity')->find()), $phone), 'mobile stored only as a keyed digest');
|
||||
$assert(Enrollment::complete(1)['status'] === 'authenticating' && Provider::$creates === 0, 'unfinished H5 does not bind');
|
||||
|
||||
Provider::$identity = ['status' => 'SUCCESS', 'indivInfo' => ['name' => Provider::NAME,
|
||||
'certType' => 'INDIVIDUAL_CH_IDCARD', 'certNo' => '1101**********123X']];
|
||||
$pending = Enrollment::status(1);
|
||||
$assert($pending['status'] === 'binding_required' && $pending['identity_details_required'] && !isset($pending['auth_url'])
|
||||
&& Provider::$creates === 0, 'successful polling exposes only safe metadata and accepts masked identity as supplemental');
|
||||
$assert(Enrollment::complete(1, 'bad-input')['identity_details_required'] && Provider::$creates === 0, 'invalid supplemental number never reaches SDK');
|
||||
$assert(Enrollment::complete(1, Provider::DOCUMENT)['status'] === 'needs_mobile' && Provider::$creates === 1,
|
||||
'successful provider proof binds without signing, but an absent provider authorization is not ready');
|
||||
$assert(Db::name('doctor_esign_identity')->count() === 0 && !str_contains(json_encode(Db::name('doctor_esign_account')->find()), Provider::DOCUMENT),
|
||||
'completed enrollment clears hosted URL and does not persist identity number');
|
||||
|
||||
$throws(static fn () => Enrollment::willingnessRecipient(1, Provider::NAME, 'bound-account'), DoctorEsignIdentityRequired::class, 'willingness requires a current authorized mobile');
|
||||
Provider::$expired = true;
|
||||
$assert(Enrollment::status(1)['status'] === 'renewal_required', 'expired provider certificate requires renewal');
|
||||
Provider::$identity = ['status' => 'INIT'];
|
||||
$assert(Enrollment::start(1, $phone)['status'] === 'authenticating' && Provider::$account === 'bound-account', 'renewal reuses canonical account');
|
||||
Provider::$identity = ['status' => 'SUCCESS', 'indivInfo' => null];
|
||||
Provider::$mobile = $phone;
|
||||
Provider::$expired = false;
|
||||
$assert(Enrollment::status(1)['identity_details_required'] === false, 'a bound account needs no supplemental input');
|
||||
$ready = Enrollment::complete(1);
|
||||
$assert($ready['status'] === 'ready' && $ready['cert_expires_at'] === strtotime('2099-01-01T00:00:00Z') && Provider::$creates === 1,
|
||||
'same account becomes ready with certificate date in configured SDK timezone');
|
||||
$assert(!str_contains(json_encode($ready), $phone) && !str_contains(json_encode($ready), Provider::DOCUMENT), 'status never returns provider identity');
|
||||
$recipient = Enrollment::willingnessRecipient(1, Provider::NAME, 'bound-account');
|
||||
$assert($recipient === ['name' => Provider::NAME, 'idNo' => Provider::DOCUMENT, 'mobile' => $phone], 'recipient includes only verified transient provider fields');
|
||||
|
||||
Provider::$duringRecipientLookup = static fn () => Db::name('doctor_esign_account')->where('doctor_id', 1)->update(['account_id' => 'changed']);
|
||||
$throws(static fn () => Enrollment::willingnessRecipient(1, Provider::NAME, 'bound-account'), DomainException::class, 'mid-flight account change cannot authorize willingness');
|
||||
Provider::$duringRecipientLookup = null;
|
||||
Provider::$mobile = null;
|
||||
Db::name('doctor_esign_account')->where('doctor_id', 1)->update(['account_id' => 'bound-account']);
|
||||
|
||||
$assert(!Enrollment::quickEnabled(), 'quick-sign is disabled by default');
|
||||
$config->set(['doctor_sms_enabled' => false, 'doctor_quicksign_enabled' => true], 'esign');
|
||||
$quickReady = Enrollment::status(1);
|
||||
$assert($quickReady['status'] === 'ready' && $quickReady['quicksign_enabled'] && $quickReady['quicksign_expires_at'] === 0,
|
||||
'a bound current certificate can enter quick-sign without SMS or previous authorization');
|
||||
$throws(static fn () => Enrollment::quickAuthorization(1, Provider::NAME, 'bound-account'), DoctorEsignAuthorizationRequired::class,
|
||||
'an established signing account and historical identity are insufficient to sign');
|
||||
$assert(Enrollment::start(2, '')['status'] === 'unbound' && Provider::$quickStarts === 0, 'an unbound physician cannot start a quick-sign grant');
|
||||
|
||||
Provider::$identity = ['status' => 'INIT'];
|
||||
Provider::$duringStart = static function () use ($assert): void {
|
||||
$processing = Enrollment::status(1);
|
||||
$assert($processing['status'] === 'authenticating' && $processing['quicksign_authorizing'] && !isset($processing['auth_url']),
|
||||
'quick-sign grant initiation is serialized');
|
||||
};
|
||||
$quick = Enrollment::start(1, '');
|
||||
Provider::$duringStart = null;
|
||||
$assert($quick['quicksign_authorizing'] && $quick['status'] === 'authenticating' && $quick['quicksign_expires_at'] === 0
|
||||
&& isset($quick['auth_url']) && Enrollment::start(1, '') === $quick && Provider::$quickStarts === 1,
|
||||
'empty mobile starts or resumes a distinct provider grant');
|
||||
$assert(Enrollment::complete(1) === $quick && Provider::$willingnessChecks === 0, 'incomplete face authentication cannot grant signing');
|
||||
|
||||
$now = time();
|
||||
Provider::$identity = ['status' => 'SUCCESS', 'indivInfo' => null, 'endTime' => $now * 1000];
|
||||
Provider::$willingnessExpiry = ($now + 3 * 86400) * 1000;
|
||||
$quickPending = Enrollment::status(1);
|
||||
$assert($quickPending['status'] === 'binding_required' && $quickPending['quicksign_authorizing']
|
||||
&& !$quickPending['identity_details_required'] && $quickPending['quicksign_expires_at'] === 0 && !isset($quickPending['auth_url']),
|
||||
'provider success waits for explicit physician confirmation without another identity prompt');
|
||||
$throws(static fn () => Enrollment::quickAuthorization(1, Provider::NAME, 'bound-account'), DoctorEsignAuthorizationRequired::class,
|
||||
'provider face verification alone does not activate grant');
|
||||
$quickGranted = Enrollment::complete(1);
|
||||
$assert($quickGranted['status'] === 'ready' && !$quickGranted['quicksign_authorizing']
|
||||
&& $quickGranted['quicksign_expires_at'] === $now + 86400 && $quickGranted['quicksign_remaining_times'] === 2
|
||||
&& !str_contains(json_encode($quickGranted), 'quick-proof') && !str_contains(json_encode($quickGranted), Provider::DOCUMENT),
|
||||
'confirmed provider proof is capped to 24 hours and remains server-only');
|
||||
$quickRow = Db::name('doctor_esign_quicksign')->where('doctor_id', 1)->find();
|
||||
$assert($quickRow['flow_id'] === 'quick-proof-1' && $quickRow['auth_url'] === null
|
||||
&& Db::name('doctor_esign_identity')->count() === 0 && Provider::$creates === 1, 'grant clears its hosted link and keeps enrollment untouched');
|
||||
|
||||
$checksBeforeReuse = Provider::$willingnessChecks;
|
||||
Provider::$willingnessExpiry = ($now + 120) * 1000 + 123;
|
||||
$assert(Enrollment::quickAuthorization(1, Provider::NAME, 'bound-account') === 'quick-proof-1'
|
||||
&& Enrollment::quickAuthorization(1, Provider::NAME, 'bound-account') === 'quick-proof-1'
|
||||
&& Provider::$willingnessChecks === $checksBeforeReuse + 2,
|
||||
'the same independent proof can be reused with a fresh provider check each time');
|
||||
$assert(Enrollment::status(1)['quicksign_expires_at'] === $now + 120, 'reported validity honors a shorter provider expiry');
|
||||
$assert(Enrollment::start(1, '')['quicksign_expires_at'] === $now + 120 && Provider::$quickStarts === 1, 'a current grant is never replaced by a casual repeat');
|
||||
$throws(static fn () => Enrollment::quickAuthorization(2, Provider::NAME, 'bound-account'), DoctorEsignIdentityRequired::class,
|
||||
'another physician cannot use this proof');
|
||||
$throws(static fn () => Enrollment::quickAuthorization(1, Provider::NAME, 'other-account'), DomainException::class,
|
||||
'signatures must match the authorized SDK account');
|
||||
$config->set(['app_id' => 'other-app'], 'esign');
|
||||
$throws(static fn () => Enrollment::quickAuthorization(1, Provider::NAME, 'bound-account'), DoctorEsignIdentityRequired::class,
|
||||
'another eSign application cannot use this proof');
|
||||
$config->set(['app_id' => 'fixture'], 'esign');
|
||||
Provider::$duringWillingnessCheck = static fn () => Db::name('doctor_esign_account')->where('doctor_id', 1)->update(['account_id' => 'changed']);
|
||||
$throws(static fn () => Enrollment::quickAuthorization(1, Provider::NAME, 'bound-account'), DomainException::class,
|
||||
'a mid-flight account change invalidates the checked result');
|
||||
Provider::$duringWillingnessCheck = null;
|
||||
Db::name('doctor_esign_account')->where('doctor_id', 1)->update(['account_id' => 'bound-account']);
|
||||
Provider::$willingnessValid = false;
|
||||
$spent = Enrollment::status(1);
|
||||
$assert($spent['quicksign_expires_at'] === 0 && $spent['quicksign_remaining_times'] === 0
|
||||
&& $spent['quicksign_unavailable_reason'] === 'exhausted' && $spent['status'] === 'ready',
|
||||
'provider exhaustion leaves certificate enrollment valid and reports the spent grant');
|
||||
$throws(static fn () => Enrollment::quickAuthorization(1, Provider::NAME, 'bound-account'), DoctorEsignAuthorizationRequired::class,
|
||||
'provider cancellation/exhaustion blocks dispatch');
|
||||
Provider::$willingnessValid = true;
|
||||
Provider::$expired = true;
|
||||
$throws(static fn () => Enrollment::quickAuthorization(1, Provider::NAME, 'bound-account'), DoctorEsignIdentityRequired::class,
|
||||
'expired identity certificate is distinct from an unavailable signing grant');
|
||||
Provider::$expired = false;
|
||||
$checksBeforeExpiry = Provider::$willingnessChecks;
|
||||
Db::name('doctor_esign_quicksign')->where('doctor_id', 1)->update(['expires_at' => time() - 1]);
|
||||
$throws(static fn () => Enrollment::quickAuthorization(1, Provider::NAME, 'bound-account'), DoctorEsignAuthorizationRequired::class,
|
||||
'locally expired grant remains invalid even if the provider still accepts the flow');
|
||||
$assert(Provider::$willingnessChecks === $checksBeforeExpiry && Enrollment::status(1)['status'] === 'ready'
|
||||
&& Enrollment::status(1)['quicksign_expires_at'] === 0, 'expired grant leaves the current signing account enrolled');
|
||||
|
||||
Provider::$identity = ['status' => 'INIT'];
|
||||
$assert(Enrollment::start(1, '')['quicksign_authorizing'] && Provider::$quickStarts === 2, 'expired grant permits a new standalone grant');
|
||||
Provider::$identity = ['status' => 'SUCCESS', 'indivInfo' => null];
|
||||
$assert(Enrollment::complete(1)['quicksign_expires_at'] === $now + 120, 'provider validity is preserved when shorter than the local bound');
|
||||
echo "Doctor eSign enrollment: $checks checks passed (SQLite and provider doubles)\n";
|
||||
}
|
||||
@@ -112,9 +112,12 @@ esignExpect($identity === ['flow_id' => 'flow-7', 'auth_url' => 'https://smlt.es
|
||||
esignExpect($request['url'] === 'https://smlopenapi.esign.cn/v2/identity/auth/web/indivAuthUrl', 'independent v2 identity API');
|
||||
esignExpect($body['indivInfo']['sdkAccountId'] === 'sdk-account-1' && !isset($body['sdkAccountId']), 'SDK account nested in indivInfo');
|
||||
esignExpect($body['configParams']['indivUneditableInfo'] === ['name', 'certType'], 'doctor name locked');
|
||||
esignExpect($body['usageType'] === 'CERTAPPLY', 'identity requests certificate agreement and issuance for signing');
|
||||
esignExpect($body['authType'] === 'PSN_TELECOM_AUTHCODE'
|
||||
&& $body['availableAuthTypes'] === ['PSN_TELECOM_AUTHCODE'], 'embedded identity uses mobile authentication without external face apps');
|
||||
// Fixed vectors independently calculated with Python hashlib/hmac; UTF-8 bytes must match exactly.
|
||||
esignExpect($request['headers']['Content-MD5'] === 'M2hjK+7n9RSpPC8C09vWVQ==', 'POST content MD5 vector');
|
||||
esignExpect($request['headers']['X-Tsign-Open-Ca-Signature'] === 'i2dGU5UsRuMb6has/RBZN5BAsECYV4ziEDF17YHaL0g=', 'POST HMACSHA256 vector');
|
||||
esignExpect($request['headers']['Content-MD5'] === 'j/xD3VTZtMlQ9HftwFK6Cg==', 'POST content MD5 vector');
|
||||
esignExpect($request['headers']['X-Tsign-Open-Ca-Signature'] === 'oMBDY2WjbOSJrIhQbxtsf9EgX/iYzf6NoP60AtqGEI4=', 'POST HMACSHA256 vector');
|
||||
esignExpect($request['headers']['X-Tsign-Open-Ca-Timestamp'] === '1800000000000', 'timestamp in milliseconds');
|
||||
esignExpect($request['headers']['X-Tsign-Open-Auth-Mode'] === 'Signature', 'signature auth mode');
|
||||
|
||||
@@ -128,6 +131,15 @@ $valid = ['errCode' => 0, 'status' => 1, 'remainingTimes' => 1, 'expireAt' => $c
|
||||
$responses[] = esignResponse($valid);
|
||||
$client->checkWillingness('flow-7');
|
||||
esignExpect(str_ends_with($requests[count($requests) - 1]['url'], '/timevale/auth/queryWillingnessValidity'), 'willingness endpoint');
|
||||
$responses[] = esignResponse($valid);
|
||||
esignExpect($client->willingnessExpiresAt('flow-7') === $valid['expireAt'], 'valid authorization returns its Unix millisecond expiry');
|
||||
$responses[] = esignResponse(array_replace($valid, ['remainingTimes' => 2]));
|
||||
esignExpect($client->willingnessValidity('flow-7') === [
|
||||
'state' => 'valid', 'expires_at' => $valid['expireAt'], 'remaining_times' => 2,
|
||||
], 'valid authorization exposes the provider count');
|
||||
$responses[] = esignResponse(array_replace($valid, ['status' => 0, 'remainingTimes' => 0]));
|
||||
esignExpect($client->willingnessValidity('flow-7')['state'] === 'exhausted',
|
||||
'provider returns exhausted even when the expiration is still in the future');
|
||||
foreach ([['status' => 0], ['remainingTimes' => 0], ['expireAt' => $clock()], ['status' => '1'], ['expireAt' => 'not-a-date']] as $invalid) {
|
||||
$responses[] = esignResponse(array_replace($valid, $invalid));
|
||||
esignThrows(fn () => $client->checkWillingness('flow-7'), EsignProviderException::class, 'WILLINGNESS_INVALID');
|
||||
@@ -139,6 +151,13 @@ $request = $requests[count($requests) - 1];
|
||||
esignExpect(str_ends_with($request['url'], '/timevale/account/addPerson'), 'account SDK endpoint');
|
||||
esignExpect(json_decode($request['body'], true) === ['name' => '张医生', 'idNo' => 'TEST-IDENTITY', 'idNoType' => 'MAINLAND', 'identityAuthId' => 'flow-7'], 'identity bound to SDK account');
|
||||
|
||||
$privateIdentity = '110101199001011237'; // Synthetic fixture, never sent over a network.
|
||||
$responses[] = esignResponse(['errCode' => 9001, 'msg' => 'mismatch ' . $privateIdentity, 'idNo' => $privateIdentity]);
|
||||
$before = count($requests);
|
||||
$bindingError = esignThrows(fn () => $client->createPerson('张医生', $privateIdentity, 'flow-7'), EsignProviderException::class, 'PROVIDER_9001');
|
||||
esignExpect(!str_contains($bindingError->getMessage(), $privateIdentity), 'SDK binding error cannot echo supplemental number');
|
||||
esignExpect(count($requests) === $before + 1, 'SDK binding is never automatically retried');
|
||||
|
||||
$responses[] = esignResponse(['errCode' => 0, 'sealData' => base64_encode('seal-image')]);
|
||||
esignExpect($client->createSeal('person-7') === base64_encode('seal-image'), 'seal result');
|
||||
$sealBody = json_decode($requests[count($requests) - 1]['body'], true);
|
||||
@@ -157,7 +176,7 @@ esignExpect(str_contains($parts['streamFile']['headers'], 'Content-Type: applica
|
||||
esignExpect($parts['streamFile']['body'] === $pdf, 'multipart preserves arbitrary binary bytes');
|
||||
$parameters = json_decode($parts['personSignParam']['body'], true);
|
||||
esignExpect($parameters['fileBean'] === ['fileName' => 'rx-7.pdf'] && !isset($parameters['fileBean']['dstPdfFile']), 'stream response requested');
|
||||
esignExpect($parameters['signType'] === 'Single' && $parameters['posBeans'] === [['posPage' => '1', 'posX' => 420, 'posY' => 70, 'width' => 100]], 'fixed prescription signature location');
|
||||
esignExpect($parameters['signType'] === 'Single' && $parameters['posBeans'] === [['posPage' => '1', 'posX' => 520, 'posY' => 108, 'width' => 48]], 'compact first-page prescription signature');
|
||||
esignExpect($parameters['willingnessId'] === 'flow-7' && $parameters['accountId'] === 'person-7', 'signature identity binding');
|
||||
|
||||
$signatures = [['signature' => ['validate' => true], 'cert' => ['cn' => '张医生']], ['signature' => ['validate' => true]]];
|
||||
@@ -201,6 +220,14 @@ foreach ([
|
||||
}
|
||||
$responses[] = esignResponse(['errCode' => 55, 'msg' => 'secret rejected identity']);
|
||||
esignThrows(fn () => $client->signPdf('person-7', 'flow-7', base64_encode('seal'), $pdf, 'rx.pdf'), EsignProviderException::class, 'PROVIDER_55');
|
||||
$responses[] = esignResponse(['errCode' => 10002, 'msg' => '签署次数不足 private supplier text']);
|
||||
$beforeQuotaRejection = count($requests);
|
||||
$quotaRejection = esignThrows(fn () => $client->signPdf('person-7', 'flow-7', base64_encode('seal'), $pdf, 'rx.pdf'), EsignProviderException::class, 'PROVIDER_10002');
|
||||
esignExpect(str_contains($quotaRejection->getMessage(), '签署次数不足') && !str_contains($quotaRejection->getMessage(), 'private'), 'signing quota provides fixed guidance without raw supplier text');
|
||||
esignExpect(count($requests) === $beforeQuotaRejection + 1, 'signing quota error sends only one request');
|
||||
$responses[] = esignResponse(['errCode' => 10002, 'msg' => 'duplicate local initialization']);
|
||||
$initializationRejection = esignThrows(fn () => $client->initialize(), EsignProviderException::class, 'PROVIDER_10002');
|
||||
esignExpect(!str_contains($initializationRejection->getMessage(), '签署次数不足'), 'initialization 10002 is not interpreted as a signing error');
|
||||
$throwing = new EsignClient(esignConfig(), static function (): array { throw new RuntimeException('https://secret:password/private'); }, $clock);
|
||||
esignThrows(fn () => $throwing->createSeal('person-7'), EsignProviderException::class, 'TRANSPORT_ERROR');
|
||||
esignThrows(fn () => $throwing->signPdf('person-7', 'flow-7', base64_encode('seal'), $pdf, 'rx.pdf'), EsignOutcomeUnknownException::class, 'TRANSPORT_ERROR');
|
||||
@@ -225,5 +252,153 @@ $responses[] = esignResponse(['code' => 0, 'data' => ['flowId' => '7', 'shortLin
|
||||
$production->startIdentity('医生', 'rx');
|
||||
esignExpect(str_starts_with($requests[count($requests) - 1]['url'], 'https://openapi.esign.cn/v2/identity/'), 'production identity endpoint');
|
||||
|
||||
$responses[] = esignResponse(['errCode' => 403, 'msg' => 'private supplied identity 11010519491231002X']);
|
||||
$before403 = count($requests);
|
||||
$forbidden = esignThrows(fn () => $client->createPerson('测试医生', '11010519491231002X', 'flow-403'), EsignProviderException::class, 'PROVIDER_403');
|
||||
esignExpect(str_contains($forbidden->getMessage(), '接口权限及 IP 白名单'), 'account 403 supplies fixed actionable configuration guidance');
|
||||
esignExpect(!str_contains($forbidden->getMessage(), '11010519491231002X') && !str_contains($forbidden->getMessage(), 'private'), '403 guidance never echoes provider identity data');
|
||||
esignExpect(count($requests) === $before403 + 1, 'account 403 is not automatically retried');
|
||||
esignExpect($forbidden->operation === 'createPerson' && $forbidden->reason === null, 'unknown 403 retains operation without guessing a cause');
|
||||
|
||||
$privateSuffix = ' idNo=11010519491231002X appSecret=private-secret-token name=私密测试医生';
|
||||
foreach ([
|
||||
['该应用无权调用此接口' . $privateSuffix, EsignProviderException::APPLICATION_ACCESS_DENIED, '应用的接口授权'],
|
||||
['FORBIDDEN: IP地址不在白名单' . $privateSuffix, EsignProviderException::IP_WHITELIST_MISMATCH, '出口 IP'],
|
||||
['IP 白名单校验失败' . $privateSuffix, EsignProviderException::IP_WHITELIST_MISMATCH, '出口 IP'],
|
||||
['SignatureDoesNotMatch' . $privateSuffix, EsignProviderException::SIGNATURE_MISMATCH, '签名配置'],
|
||||
['FORBIDDEN' . $privateSuffix, null, '接口权限及 IP 白名单'],
|
||||
['未知供应商错误' . $privateSuffix, null, '接口权限及 IP 白名单'],
|
||||
['IP 白名单信息' . $privateSuffix, null, '接口权限及 IP 白名单'],
|
||||
['NotSignatureDoesNotMatch' . $privateSuffix, null, '接口权限及 IP 白名单'],
|
||||
[['msg' => '该应用无权调用此接口' . $privateSuffix], null, '接口权限及 IP 白名单'],
|
||||
[null, null, '接口权限及 IP 白名单'],
|
||||
] as [$vendorMessage, $reason, $hint]) {
|
||||
$responses[] = esignResponse(['errCode' => 403, 'msg' => $vendorMessage, 'idNo' => $privateIdentity]);
|
||||
$before = count($requests);
|
||||
$exception = esignThrows(fn () => $client->createPerson('测试医生', 'TEST-IDENTITY', 'flow-403'), EsignProviderException::class, 'PROVIDER_403');
|
||||
esignExpect($exception->operation === 'createPerson' && $exception->reason === $reason, '403 reason is a recognized enum or null');
|
||||
esignExpect(str_contains($exception->getMessage(), $hint), '403 reason supplies only fixed guidance');
|
||||
foreach (['11010519491231002X', $privateIdentity, 'private-secret-token', '私密测试医生', '未知供应商错误'] as $privateValue) {
|
||||
esignExpect(!str_contains($exception->getMessage(), $privateValue), '403 diagnostic omits provider payload');
|
||||
}
|
||||
esignExpect(count($requests) === $before + 1, 'classified 403 never retries');
|
||||
}
|
||||
$responses[] = esignResponse(['errCode' => 9001, 'msg' => '该应用无权调用此接口' . $privateSuffix]);
|
||||
$exception = esignThrows(fn () => $client->createPerson('测试医生', 'TEST-IDENTITY', 'flow-other'), EsignProviderException::class, 'PROVIDER_9001');
|
||||
esignExpect($exception->reason === null, '403 classification does not alter other provider errors');
|
||||
$invalidReason = new EsignProviderException('createPerson', 'PROVIDER_403', $privateSuffix);
|
||||
esignExpect($invalidReason->reason === null && !str_contains($invalidReason->getMessage(), 'private-secret-token'), 'exception rejects unrecognized reason values');
|
||||
|
||||
$account = [
|
||||
'accountId' => 'person-7', 'name' => '测试医生', 'idNo' => $privateIdentity,
|
||||
'idNoType' => 'MAINLAND', 'accountType' => 'PERSON',
|
||||
];
|
||||
$responses[] = esignResponse(['errCode' => 0, 'cert' => 'cert-contents'] + $account);
|
||||
esignExpect($client->signingAccount('person-7') === $account, 'signing account returns only requested fields');
|
||||
$request = $requests[array_key_last($requests)];
|
||||
esignExpect(str_ends_with($request['url'], '/timevale/account/queryByAccountId')
|
||||
&& json_decode($request['body'], true) === ['accountId' => 'person-7'], 'signing account SDK request');
|
||||
foreach ([['idNo' => null], ['accountId' => 'other-person']] as $invalidAccount) {
|
||||
$responses[] = esignResponse(['errCode' => 0] + $invalidAccount + $account);
|
||||
esignThrows(fn () => $client->signingAccount('person-7'), EsignProviderException::class, 'RESPONSE_INVALID');
|
||||
}
|
||||
|
||||
$certDates = ['startDate' => '2026-09-11 10:20:30', 'endDate' => '2027-09-11 10:20:30'];
|
||||
$responses[] = esignResponse(['errCode' => 0, 'sn' => 'cert-serial', 'owner' => '测试医生'] + $certDates);
|
||||
esignExpect($client->certificateValidity('person-7') === $certDates, 'certificate validity retains provider dates only');
|
||||
$request = $requests[array_key_last($requests)];
|
||||
esignExpect(str_ends_with($request['url'], '/timevale/user/cert/queryLatestAvailableCert')
|
||||
&& json_decode($request['body'], true) === ['accountId' => 'person-7'], 'certificate validity SDK request');
|
||||
$responses[] = esignResponse(['errCode' => 0, 'startDate' => $certDates['startDate']]);
|
||||
esignThrows(fn () => $client->certificateValidity('person-7'), EsignProviderException::class, 'RESPONSE_INVALID');
|
||||
|
||||
$doctorIdentity = ['flowId' => 'doctor-enrollment-1', 'shortLink' => 'https://smlt.esign.cn/enrollment'];
|
||||
foreach ([null, 'person-7'] as $accountId) {
|
||||
$responses[] = esignResponse(['code' => 0, 'data' => $doctorIdentity]);
|
||||
esignExpect($client->startDoctorIdentity('测试医生', 'doctor-context', '13800138000', $accountId)
|
||||
=== ['flow_id' => 'doctor-enrollment-1', 'auth_url' => $doctorIdentity['shortLink']], 'doctor enrollment returns hosted URL');
|
||||
$request = $requests[array_key_last($requests)];
|
||||
$body = json_decode($request['body'], true);
|
||||
$person = ['name' => '测试医生', 'certType' => 'INDIVIDUAL_CH_IDCARD', 'authMobileNo' => '13800138000'];
|
||||
if ($accountId !== null) {
|
||||
$person['sdkAccountId'] = $accountId;
|
||||
}
|
||||
esignExpect($request['url'] === 'https://smlopenapi.esign.cn/v2/identity/auth/web/indivAuthUrl'
|
||||
&& $body === [
|
||||
'indivInfo' => $person,
|
||||
'usageType' => 'CERTAPPLY',
|
||||
'authType' => 'PSN_FACEAUTH_BYURL_ZHIMA',
|
||||
'availableAuthTypes' => ['PSN_FACEAUTH_BYURL_ZHIMA'],
|
||||
'configParams' => ['indivUneditableInfo' => ['name', 'certType']],
|
||||
'contextInfo' => ['contextId' => 'doctor-context', 'showResultPage' => true],
|
||||
], 'enrollment requests certificate and authorizes mobile through Alipay face authentication');
|
||||
}
|
||||
$responses[] = esignResponse(['code' => 0, 'data' => ['flowId' => 'enrollment', 'shortLink' => 'https://attacker.invalid/enrollment']]);
|
||||
esignThrows(fn () => $client->startDoctorIdentity('测试医生', 'ctx', '13800138000'), EsignProviderException::class, 'AUTH_URL_INVALID');
|
||||
|
||||
$responses[] = esignResponse(['code' => 0, 'data' => ['flowId' => 'quick-auth', 'shortLink' => 'https://smlt.esign.cn/quick']]);
|
||||
esignExpect($client->startDoctorQuickAuthorization('测试医生', $privateIdentity, 'doctor-quicksign-ctx', 'person-7')
|
||||
=== ['flow_id' => 'quick-auth', 'auth_url' => 'https://smlt.esign.cn/quick'], 'quickface authorization result stays limited to a flow and hosted URL');
|
||||
$request = $requests[array_key_last($requests)];
|
||||
$body = json_decode($request['body'], true);
|
||||
esignExpect($request['url'] === 'https://smlopenapi.esign.cn/v2/identity/auth/web/indivAuthUrl'
|
||||
&& $body['indivInfo'] === ['name' => '测试医生', 'certType' => 'INDIVIDUAL_CH_IDCARD', 'certNo' => $privateIdentity, 'sdkAccountId' => 'person-7']
|
||||
&& $body['usageType'] === 'PUREVERIFY'
|
||||
&& $body['availableAuthTypes'] === ['PSN_FACEAUTH_BYURL_ZHIMA']
|
||||
&& $body['configParams']['indivUneditableInfo'] === ['name', 'certType', 'certNo']
|
||||
&& $body['contextInfo']['contextId'] === 'doctor-quicksign-ctx', 'quick-sign face flow locks the bound identity and asks for no SMS credentials');
|
||||
|
||||
$willingnessEndpoint = 'https://smlopenapi.esign.cn/v2/identity/willingness/api/individual';
|
||||
$doctorInfo = ['name' => '测试医生', 'idNo' => $privateIdentity, 'certType' => 'INDIVIDUAL_CH_IDCARD'];
|
||||
$responses[] = esignResponse(['code' => 0, 'data' => ['mobileNo' => '13800138000']]);
|
||||
esignExpect($client->authorizedMobile('测试医生', $privateIdentity) === '13800138000', 'authorized phone returned as text');
|
||||
$request = $requests[array_key_last($requests)];
|
||||
esignExpect($request['method'] === 'POST' && $request['url'] === $willingnessEndpoint . '/get-individual-info'
|
||||
&& json_decode($request['body'], true) === $doctorInfo, 'authorized phone read-only request');
|
||||
foreach ([null, ['mobileNo' => null], ['mobileNo' => '']] as $unbound) {
|
||||
$responses[] = esignResponse(['code' => 0, 'data' => $unbound]);
|
||||
esignExpect($client->authorizedMobile('测试医生', $privateIdentity) === null, 'provider returned no phone binding');
|
||||
}
|
||||
foreach (['unexpected', ['mobileNo' => '138****8000'], ['mobileNo' => 13800138000]] as $malformed) {
|
||||
$responses[] = esignResponse(['code' => 0, 'data' => $malformed]);
|
||||
esignThrows(fn () => $client->authorizedMobile('测试医生', $privateIdentity), EsignProviderException::class, 'RESPONSE_INVALID');
|
||||
}
|
||||
|
||||
foreach (['sms-flow-1', 'sms-flow-2'] as $smsFlow) {
|
||||
$responses[] = esignResponse(['code' => 0, 'data' => ['flowId' => $smsFlow]]);
|
||||
esignExpect($client->sendWillingnessCode('测试医生', $privateIdentity, '13800138000') === $smsFlow, 'new willingness flow from provider');
|
||||
$request = $requests[array_key_last($requests)];
|
||||
esignExpect($request['method'] === 'POST' && $request['url'] === $willingnessEndpoint . '/send-code'
|
||||
&& json_decode($request['body'], true) === ['mobileNo' => '13800138000'] + $doctorInfo,
|
||||
'SMS request for the authorized user');
|
||||
}
|
||||
$responses[] = esignResponse(['code' => 0, 'data' => null]);
|
||||
esignThrows(fn () => $client->sendWillingnessCode('测试医生', $privateIdentity, '13800138000'), EsignProviderException::class, 'RESPONSE_INVALID');
|
||||
$responses[] = esignResponse(['code' => 0, 'data' => null]);
|
||||
$client->verifyWillingnessCode('sms/flow', '000123');
|
||||
$request = $requests[array_key_last($requests)];
|
||||
esignExpect($request['method'] === 'POST' && $request['url'] === $willingnessEndpoint . '/sms%2Fflow/verify-send-code'
|
||||
&& json_decode($request['body'], true) === ['authCode' => '000123'], 'verification preserves leading zeroes and encodes the flow path');
|
||||
|
||||
$before = count($requests);
|
||||
esignThrows(fn () => $client->startDoctorIdentity('测试医生', 'ctx', '138****8000'), EsignProviderException::class, 'INPUT_INVALID');
|
||||
esignThrows(fn () => $client->sendWillingnessCode('测试医生', $privateIdentity, '+8613800138000'), EsignProviderException::class, 'INPUT_INVALID');
|
||||
esignThrows(fn () => $client->verifyWillingnessCode('sms-flow-1', '12345'), EsignProviderException::class, 'INPUT_INVALID');
|
||||
esignExpect(count($requests) === $before, 'invalid phone and code are rejected before provider requests');
|
||||
|
||||
foreach ([
|
||||
['authorizedMobile', fn () => $client->authorizedMobile('测试医生', $privateIdentity), 30500101],
|
||||
['sendWillingnessCode', fn () => $client->sendWillingnessCode('测试医生', $privateIdentity, '13800138000'), 30500101],
|
||||
['verifyWillingnessCode', fn () => $client->verifyWillingnessCode('sms-flow-1', '000123'), 30503002],
|
||||
] as [$operation, $call, $code]) {
|
||||
$responses[] = esignResponse(['code' => $code, 'message' => 'private ' . $privateIdentity . ' 13800138000 000123', 'data' => ['idNo' => $privateIdentity]]);
|
||||
$before = count($requests);
|
||||
$exception = esignThrows($call, EsignProviderException::class, 'PROVIDER_' . $code);
|
||||
esignExpect($exception->operation === $operation && count($requests) === $before + 1, 'provider errors preserve operation without retries');
|
||||
foreach ([$privateIdentity, '13800138000', '000123', 'private'] as $secret) {
|
||||
esignExpect(!str_contains($exception->getMessage(), $secret), 'provider errors omit sensitive payloads');
|
||||
}
|
||||
}
|
||||
|
||||
esignExpect($responses === [], 'all expected transport responses consumed');
|
||||
echo 'EsignClient: ' . $checks . " checks passed (offline)\n";
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\common\service\esign {
|
||||
final class PrescriptionEsignService
|
||||
{
|
||||
public static array $calls = [];
|
||||
public static array $starts = [];
|
||||
public static array $verifications = [];
|
||||
public static function start(int $id, int $actor, array $info, bool $restartIdentity = false): array
|
||||
{
|
||||
self::$starts[] = [$id, $actor, $info, $restartIdentity];
|
||||
return ['status' => 'authenticating'];
|
||||
}
|
||||
public static function complete(int $id, int $actor, array $info, string $identityNumber = '', bool $verifyOnly = false): array
|
||||
{
|
||||
self::$calls[] = [$id, $actor, $info, $identityNumber, $verifyOnly];
|
||||
return ['status' => 'signed'];
|
||||
}
|
||||
public static function verifyWillingness(int $id, int $actor, array $info, string $code): array
|
||||
{
|
||||
self::$verifications[] = [$id, $actor, $info, $code];
|
||||
return ['status' => 'authenticating'];
|
||||
}
|
||||
}
|
||||
}
|
||||
namespace app\common\model {
|
||||
class OperationLog
|
||||
{
|
||||
public array $fields = [];
|
||||
public static array $saved = [];
|
||||
public function __set(string $key, $value): void { $this->fields[$key] = $value; }
|
||||
public function save(): bool { self::$saved[] = $this->fields; return true; }
|
||||
}
|
||||
}
|
||||
namespace app\adminapi\controller {
|
||||
class BaseAdminController
|
||||
{
|
||||
public $request;
|
||||
public int $adminId = 7;
|
||||
public array $adminInfo = ['admin_id' => 7, 'name' => '测试医师'];
|
||||
public function isNotNeedLogin(): bool { return false; }
|
||||
protected function data(array $data): array { return ['code' => 1, 'data' => $data]; }
|
||||
protected function fail(string $message): array { return ['code' => 0, 'msg' => $message]; }
|
||||
}
|
||||
}
|
||||
namespace {
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
require dirname(__DIR__) . '/vendor/topthink/framework/src/helper.php';
|
||||
$app = new think\App(); // No initialize, environment, real DB, credentials or network.
|
||||
$checks = 0;
|
||||
$expect = static function (bool $condition, string $label) use (&$checks): void {
|
||||
if (!$condition) { throw new RuntimeException($label); }
|
||||
++$checks;
|
||||
};
|
||||
$number = '110101199001011237';
|
||||
$controller = new app\adminapi\controller\tcm\PrescriptionController();
|
||||
$request = (new app\Request())->withServer(['REQUEST_METHOD' => 'POST'])->setMethod('POST')->setController('tcm.Prescription')->setAction('esignComplete')
|
||||
->setUrl('/adminapi/tcm.prescription/esignComplete?identity_number=' . $number)
|
||||
->withPost(['id' => 41, 'identity_number' => $number, 'extra' => ['identity_number' => $number]]);
|
||||
$request->controllerObject = $controller;
|
||||
$request->adminInfo = $controller->adminInfo;
|
||||
$controller->request = $request;
|
||||
$result = $controller->esignComplete();
|
||||
$calls = app\common\service\esign\PrescriptionEsignService::$calls;
|
||||
$expect($result['code'] === 1 && $calls[0] === [41, 7, $controller->adminInfo, $number, false], 'POST input forwarded only to current authenticated doctor service');
|
||||
$expect(!str_contains(json_encode($result), $number), 'controller response has no supplemental input');
|
||||
|
||||
think\Container::getInstance()->instance('request', $request);
|
||||
$response = new class($result) {
|
||||
public function __construct(private array $result) {}
|
||||
public function getContent(): string { return json_encode($this->result); }
|
||||
};
|
||||
(new app\adminapi\listener\OperationLog())->handle($response);
|
||||
$audit = app\common\model\OperationLog::$saved[0];
|
||||
$expect(json_decode($audit['params'], true) === ['id' => 41], 'operation audit allowlists prescription id only, including nested malicious inputs');
|
||||
$expect(!str_contains(json_encode($audit), $number) && !str_contains($audit['url'], '?'), 'operation audit removes submitted identity and URL query');
|
||||
|
||||
$controller->request = (new app\Request())->setMethod('POST')->withPost(['id' => 41, 'identity_number' => [$number]]);
|
||||
$expect($controller->esignComplete()['code'] === 0 && count(app\common\service\esign\PrescriptionEsignService::$calls) === 1, 'array identity input rejected without invoking completion');
|
||||
$controller->request = (new app\Request())->setMethod('GET')->withGet(['id' => 41, 'identity_number' => $number]);
|
||||
$expect($controller->esignComplete()['code'] === 0 && count(app\common\service\esign\PrescriptionEsignService::$calls) === 1, 'GET never performs completion');
|
||||
$controller->request = (new app\Request())->setMethod('POST')->withPost(['id' => 42]);
|
||||
$expect($controller->esignComplete()['code'] === 1 && app\common\service\esign\PrescriptionEsignService::$calls[1][3] === '', 'existing complete callers keep optional input compatibility');
|
||||
|
||||
$controller->request = (new app\Request())->setMethod('POST')->withPost(['id' => 42, 'verify_only' => true]);
|
||||
$expect($controller->esignComplete()['code'] === 1 && app\common\service\esign\PrescriptionEsignService::$calls[2][4] === true, 'explicit archive verification flag forwarded');
|
||||
$controller->request = (new app\Request())->setMethod('POST')->withPost(['id' => 42, 'restart_identity' => true]);
|
||||
$expect($controller->esignStart()['code'] === 1 && app\common\service\esign\PrescriptionEsignService::$starts[0][3] === true, 'explicit replacement flag forwarded');
|
||||
foreach ([null, 'true', 'false', 1, [], ['true']] as $invalid) {
|
||||
$controller->request = (new app\Request())->setMethod('POST')->withPost(['id' => 42, 'verify_only' => $invalid, 'restart_identity' => $invalid]);
|
||||
$expect($controller->esignComplete()['code'] === 0 && count(app\common\service\esign\PrescriptionEsignService::$calls) === 3, 'invalid archive verification flag cannot fall through to signing');
|
||||
$expect($controller->esignStart()['code'] === 0 && count(app\common\service\esign\PrescriptionEsignService::$starts) === 1, 'invalid replacement flag cannot change identity flow');
|
||||
}
|
||||
|
||||
$code = '023941';
|
||||
$mobile = '13800000000';
|
||||
$authUrl = 'https://smlt.esign.cn/example/private-auth-url';
|
||||
$controller->request = (new app\Request())->setMethod('POST')->withPost(['id' => 42, 'auth_code' => $code, 'doctor_id' => 41]);
|
||||
$expect($controller->esignVerifyWillingness()['code'] === 1
|
||||
&& app\common\service\esign\PrescriptionEsignService::$verifications === [[42, 7, $controller->adminInfo, $code]], 'OTP verifies only for current authenticated actor; leading zero preserved');
|
||||
$controller->request = (new app\Request())->setMethod('GET')->withGet(['id' => 42, 'auth_code' => $code]);
|
||||
$expect($controller->esignVerifyWillingness()['code'] === 0, 'GET cannot submit an OTP');
|
||||
foreach (['esignVerifyWillingness', 'esignDoctorStart', 'esignDoctorComplete', 'esignDoctorStatus', 'detail'] as $action) {
|
||||
$privacyRequest = (new app\Request())->setMethod('POST')->setController('tcm.Prescription')->setAction($action)
|
||||
->setUrl('/adminapi/tcm.prescription/' . $action . '?mobile=' . $mobile);
|
||||
if ($action !== 'detail') {
|
||||
$privacyRequest->withPost(['id' => 42, 'mobile' => $mobile, 'identity_number' => $number, 'auth_code' => $code]);
|
||||
}
|
||||
$privacyRequest->controllerObject = $controller;
|
||||
$privacyRequest->adminInfo = $controller->adminInfo;
|
||||
think\Container::getInstance()->instance('request', $privacyRequest);
|
||||
$privacyResponse = new class($authUrl) {
|
||||
public function __construct(private string $url) {}
|
||||
public function getContent(): string { return json_encode(['code' => 1, 'data' => ['status' => 'authenticating', 'auth_url' => $this->url]]); }
|
||||
};
|
||||
if ($action === 'detail') {
|
||||
$privacyRequest->setUrl('/adminapi/tcm.prescription/detail');
|
||||
}
|
||||
(new app\adminapi\listener\OperationLog())->handle($privacyResponse);
|
||||
$audit = end(app\common\model\OperationLog::$saved);
|
||||
$entry = json_encode($audit);
|
||||
$expect(!str_contains($entry, $mobile) && !str_contains($entry, $number) && !str_contains($entry, $code)
|
||||
&& !str_contains($audit['result'], 'private-auth-url'), "$action audit omits signing secrets and authorization URL");
|
||||
}
|
||||
echo "eSign identity controller/privacy: $checks checks passed (isolated doubles, no DB/network)\n";
|
||||
}
|
||||
@@ -426,7 +426,7 @@ try {
|
||||
$expect($blankBatch['trigger_type'] === 'blank_to_manual' && (int) $blankBatch['patient_id'] === 100, 'blank hook carries authoritative binding');
|
||||
$expect(\app\adminapi\logic\tcm\PrescriptionLogic::edit($editParams, 1), 'same edit can replay');
|
||||
$expect((int) Db::name('prescription_ai_batch')->where('prescription_id', $blank['id'])->count() === 1, 'same edit does not generate twice');
|
||||
$expect(\app\adminapi\logic\tcm\PrescriptionLogic::void((int) $blank['id'], 1, 'Test'), 'real void hook succeeds');
|
||||
$expect(\app\adminapi\logic\tcm\PrescriptionLogic::void((int) $blank['id'], 1, $root), 'real void hook succeeds');
|
||||
$expect(Db::name('prescription_ai_batch')->where('id', $blankBatch['id'])->value('validity') === 'voided', 'real void hook invalidates');
|
||||
$addParams = ['request_key' => 'add-request-1234567890123456', 'diagnosis_id' => 0, 'patient_id' => 100,
|
||||
'patient_name' => 'fixture', 'gender' => 1, 'age' => 50, 'clinical_diagnosis' => 'fixture',
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -42,6 +42,7 @@ try {
|
||||
$pdo->exec('CREATE TABLE zyt_tcm_prescription (
|
||||
id INT UNSIGNED PRIMARY KEY,creator_id INT,doctor_name VARCHAR(100),patient_name VARCHAR(100),phone VARCHAR(30),gender INT,
|
||||
audit_status INT DEFAULT 0,void_status INT DEFAULT 0,delete_time INT NULL,update_time INT DEFAULT 0,
|
||||
void_time INT NULL,void_by INT NULL,void_by_name VARCHAR(100),
|
||||
is_system_auto INT DEFAULT 0,herbs TEXT,clinical_diagnosis TEXT
|
||||
) ENGINE=InnoDB');
|
||||
$pdo->exec("INSERT INTO zyt_tcm_prescription (id,creator_id,doctor_name) VALUES (1,1,'测试医师')");
|
||||
@@ -54,6 +55,15 @@ try {
|
||||
$pdo->exec(file_get_contents(dirname(__DIR__) . '/database/migrations/2026_04_07_create_tcm_prescription_order.sql'));
|
||||
$pdo->exec('CREATE TABLE zyt_pharmacy_submission_claim (id INT PRIMARY KEY,prescription_order_id INT,source_revision INT,status VARCHAR(40))');
|
||||
Db::name('tcm_prescription_order')->insert(['id' => 1, 'order_no' => 'TEST-ESIGN', 'prescription_id' => 2, 'prescription_audit_status' => 0, 'fulfillment_status' => 0]);
|
||||
Db::name('tcm_prescription_order')->insert(['id' => 2, 'order_no' => 'TEST-LEGACY-PENDING', 'prescription_id' => 1, 'prescription_audit_status' => 0, 'fulfillment_status' => 0]);
|
||||
$expect(PrescriptionLogic::audit(1, 'approve', '', 1, $root) === false, 'unmarked pending prescription requires signature after enablement');
|
||||
$expect(PrescriptionOrderLogic::auditPrescription(2, 'approve', '', 1, $root) === false, 'order audit also gates an unmarked pending prescription');
|
||||
$expect(PrescriptionOrderLogic::addLog(['id' => 2, 'summary' => '测试', 'prescription_audit_status' => 1], 1, $root) === false,
|
||||
'manual order status cannot bypass a required signature on an unmarked draft');
|
||||
$expect(Db::name('tcm_prescription')->find(1) === $row, 'approval attempts do not enroll or modify an unsigned prescription');
|
||||
$pdo->exec("INSERT INTO zyt_tcm_prescription (id,creator_id,doctor_name,audit_status) VALUES (3,1,'测试医师',1)");
|
||||
PrescriptionEsignService::assertSignedById(3);
|
||||
$expect(PrescriptionEsignService::describe(Db::name('tcm_prescription')->find(3), 1)['status'] === 'legacy', 'previously approved historical prescription remains on record');
|
||||
$expect(PrescriptionLogic::audit(2, 'approve', '', 1, $root) === false, 'manual prescription audit rejects unsigned');
|
||||
$expect(str_contains(PrescriptionLogic::getError(), '电子签署'), 'manual audit explains signature requirement');
|
||||
$expect(PrescriptionOrderLogic::auditPrescription(1, 'approve', '', 1, $root) === false, 'order audit rejects unsigned before write');
|
||||
@@ -112,6 +122,14 @@ try {
|
||||
$expect(PrescriptionOrderLogic::auditPrescription(1, 'approve', '', 1, $root) === false && PrescriptionOrderLogic::getError() === 'TEST_LOCK_OBSERVED', 'order audit reaches locked write');
|
||||
$expect(PrescriptionOrderLogic::addLog(['id' => 1, 'summary' => '测试', 'prescription_audit_status' => 1], 1, $root) === false && PrescriptionOrderLogic::getError() === 'TEST_LOCK_OBSERVED', 'manual status change reaches locked write');
|
||||
$expect($events->attempts === 3 && (int) Db::name('tcm_prescription')->where('id', 2)->value('void_status') === 0, 'all concurrent void attempts blocked');
|
||||
\think\Model::setEvent(null);
|
||||
Db::name('tcm_prescription_order')->where('id', 1)->update(['fulfillment_status' => 4]);
|
||||
$pdo->exec("INSERT INTO zyt_pharmacy_submission_claim VALUES (1, 1, 1, 'FAILED'), (2, 1, 2, 'PENDING')");
|
||||
$expect(!PrescriptionLogic::void(2, 1, $root) && str_contains(PrescriptionLogic::getError(), '提交药房'),
|
||||
'void locks and checks the latest pharmacy claim on a released order');
|
||||
Db::name('pharmacy_submission_claim')->where('id', 2)->update(['status' => 'FAILED']);
|
||||
$expect(PrescriptionLogic::void(2, 1, $root), 'void succeeds when the released order has no active claim');
|
||||
$expect(PrescriptionEsignService::download(2, 1, $root)['sha256'] === hash('sha256', $pdf), 'void preserves downloadable signed evidence');
|
||||
echo "Prescription eSign MySQL migration and business gates: $checks checks passed\n";
|
||||
} finally {
|
||||
\think\Model::setEvent(null);
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 99 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 112 KiB |
Reference in New Issue
Block a user