Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
db6d327e91 | ||
|
|
0dc41a1507 | ||
|
|
378bf32069 |
@@ -28,6 +28,8 @@ app/.test-tmp-stream/
|
||||
/.codex
|
||||
/.agents
|
||||
/server/.spool
|
||||
/server/storage/esign/
|
||||
/server/.env.esign.local
|
||||
# Generated ancient-books search indexes; the source corpus is tracked.
|
||||
/server/knowledge/tcm-ancient-books-index.json
|
||||
/server/knowledge/tcm-ancient-books-index/
|
||||
|
||||
@@ -373,6 +373,159 @@ export function getMsgAuditPermitUsers() {
|
||||
|
||||
// ========== 中医处方单 ==========
|
||||
|
||||
export interface PrescriptionEsignConfig {
|
||||
enabled: boolean
|
||||
environment: 'sandbox' | 'production'
|
||||
verification_method?: 'sms' | 'quick'
|
||||
review_enabled?: boolean
|
||||
}
|
||||
|
||||
export interface PrescriptionEsignStatus extends PrescriptionEsignConfig {
|
||||
required: boolean
|
||||
status: 'pending' | 'authenticating' | 'signing' | 'signed' | 'failed' | 'uncertain' | 'voided' | 'legacy'
|
||||
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
|
||||
}
|
||||
|
||||
export interface PrescriptionEsignFile {
|
||||
filename: string
|
||||
content_base64: string
|
||||
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' })
|
||||
}
|
||||
|
||||
export function prescriptionEsignStatus(params: { id: number }): Promise<PrescriptionEsignStatus> {
|
||||
return request.get({ url: '/tcm.prescription/esignStatus', params })
|
||||
}
|
||||
|
||||
/** 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 prescriptionEsignVerifyWillingness(params: { id: number; auth_code: string }): Promise<PrescriptionEsignIdentityStatus> {
|
||||
return request.post(
|
||||
{ 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 }
|
||||
)
|
||||
}
|
||||
|
||||
export function prescriptionEsignDownload(params: { id: number }): Promise<PrescriptionEsignFile> {
|
||||
return request.get({ url: '/tcm.prescription/esignDownload', params, timeout: 60000 })
|
||||
}
|
||||
|
||||
// 处方列表
|
||||
export function prescriptionLists(params: any) {
|
||||
return request.get({ url: '/tcm.prescription/lists', params })
|
||||
|
||||
@@ -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>
|
||||
@@ -0,0 +1,694 @@
|
||||
<template>
|
||||
<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="confirmed && state?.environment === 'sandbox' && state.status !== 'legacy'" type="warning" size="small">
|
||||
沙箱测试
|
||||
</el-tag>
|
||||
</div>
|
||||
<el-steps v-if="(confirmed || busy) && state?.required && state.status !== 'voided' && (!audit || state.can_sign || state.can_retry_verify)" :active="activeStep" finish-status="success" simple>
|
||||
<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="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, 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 {
|
||||
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)
|
||||
}
|
||||
|
||||
function initialStatus(): PrescriptionEsignStatus | null {
|
||||
try {
|
||||
return validateEsignStatus(props.initialState)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
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 || '请查询签署状态,核对快捷签授权。'
|
||||
}
|
||||
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 ? '请查询短信验证状态。' : '请将本张处方的验证码发送到医生绑定的手机号。'
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
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 (!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 {
|
||||
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 {
|
||||
if (isCurrent(current, id)) work.value = null
|
||||
}
|
||||
}
|
||||
|
||||
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()
|
||||
}
|
||||
|
||||
watch(() => props.prescriptionId, resetStatus, { immediate: true })
|
||||
watch(() => props.initialState, (value) => {
|
||||
// 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-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>
|
||||
@@ -510,7 +510,12 @@
|
||||
</el-form-item>
|
||||
</el-col>
|
||||
<el-col :span="24">
|
||||
<el-form-item label="医师签名" prop="doctor_signature" required>
|
||||
<el-alert v-if="esignError" type="error" :closable="false" class="mb-3">
|
||||
{{ 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' ? '沙箱测试。保存草稿后,由开方医生本人确认签署。' : '保存草稿后,由开方医生本人确认签署。'" />
|
||||
<el-form-item v-else-if="esignReady" label="医师签名" prop="doctor_signature" required>
|
||||
<div class="signature-pad-wrap">
|
||||
<canvas
|
||||
ref="signatureCanvasRef"
|
||||
@@ -534,6 +539,13 @@
|
||||
</div>
|
||||
|
||||
<div v-else class="rx-wrap">
|
||||
<EsignPrescriptionPanel
|
||||
v-if="visible"
|
||||
:key="savedPrescription.id"
|
||||
:prescription-id="Number(savedPrescription.id)"
|
||||
:initial-state="savedPrescription.esign"
|
||||
@status-change="onEsignStatusChange"
|
||||
/>
|
||||
<div class="rx-toolbar">
|
||||
<el-tag v-if="savedPrescription.void_status === 1" type="danger" size="small">已作废</el-tag>
|
||||
<el-tag v-else-if="approvedPreviewOnly" type="success" size="small">已通过</el-tag>
|
||||
@@ -679,13 +691,14 @@
|
||||
</div>
|
||||
|
||||
<div class="flex justify-end gap-2 mt-4">
|
||||
<el-button @click="handleDownloadImage">
|
||||
<el-button v-if="!requiresOriginalEsignPdf(savedPrescription.esign)" @click="handleDownloadImage">
|
||||
<el-icon><Download /></el-icon>
|
||||
下载图片
|
||||
</el-button>
|
||||
<el-button type="primary" @click="handleDownloadPdf">
|
||||
<el-button type="primary" @click="handleDownloadPdf"
|
||||
:disabled="requiresOriginalEsignPdf(savedPrescription.esign) && !savedPrescription.esign?.can_download">
|
||||
<el-icon><Document /></el-icon>
|
||||
下载PDF
|
||||
{{ requiresOriginalEsignPdf(savedPrescription.esign) ? '下载已签原始 PDF' : '下载PDF' }}
|
||||
</el-button>
|
||||
<el-tooltip
|
||||
v-if="savedPrescription.void_status !== 1 && !approvedPreviewOnly"
|
||||
@@ -713,7 +726,9 @@
|
||||
<template v-if="!savedPrescription" #footer>
|
||||
<div class="flex justify-end gap-2">
|
||||
<el-button @click="handleClose">取消</el-button>
|
||||
<el-button type="primary" @click="handleSave" :loading="saving">保存处方</el-button>
|
||||
<el-button type="primary" @click="handleSave" :loading="saving || esignLoading" :disabled="!esignReady">
|
||||
{{ esignEnabled ? '保存处方草稿' : '保存处方' }}
|
||||
</el-button>
|
||||
</div>
|
||||
</template>
|
||||
</el-drawer>
|
||||
@@ -860,6 +875,10 @@ import { prescriptionAdd, prescriptionDetail, prescriptionGetByAppointment, pres
|
||||
import { medicineLists } from '@/api/medicine'
|
||||
import { getDictData } from '@/api/app'
|
||||
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 type { PrescriptionEsignStatus } from '@/api/tcm'
|
||||
import html2canvas from 'html2canvas'
|
||||
import { jsPDF } from 'jspdf'
|
||||
import useUserStore from '@/stores/modules/user'
|
||||
@@ -1043,6 +1062,12 @@ const signatureActivePointerId = ref<number | null>(null)
|
||||
const SIGNATURE_CSS_W = 560
|
||||
const SIGNATURE_CSS_H = 168
|
||||
const savedPrescription = ref<any>(null)
|
||||
const { config: esignConfig, enabled: esignEnabled, ready: esignReady, loading: esignLoading, error: esignError, load: loadEsignConfig } = usePrescriptionEsignConfig()
|
||||
|
||||
const onEsignStatusChange = (state: PrescriptionEsignStatus) => {
|
||||
if (savedPrescription.value) savedPrescription.value.esign = state
|
||||
emit('success')
|
||||
}
|
||||
/** 预览联次:药房联 / 处方联(与消费者处方查看一致) */
|
||||
const prescriptionTabType = ref<'internal' | 'user'>('internal') // 保留兼容 openPreview options.slipType
|
||||
/** 诊单列表「查看」仅展示处方联,不展示详细病历 A3 */
|
||||
@@ -1661,6 +1686,7 @@ const open = async (data: any, options?: { templateId?: number; stationName?: st
|
||||
}
|
||||
|
||||
await loadDictOptions()
|
||||
await loadEsignConfig()
|
||||
|
||||
const appointmentId = Number(data.id ?? data.appointment_id ?? 0)
|
||||
if (appointmentId) {
|
||||
@@ -2032,6 +2058,9 @@ watch(() => formData.prescription_type, (newType) => {
|
||||
})
|
||||
|
||||
const handleSave = async () => {
|
||||
if (saving.value) return
|
||||
if (!esignReady.value && !(await loadEsignConfig())) return
|
||||
if (saving.value) return
|
||||
if (!formData.clinical_diagnosis?.trim()) {
|
||||
feedback.msgWarning('请输入临床诊断')
|
||||
return
|
||||
@@ -2056,7 +2085,7 @@ const handleSave = async () => {
|
||||
}
|
||||
}
|
||||
|
||||
if (!formData.doctor_signature?.trim()) {
|
||||
if (!esignEnabled.value && !formData.doctor_signature?.trim()) {
|
||||
feedback.msgWarning('请使用电子签名板手写医师签名')
|
||||
return
|
||||
}
|
||||
@@ -2103,8 +2132,19 @@ const handleSave = async () => {
|
||||
})
|
||||
const id = res?.id
|
||||
if (id) {
|
||||
const detail = await prescriptionDetail({ id })
|
||||
savedPrescription.value = detail
|
||||
// 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 ? '处方草稿已保存' : '处方已保存')
|
||||
try {
|
||||
const detail = await prescriptionDetail({ id })
|
||||
if (savedPrescription.value?.id === id) {
|
||||
savedPrescription.value = { ...detail, esign: savedPrescription.value.esign ?? detail.esign }
|
||||
}
|
||||
} catch {
|
||||
if (savedPrescription.value?.id === id) {
|
||||
feedback.msgWarning(res.esign?.required ? '处方详情暂未加载,可继续操作' : '处方已保存,详情暂未加载,可从已开处方继续签署')
|
||||
}
|
||||
}
|
||||
emit('success')
|
||||
} else {
|
||||
feedback.msgError('保存失败')
|
||||
@@ -2156,6 +2196,7 @@ const fetchCaseRecord = async (diagnosisId: number) => {
|
||||
}
|
||||
|
||||
const handleNewPrescription = async () => {
|
||||
await loadEsignConfig()
|
||||
const saved = savedPrescription.value
|
||||
if (saved) {
|
||||
// 将患者信息、诊断信息填入表单,新建处方时保留
|
||||
@@ -2273,6 +2314,7 @@ const handleDownloadImage = async () => {
|
||||
|
||||
const handleDownloadPdf = async () => {
|
||||
try {
|
||||
if (await downloadPrescriptionPdfIfRequired(Number(savedPrescription.value?.id))) return
|
||||
const canvas = await captureElement()
|
||||
const imgData = canvas.toDataURL('image/png')
|
||||
const pdf = new jsPDF({
|
||||
@@ -2301,8 +2343,8 @@ const handleDownloadPdf = async () => {
|
||||
|
||||
pdf.save(`处方_${savedPrescription.value?.patient_name || '未命名'}_${Date.now()}.pdf`)
|
||||
feedback.msgSuccess('PDF已下载')
|
||||
} catch (e) {
|
||||
feedback.msgError('下载PDF失败')
|
||||
} catch (e: any) {
|
||||
feedback.msgError(e?.message || '下载PDF失败')
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { computed, ref } from 'vue'
|
||||
import { prescriptionEsignConfig, type PrescriptionEsignConfig } from '@/api/tcm'
|
||||
|
||||
/** A failed capability lookup must not silently switch a prescription to handwritten signing. */
|
||||
export function usePrescriptionEsignConfig() {
|
||||
const config = ref<PrescriptionEsignConfig | null>(null)
|
||||
const loading = ref(false)
|
||||
const error = ref('')
|
||||
let request: Promise<boolean> | null = null
|
||||
|
||||
function load(): Promise<boolean> {
|
||||
if (request) return request
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
request = prescriptionEsignConfig()
|
||||
.then((value) => {
|
||||
if (typeof value?.enabled !== 'boolean' || !['sandbox', 'production'].includes(value.environment)) {
|
||||
throw new Error('Invalid signing configuration')
|
||||
}
|
||||
config.value = value
|
||||
return true
|
||||
})
|
||||
.catch(() => {
|
||||
config.value = null
|
||||
error.value = '签署配置加载失败,请重试后保存处方'
|
||||
return false
|
||||
})
|
||||
.finally(() => {
|
||||
loading.value = false
|
||||
request = null
|
||||
})
|
||||
return request
|
||||
}
|
||||
|
||||
return {
|
||||
config,
|
||||
enabled: computed(() => config.value?.enabled === true),
|
||||
ready: computed(() => config.value !== null),
|
||||
loading,
|
||||
error,
|
||||
load
|
||||
}
|
||||
}
|
||||
@@ -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) => {
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
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 {
|
||||
const url = new URL(value)
|
||||
const hosts = ['smlt.esign.cn', 'smlfront.esign.cn', 't.esign.cn', 'idverify.esign.cn']
|
||||
const allowedPort = !url.port || (url.hostname === 'smlfront.esign.cn' && url.port === '8890')
|
||||
return url.protocol === 'https:' && hosts.includes(url.hostname) && allowedPort && !url.username && !url.password ? url.href : ''
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
export function validateEsignStatus(value: unknown): PrescriptionEsignStatus {
|
||||
const state = value as PrescriptionEsignStatus | null
|
||||
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')
|
||||
|| (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)
|
||||
return value.required || value.status !== 'legacy' || value.can_download
|
||||
} catch {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
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('签署文件缺少有效校验信息')
|
||||
if (!globalThis.crypto?.subtle) throw new Error('请通过 HTTPS 访问,以校验签署文件')
|
||||
let bytes: Uint8Array
|
||||
try {
|
||||
bytes = Uint8Array.from(atob(file.content_base64), (c) => c.charCodeAt(0))
|
||||
} catch {
|
||||
throw new Error('签署文件内容无效,请重新下载')
|
||||
}
|
||||
if (String.fromCharCode(...bytes.subarray(0, 5)) !== '%PDF-') {
|
||||
throw new Error('签署文件不是有效 PDF,请重新下载')
|
||||
}
|
||||
const digest = await crypto.subtle.digest('SHA-256', bytes)
|
||||
const hash = Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, '0')).join('')
|
||||
if (hash !== file.sha256.toLowerCase()) throw new Error('签署文件校验失败,已停止下载,请重试')
|
||||
return bytes
|
||||
}
|
||||
|
||||
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
|
||||
link.download = (file.filename || `处方_${id}_已签.pdf`).replace(/[\\/:*?"<>|\u0000-\u001f]/g, '_')
|
||||
document.body.appendChild(link)
|
||||
link.click()
|
||||
link.remove()
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000)
|
||||
}
|
||||
|
||||
/** Legacy exports may render locally; every other state must preserve the server's original. */
|
||||
export async function downloadPrescriptionPdfIfRequired(id: number): Promise<boolean> {
|
||||
if (!Number.isInteger(id) || id <= 0) throw new Error('缺少处方编号,无法核对签署状态')
|
||||
const status = validateEsignStatus(await prescriptionEsignStatus({ id }))
|
||||
if (!requiresOriginalEsignPdf(status)) return false
|
||||
if (!status.can_download) throw new Error(status.message || '处方尚未签署完成,请完成签署后下载')
|
||||
await downloadOriginalEsignPdf(id)
|
||||
return true
|
||||
}
|
||||
@@ -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,10 +282,18 @@
|
||||
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="showEdit && slipView?.id && !viewDetailLoading"
|
||||
:key="slipView.id"
|
||||
:prescription-id="Number(slipView.id)"
|
||||
:initial-state="slipView.esign"
|
||||
@status-change="onEsignStatusChange"
|
||||
/>
|
||||
<!-- 顶部工具栏(不打印 / 不下载) -->
|
||||
<div class="rx-toolbar">
|
||||
<el-tag
|
||||
@@ -308,16 +319,27 @@
|
||||
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 :icon="Printer" size="small" @click="handlePrintSlip">打印</el-button>
|
||||
<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"
|
||||
:icon="Download"
|
||||
size="small"
|
||||
:loading="downloadingSlip"
|
||||
:disabled="viewDetailLoading || (requiresOriginalEsignPdf(slipView?.esign) && !slipView?.esign?.can_download)"
|
||||
@click="handleDownloadSlip"
|
||||
>
|
||||
下载 PDF (A4)
|
||||
{{ requiresOriginalEsignPdf(slipView?.esign) ? '下载已签原始 PDF' : '下载 PDF (A4)' }}
|
||||
</el-button>
|
||||
</div>
|
||||
|
||||
@@ -984,7 +1006,12 @@
|
||||
<el-input v-model="editForm.doctor_name" placeholder="请输入医师姓名" />
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="医师签名" prop="doctor_signature" required>
|
||||
<el-alert v-if="esignError" type="error" :closable="false" class="mb-3">
|
||||
{{ 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' ? '沙箱测试。保存草稿后,由开方医生本人确认签署。' : '保存草稿后,由开方医生本人确认签署。'" />
|
||||
<el-form-item v-else-if="esignReady" label="医师签名" prop="doctor_signature" required>
|
||||
<div class="signature-pad-wrap">
|
||||
<canvas
|
||||
ref="signatureCanvasRef"
|
||||
@@ -1009,8 +1036,8 @@
|
||||
</template>
|
||||
<template v-else>
|
||||
<el-button @click="showEdit = false">取消</el-button>
|
||||
<el-button type="primary" @click="handleSubmit" :loading="submitLoading">
|
||||
确定
|
||||
<el-button type="primary" @click="handleSubmit" :loading="submitLoading || esignLoading" :disabled="!esignReady">
|
||||
{{ esignEnabled ? '保存处方草稿' : '确定' }}
|
||||
</el-button>
|
||||
</template>
|
||||
</template>
|
||||
@@ -1531,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>
|
||||
@@ -1548,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>
|
||||
@@ -1584,9 +1620,13 @@ import type { FormInstance, FormRules } from 'element-plus'
|
||||
import DaterangePicker from '@/components/daterange-picker/index.vue'
|
||||
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 { 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'
|
||||
|
||||
@@ -1726,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')
|
||||
@@ -1768,6 +1809,12 @@ const SIGNATURE_CSS_W = 560
|
||||
const SIGNATURE_CSS_H = 168
|
||||
/** 查看模式:处方笺数据源(先列表行,再详情覆盖) */
|
||||
const slipView = ref<Record<string, any> | null>(null)
|
||||
const { config: esignConfig, enabled: esignEnabled, ready: esignReady, loading: esignLoading, error: esignError, load: loadEsignConfig } = usePrescriptionEsignConfig()
|
||||
|
||||
const onEsignStatusChange = (state: PrescriptionEsignStatus) => {
|
||||
if (slipView.value) slipView.value.esign = state
|
||||
void getLists()
|
||||
}
|
||||
const viewDetailLoading = ref(false)
|
||||
|
||||
const roleOptions = ref<Array<{ id: number; name: string }>>([])
|
||||
@@ -1776,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)
|
||||
@@ -2622,6 +2674,16 @@ function handlePrintSlip() {
|
||||
|
||||
/* === 下载 PDF(A4) === */
|
||||
async function handleDownloadSlip() {
|
||||
if (downloadingSlip.value) return
|
||||
downloadingSlip.value = true
|
||||
try {
|
||||
if (await downloadPrescriptionPdfIfRequired(Number(slipView.value?.id))) return
|
||||
} catch (e: any) {
|
||||
feedback.msgError(e?.message || '下载签署文件失败')
|
||||
return
|
||||
} finally {
|
||||
downloadingSlip.value = false
|
||||
}
|
||||
const node = getRxPaperEl()
|
||||
if (!node) {
|
||||
feedback.msgWarning('处方笺尚未渲染完成')
|
||||
@@ -2881,7 +2943,7 @@ const rules: FormRules = {
|
||||
{
|
||||
required: true,
|
||||
validator: (_rule, v, cb) => {
|
||||
if (!v || !String(v).trim()) {
|
||||
if (!esignEnabled.value && (!v || !String(v).trim())) {
|
||||
cb(new Error('请使用电子签名板手写医师签名'))
|
||||
} else {
|
||||
cb()
|
||||
@@ -3061,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)
|
||||
@@ -3269,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
|
||||
@@ -3292,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 {
|
||||
/* 拦截器已提示 */
|
||||
@@ -3684,6 +3769,7 @@ const resetForm = () => {
|
||||
|
||||
// 新增处方
|
||||
const handleAdd = () => {
|
||||
void loadEsignConfig()
|
||||
resetForm()
|
||||
editForm.doctor_name = String(userStore.userInfo?.name || '')
|
||||
editingWasVoid.value = false
|
||||
@@ -3723,6 +3809,7 @@ const handleView = async (row: any) => {
|
||||
|
||||
// 编辑处方
|
||||
const handleEdit = async (row: any) => {
|
||||
await loadEsignConfig()
|
||||
editingWasVoid.value = Number(row.void_status) === 1
|
||||
editingWasRejected.value = Number(row.audit_status) === 2
|
||||
editMode.value = 'edit'
|
||||
@@ -3823,6 +3910,8 @@ const handleEdit = async (row: any) => {
|
||||
|
||||
// 提交表单
|
||||
const handleSubmit = async () => {
|
||||
if (submitLoading.value) return
|
||||
if (!esignReady.value && !(await loadEsignConfig())) return
|
||||
if (!formRef.value) return
|
||||
|
||||
try {
|
||||
@@ -3831,6 +3920,7 @@ const handleSubmit = async () => {
|
||||
// Element Plus:校验失败会 reject,表单项已展示错误,勿再向外抛成 Uncaught
|
||||
return
|
||||
}
|
||||
if (submitLoading.value) return
|
||||
|
||||
// 验证药材
|
||||
if (!editForm.herbs || editForm.herbs.length === 0) {
|
||||
@@ -3856,16 +3946,21 @@ const handleSubmit = async () => {
|
||||
try {
|
||||
const params: Record<string, unknown> = { ...editForm }
|
||||
|
||||
let result: any
|
||||
if (editMode.value === 'add') {
|
||||
params.audit_status = 0
|
||||
await prescriptionAdd(params)
|
||||
feedback.msgSuccess('添加成功,已提交审核')
|
||||
result = await prescriptionAdd(params)
|
||||
} else {
|
||||
await prescriptionEdit(params)
|
||||
feedback.msgSuccess('保存成功,处方已重新进入待审核')
|
||||
result = await prescriptionEdit(params)
|
||||
}
|
||||
|
||||
showEdit.value = false
|
||||
if (esignEnabled.value || requiresOriginalEsignPdf(result?.esign)) {
|
||||
const id = Number(result?.id || editForm.id)
|
||||
feedback.msgSuccess(result?.esign?.required ? '处方草稿已保存' : '处方已保存,请核对电子签署状态')
|
||||
await handleView({ ...editForm, id, audit_status: 0, esign: result?.esign })
|
||||
} else {
|
||||
feedback.msgSuccess('保存成功,处方已进入待审核')
|
||||
showEdit.value = false
|
||||
}
|
||||
getLists()
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
@@ -3894,6 +3989,7 @@ onActivated(() => {
|
||||
})
|
||||
|
||||
onMounted(async () => {
|
||||
void loadEsignConfig()
|
||||
await loadRoleOptions()
|
||||
await loadRegionData()
|
||||
await loadServicePackageOptions()
|
||||
@@ -3911,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">
|
||||
@@ -1786,6 +1797,7 @@
|
||||
<el-button
|
||||
size="small"
|
||||
:loading="prescriptionSlipExporting"
|
||||
v-if="!requiresOriginalEsignPdf(prescriptionViewData.esign)"
|
||||
@click="downloadPrescriptionSlipImage"
|
||||
>
|
||||
下载图片
|
||||
@@ -1793,9 +1805,10 @@
|
||||
<el-button
|
||||
size="small"
|
||||
:loading="prescriptionSlipExporting"
|
||||
:disabled="requiresOriginalEsignPdf(prescriptionViewData.esign) && !prescriptionViewData.esign?.can_download"
|
||||
@click="downloadPrescriptionSlipPdf"
|
||||
>
|
||||
下载PDF
|
||||
{{ requiresOriginalEsignPdf(prescriptionViewData.esign) ? '下载已签原始 PDF' : '下载PDF' }}
|
||||
</el-button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -1860,6 +1873,13 @@
|
||||
<div v-if="prescriptionViewData.audit_remark" class="mt-1">驳回意见:{{ prescriptionViewData.audit_remark }}</div>
|
||||
</div>
|
||||
|
||||
<EsignPrescriptionPanel
|
||||
v-if="prescriptionViewVisible && prescriptionViewData && !prescriptionViewLoading"
|
||||
:key="prescriptionViewData.id"
|
||||
:prescription-id="Number(prescriptionViewData.id)"
|
||||
:initial-state="prescriptionViewData.esign"
|
||||
@status-change="prescriptionViewData.esign = $event"
|
||||
/>
|
||||
<PrescriptionSlip
|
||||
v-if="prescriptionViewData"
|
||||
ref="rxSlipRef"
|
||||
@@ -2128,6 +2148,9 @@ import {
|
||||
getAssistants
|
||||
} from '@/api/tcm'
|
||||
import PrescriptionSlip from '@/components/prescription-slip/index.vue'
|
||||
import EsignPrescriptionPanel from '@/components/EsignPrescriptionPanel.vue'
|
||||
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'
|
||||
@@ -3694,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
|
||||
@@ -3928,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)
|
||||
})
|
||||
|
||||
// ─── 快捷填写快递单号 ────────────────────────────────────────────
|
||||
@@ -5110,6 +5144,7 @@ async function downloadPrescriptionSlipPdf() {
|
||||
if (!prescriptionViewData.value) return
|
||||
prescriptionSlipExporting.value = true
|
||||
try {
|
||||
if (await downloadPrescriptionPdfIfRequired(Number(prescriptionViewData.value.id))) return
|
||||
const canvas = await capturePrescriptionSlipCanvas()
|
||||
const imgData = canvas.toDataURL('image/jpeg', 0.95)
|
||||
/**
|
||||
@@ -5141,8 +5176,8 @@ async function downloadPrescriptionSlipPdf() {
|
||||
}
|
||||
pdf.save(`${slipDownloadBaseName()}.pdf`)
|
||||
feedback.msgSuccess('PDF已下载')
|
||||
} catch {
|
||||
feedback.msgError('下载PDF失败')
|
||||
} catch (e: any) {
|
||||
feedback.msgError(e?.message || '下载PDF失败')
|
||||
} finally {
|
||||
prescriptionSlipExporting.value = false
|
||||
}
|
||||
|
||||
@@ -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">
|
||||
@@ -2386,6 +2397,7 @@
|
||||
<el-button
|
||||
size="small"
|
||||
:loading="prescriptionSlipExporting"
|
||||
v-if="!requiresOriginalEsignPdf(prescriptionViewData.esign)"
|
||||
@click="downloadPrescriptionSlipImage"
|
||||
>
|
||||
下载图片
|
||||
@@ -2393,9 +2405,10 @@
|
||||
<el-button
|
||||
size="small"
|
||||
:loading="prescriptionSlipExporting"
|
||||
:disabled="requiresOriginalEsignPdf(prescriptionViewData.esign) && !prescriptionViewData.esign?.can_download"
|
||||
@click="downloadPrescriptionSlipPdf"
|
||||
>
|
||||
下载PDF
|
||||
{{ requiresOriginalEsignPdf(prescriptionViewData.esign) ? '下载已签原始 PDF' : '下载PDF' }}
|
||||
</el-button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -2460,6 +2473,13 @@
|
||||
<div v-if="prescriptionViewData.audit_remark" class="mt-1">驳回意见:{{ prescriptionViewData.audit_remark }}</div>
|
||||
</div>
|
||||
|
||||
<EsignPrescriptionPanel
|
||||
v-if="prescriptionViewVisible && prescriptionViewData && !prescriptionViewLoading"
|
||||
:key="prescriptionViewData.id"
|
||||
:prescription-id="Number(prescriptionViewData.id)"
|
||||
:initial-state="prescriptionViewData.esign"
|
||||
@status-change="prescriptionViewData.esign = $event"
|
||||
/>
|
||||
<PrescriptionSlip
|
||||
v-if="prescriptionViewData"
|
||||
ref="rxSlipRef"
|
||||
@@ -2633,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,
|
||||
@@ -2691,6 +2712,9 @@ import {
|
||||
supplyModeTagType
|
||||
} from './components/prescription-order-utils'
|
||||
import PrescriptionSlip from '@/components/prescription-slip/index.vue'
|
||||
import EsignPrescriptionPanel from '@/components/EsignPrescriptionPanel.vue'
|
||||
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'
|
||||
@@ -4654,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
|
||||
@@ -4853,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)
|
||||
})
|
||||
|
||||
// ─── 快捷填写快递单号 ────────────────────────────────────────────
|
||||
@@ -5858,6 +5894,7 @@ async function downloadPrescriptionSlipPdf() {
|
||||
if (!prescriptionViewData.value) return
|
||||
prescriptionSlipExporting.value = true
|
||||
try {
|
||||
if (await downloadPrescriptionPdfIfRequired(Number(prescriptionViewData.value.id))) return
|
||||
const canvas = await capturePrescriptionSlipCanvas()
|
||||
const imgData = canvas.toDataURL('image/jpeg', 0.95)
|
||||
/**
|
||||
@@ -5889,8 +5926,8 @@ async function downloadPrescriptionSlipPdf() {
|
||||
}
|
||||
pdf.save(`${slipDownloadBaseName()}.pdf`)
|
||||
feedback.msgSuccess('PDF已下载')
|
||||
} catch {
|
||||
feedback.msgError('下载PDF失败')
|
||||
} catch (e: any) {
|
||||
feedback.msgError(e?.message || '下载PDF失败')
|
||||
} finally {
|
||||
prescriptionSlipExporting.value = false
|
||||
}
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
"""Server-authoritative electronic signature DTOs and original-file validation."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import binascii
|
||||
import hashlib
|
||||
import hmac
|
||||
import re
|
||||
from collections.abc import Mapping
|
||||
from typing import Any
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from .errors import ApiProtocolError
|
||||
|
||||
ESIGN_LABELS = {
|
||||
"pending": "待签署",
|
||||
"authenticating": "待完成核身",
|
||||
"signing": "签署中",
|
||||
"signed": "已签署",
|
||||
"failed": "签署失败",
|
||||
"uncertain": "签署结果待确认",
|
||||
"voided": "已失效",
|
||||
"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)
|
||||
|
||||
|
||||
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"))
|
||||
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()
|
||||
try:
|
||||
parts = urlsplit(url)
|
||||
valid = (
|
||||
parts.scheme == "https"
|
||||
and parts.hostname in {"smlt.esign.cn", "smlfront.esign.cn", "t.esign.cn", "idverify.esign.cn"}
|
||||
and not parts.username
|
||||
and not parts.password
|
||||
and (parts.port in (None, 443) or (parts.hostname == "smlfront.esign.cn" and parts.port == 8890))
|
||||
and not any(ord(char) < 32 or char == "\\" for char in url)
|
||||
)
|
||||
except ValueError:
|
||||
valid = False
|
||||
if not valid:
|
||||
raise ValueError("核身链接无效,请重新查询签署状态。")
|
||||
return url
|
||||
|
||||
|
||||
def signed_pdf_bytes(value: Any) -> bytes:
|
||||
if not isinstance(value, Mapping):
|
||||
raise ApiProtocolError("已签原件数据格式不正确")
|
||||
try:
|
||||
content = base64.b64decode(value.get("content_base64", ""), validate=True)
|
||||
except (ValueError, TypeError, binascii.Error) as error:
|
||||
raise ApiProtocolError("已签原件编码不正确") from error
|
||||
expected = str(value.get("sha256") or "").lower()
|
||||
if not content.startswith(b"%PDF-") or not hmac.compare_digest(
|
||||
hashlib.sha256(content).hexdigest(), expected
|
||||
):
|
||||
raise ApiProtocolError("已签原件校验失败,请重试下载")
|
||||
return content
|
||||
@@ -614,6 +614,7 @@ class Prescription:
|
||||
aux_usage: JSONDict = field(default_factory=dict)
|
||||
doctor_name: str = ""
|
||||
doctor_signature: str = ""
|
||||
esign: JSONDict = field(default_factory=dict)
|
||||
creator_id: int | None = None
|
||||
assistant_name: str = ""
|
||||
is_system_auto: bool = False
|
||||
@@ -687,6 +688,7 @@ class Prescription:
|
||||
aux_usage=dict(_mapping(source.get("aux_usage"))),
|
||||
doctor_name=_text(source.get("doctor_name")),
|
||||
doctor_signature=_text(source.get("doctor_signature")),
|
||||
esign=dict(_mapping(source.get("esign"))),
|
||||
creator_id=_integer(source.get("creator_id"), None),
|
||||
assistant_name=_text(source.get("assistant_name")),
|
||||
is_system_auto=_boolean(source.get("is_system_auto")),
|
||||
@@ -764,6 +766,7 @@ class Prescription:
|
||||
"aux_usage": dict(self.aux_usage),
|
||||
"doctor_name": self.doctor_name,
|
||||
"doctor_signature": self.doctor_signature,
|
||||
"esign": dict(self.esign),
|
||||
"is_shared": int(self.is_shared),
|
||||
"visible_role_ids": list(self.visible_role_ids),
|
||||
"audit_status": self.audit_status,
|
||||
|
||||
@@ -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."""
|
||||
@@ -1303,8 +1307,59 @@ class DemoDoctorRepository:
|
||||
with self._lock:
|
||||
for prescription in self._prescriptions:
|
||||
if prescription.id == prescription_id:
|
||||
return deepcopy(prescription)
|
||||
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, *, restart_identity: bool = False) -> dict[str, Any]:
|
||||
return self.get_prescription_esign_status(prescription_id)
|
||||
|
||||
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]:
|
||||
raise ApiBusinessError("演示模式没有已签原件", code=0)
|
||||
|
||||
def create_prescription(
|
||||
self,
|
||||
@@ -1323,6 +1378,7 @@ class DemoDoctorRepository:
|
||||
body.setdefault("doctor_name", "陈医生(演示)")
|
||||
body.setdefault("create_time", datetime.now().replace(microsecond=0).isoformat(sep=" "))
|
||||
body["id"] = prescription_id
|
||||
body["esign"] = self._disabled_prescription_esign()
|
||||
created = Prescription.from_dict(body)
|
||||
self._prescriptions.append(created)
|
||||
self._sync_prescription_flag(created.diagnosis_id)
|
||||
@@ -1361,6 +1417,7 @@ class DemoDoctorRepository:
|
||||
body["audit_status"] = 0
|
||||
body["audit_remark"] = ""
|
||||
body["void_status"] = 0
|
||||
body["esign"] = self._disabled_prescription_esign()
|
||||
updated = Prescription.from_dict(body)
|
||||
self._prescriptions[self._prescriptions.index(original)] = updated
|
||||
self._sync_prescription_flag(updated.diagnosis_id)
|
||||
@@ -1454,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
|
||||
@@ -1466,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]:
|
||||
@@ -1477,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
|
||||
@@ -1509,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,
|
||||
@@ -250,6 +251,39 @@ class DoctorRepository(Protocol):
|
||||
def get_prescription(self, prescription_id: int) -> Prescription:
|
||||
"""Return one issued prescription."""
|
||||
|
||||
def get_prescription_esign_config(self) -> dict[str, Any]:
|
||||
"""Return electronic signature capability without provider credentials."""
|
||||
|
||||
def get_prescription_esign_status(self, prescription_id: int) -> dict[str, Any]:
|
||||
"""Query the authoritative signature state and current actor capabilities."""
|
||||
|
||||
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 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."""
|
||||
|
||||
def get_prescription_ai_capabilities(self) -> dict[str, Any]:
|
||||
"""Read the server's current agreement visibility decision."""
|
||||
|
||||
@@ -1696,6 +1730,109 @@ class RemoteDoctorRepository:
|
||||
)
|
||||
return Prescription.from_dict(result)
|
||||
|
||||
def get_prescription_esign_config(self) -> dict[str, Any]:
|
||||
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, **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, **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 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 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:
|
||||
raise ValueError("prescription id is required")
|
||||
endpoint = "tcm.prescription/esignDownload"
|
||||
return dict(_require_mapping(_client_request(self.client, "get", endpoint, {"id": prescription_id}, timeout=60.0), endpoint))
|
||||
|
||||
def _prescription_ai_request(self, action: str, params: dict[str, Any], *, mutation: bool = False) -> dict[str, Any]:
|
||||
endpoint = f"tcm.prescriptionAi/{action}"
|
||||
payload = _client_request(self.client, "post" if mutation else "get", endpoint, params, timeout=30.0)
|
||||
@@ -3626,6 +3763,8 @@ def _prescription_payload(
|
||||
raise TypeError("prescription must be a Prescription or mapping")
|
||||
result.update(fields)
|
||||
result.pop("raw", None)
|
||||
# Signature state is response-only and must never be asserted by a client.
|
||||
result.pop("esign", None)
|
||||
if "herbs" in result and isinstance(result["herbs"], (list, tuple)):
|
||||
result["herbs"] = [dict(item) for item in result["herbs"] if isinstance(item, Mapping)]
|
||||
if "visible_role_ids" in result and isinstance(
|
||||
|
||||
@@ -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",
|
||||
)
|
||||
@@ -3740,8 +3749,8 @@ class DiagnosisDialog(QDialog):
|
||||
self._show_message("正在提交…", "info")
|
||||
run_async(
|
||||
operation,
|
||||
on_success=lambda _result: self._media_mutation_success(
|
||||
success_text, reload_key, diagnosis_id, generation
|
||||
on_success=lambda result: self._media_mutation_success(
|
||||
success_text, reload_key, diagnosis_id, generation, result
|
||||
),
|
||||
on_error=lambda error: self._mutation_error(error, diagnosis_id, generation, "media"),
|
||||
on_finished=on_finished,
|
||||
@@ -3753,10 +3762,15 @@ class DiagnosisDialog(QDialog):
|
||||
reload_key: str,
|
||||
diagnosis_id: int,
|
||||
generation: int,
|
||||
result: Any = None,
|
||||
) -> None:
|
||||
if generation != self._media_generation or diagnosis_id != self._diagnosis_id:
|
||||
return
|
||||
self._show_message(text, "success")
|
||||
from .prescription_esign import resume_saved_prescription, saved_prescription_message
|
||||
kind = "success"
|
||||
if reload_key == "prescription":
|
||||
text, kind = saved_prescription_message(result, text)
|
||||
self._show_message(text, kind)
|
||||
self._loaded_tabs.discard(reload_key)
|
||||
if reload_key == "chat":
|
||||
QTimer.singleShot(
|
||||
@@ -3769,6 +3783,8 @@ class DiagnosisDialog(QDialog):
|
||||
)
|
||||
else:
|
||||
self._ensure_tab_loaded(reload_key, force=True)
|
||||
if reload_key == "prescription":
|
||||
resume_saved_prescription(self.repository, result, self)
|
||||
|
||||
def _order_offset_changed(self, value: int) -> None:
|
||||
self.order_offset_preview.setText(f"第 1 笔实单计为{_visit_slot_label(value)}")
|
||||
@@ -4142,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)
|
||||
@@ -4154,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,6 +117,13 @@ from ..widgets import (
|
||||
show_toast,
|
||||
)
|
||||
from .diagnosis import DiagnosisDialog as _StructuredDiagnosisDialog
|
||||
from .prescription_esign import (
|
||||
PrescriptionEsignDialog,
|
||||
open_saved_original,
|
||||
save_signed_original,
|
||||
signature_state,
|
||||
signature_time_text,
|
||||
)
|
||||
|
||||
PRESCRIPTION_DRAWER_QSS = clinical_stylesheet(r"""
|
||||
QFrame#PrescriptionDrawerSurface {
|
||||
@@ -964,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": "复诊",
|
||||
@@ -2859,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)
|
||||
@@ -2874,8 +3011,13 @@ class PrescriptionEditorDialog(QDialog):
|
||||
else None
|
||||
)
|
||||
self._source = _mapping(prescription)
|
||||
self._esign_enabled = False
|
||||
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
|
||||
@@ -2987,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
|
||||
@@ -2996,6 +3144,56 @@ 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):
|
||||
return
|
||||
self._esign_ready = False
|
||||
self.save_button.setEnabled(False)
|
||||
self.esign_retry_button.setEnabled(False)
|
||||
self.esign_hint.setText("正在确认电子签署方式…")
|
||||
self.esign_hint.show()
|
||||
run_async(method, on_success=self._esign_config_loaded, on_error=self._esign_config_failed)
|
||||
|
||||
def _esign_config_loaded(self, result: Any) -> None:
|
||||
try:
|
||||
config = esign_config(result)
|
||||
except Exception as error:
|
||||
self._esign_config_failed(error)
|
||||
return
|
||||
self._esign_ready = True
|
||||
self._esign_enabled = config["enabled"]
|
||||
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 ""
|
||||
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:
|
||||
return self.mode == "edit" and prescription_edit_is_locked(self.prescription)
|
||||
|
||||
def _esign_config_failed(self, error: Exception) -> None:
|
||||
self._esign_ready = False
|
||||
self.save_button.setEnabled(False)
|
||||
self.esign_hint.setText(f"无法确认签署方式:{friendly_error(error)} 请重试后保存。")
|
||||
self.esign_hint.show()
|
||||
self.esign_retry_button.show()
|
||||
self.esign_retry_button.setEnabled(True)
|
||||
|
||||
def _build_header(self) -> QFrame:
|
||||
header = QFrame()
|
||||
@@ -3474,7 +3672,17 @@ class PrescriptionEditorDialog(QDialog):
|
||||
hint = QLabel("* 必填,请在框内手写医师签名")
|
||||
hint.setObjectName("PrescriptionSignatureHint")
|
||||
signature_layout.addWidget(hint)
|
||||
layout.addWidget(self._field("医师签名", signature_host, required=True))
|
||||
self.signature_field = self._field("医师签名", signature_host, required=True)
|
||||
layout.addWidget(self.signature_field)
|
||||
self.esign_hint = QLabel()
|
||||
self.esign_hint.setWordWrap(True)
|
||||
self.esign_hint.setObjectName("PrescriptionFormHint")
|
||||
self.esign_hint.hide()
|
||||
layout.addWidget(self.esign_hint)
|
||||
self.esign_retry_button = QPushButton("重新读取签署方式")
|
||||
self.esign_retry_button.clicked.connect(self._load_esign_config)
|
||||
self.esign_retry_button.hide()
|
||||
layout.addWidget(self.esign_retry_button, 0, Qt.AlignmentFlag.AlignLeft)
|
||||
return section
|
||||
|
||||
def scroll_to_section(self, index: int) -> None:
|
||||
@@ -4051,7 +4259,7 @@ class PrescriptionEditorDialog(QDialog):
|
||||
"dietary_taboo": self.dietary_taboo.values(),
|
||||
"usage_notes": self.usage_notes.toPlainText().strip(),
|
||||
"doctor_name": self.doctor_name.text().strip(),
|
||||
"doctor_signature": self.signature.data_url(),
|
||||
"doctor_signature": "" if self._esign_enabled else self.signature.data_url(),
|
||||
"aux_usage": {
|
||||
"dosage_amount": self.aux_dosage_amount.value(),
|
||||
"dosage_bag_count": self.aux_dosage_bag_count.value(),
|
||||
@@ -4095,7 +4303,15 @@ 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")
|
||||
return
|
||||
if self._esign_content_locked():
|
||||
self.validation.show_message("处方签署内容已冻结,请作废后重新开方。", "warning")
|
||||
return
|
||||
checks = (
|
||||
(payload["patient_name"], "请输入患者姓名", self.patient_name, 0),
|
||||
(payload["prescription_date"], "请选择处方日期", self.date_edit, 0),
|
||||
@@ -4108,7 +4324,7 @@ class PrescriptionEditorDialog(QDialog):
|
||||
(payload.get("dose_count"), "请输入剂数", self.dose_count, 2),
|
||||
(payload["doctor_name"], "请输入医师姓名", self.doctor_name, 3),
|
||||
(
|
||||
payload["doctor_signature"],
|
||||
self._esign_enabled or payload["doctor_signature"],
|
||||
"请使用电子签名板手写医师签名",
|
||||
self.signature,
|
||||
3,
|
||||
@@ -4155,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)
|
||||
@@ -4517,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,
|
||||
*,
|
||||
@@ -4545,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")) == "主方"]
|
||||
@@ -4751,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>'
|
||||
)
|
||||
@@ -4805,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
|
||||
@@ -4883,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; }}
|
||||
@@ -4921,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}">
|
||||
@@ -5229,11 +5505,23 @@ class PrescriptionDetailDialog(QDialog):
|
||||
initial_tab: str = "prescription",
|
||||
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)
|
||||
_apply_prescription_dialog_style(self)
|
||||
self.prescription = prescription
|
||||
self.repository = repository if repository is not None else getattr(parent, "repository", None)
|
||||
self.esign = signature_state(prescription)
|
||||
try:
|
||||
self.esign = esign_status(self.esign)
|
||||
self._esign_unconfirmed = False
|
||||
except Exception:
|
||||
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"))
|
||||
@@ -5254,11 +5542,19 @@ 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.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)
|
||||
actions.addStretch(1)
|
||||
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")
|
||||
pdf_button.clicked.connect(self.choose_pdf_path)
|
||||
actions.addWidget(pdf_button)
|
||||
@@ -5291,6 +5587,9 @@ 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")
|
||||
self.preview.setOpenExternalLinks(False)
|
||||
@@ -5334,7 +5633,91 @@ 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
|
||||
self._esign_busy = True
|
||||
self._sync_esign_export()
|
||||
prescription_id = _int(first_value(self.prescription, "id", default=0))
|
||||
run_async(lambda: self.repository.get_prescription_esign_status(prescription_id), on_success=self._esign_loaded, on_error=self._esign_failed, on_finished=self._esign_finished)
|
||||
|
||||
def _esign_loaded(self, result: Any) -> None:
|
||||
try:
|
||||
self.esign = esign_status(result)
|
||||
except Exception as error:
|
||||
self._esign_failed(error)
|
||||
return
|
||||
self._esign_unconfirmed = False
|
||||
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")
|
||||
self._sync_esign_export()
|
||||
|
||||
def _esign_finished(self) -> None:
|
||||
self._esign_busy = False
|
||||
self._sync_esign_export()
|
||||
|
||||
def _sync_esign_export(self) -> None:
|
||||
case_record = self._is_case_record_selected()
|
||||
electronic = self.esign.get("required") is True or self.esign.get("status") != "legacy" or self.esign.get("can_download") is True
|
||||
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:
|
||||
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()
|
||||
|
||||
def _current_variant(self) -> str:
|
||||
return "user" if self.tabs.tabText(self.tabs.currentIndex()) == "处方联" else "internal"
|
||||
@@ -5370,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="")
|
||||
@@ -5388,10 +5774,65 @@ 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():
|
||||
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() -> 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 "当前尚无可下载的已签原件,请先完成签署。")
|
||||
return current, save_signed_original(self.repository, prescription_id, current["environment"], output)
|
||||
return current, None
|
||||
|
||||
def checked(result: tuple[dict[str, Any], Path | None]) -> None:
|
||||
current, saved_path = result
|
||||
self._esign_loaded(current)
|
||||
if saved_path is not None:
|
||||
prefix = "沙箱测试:" if current["environment"] == "sandbox" 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)
|
||||
|
||||
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
|
||||
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."""
|
||||
is_case_record = self._is_case_record_selected()
|
||||
output_label = "详细病历" if is_case_record else "处方笺"
|
||||
image = self._current_output_image()
|
||||
|
||||
@@ -0,0 +1,995 @@
|
||||
"""In-system identity authentication and server-authoritative prescription signing."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable, Mapping
|
||||
from hashlib import sha256
|
||||
from pathlib import Path
|
||||
from time import monotonic
|
||||
from typing import Any
|
||||
|
||||
from PySide6.QtCore import (
|
||||
QDate,
|
||||
QDateTime,
|
||||
QIODeviceBase,
|
||||
QSaveFile,
|
||||
Qt,
|
||||
QTimer,
|
||||
QTimeZone,
|
||||
QUrl,
|
||||
Signal,
|
||||
)
|
||||
from PySide6.QtGui import QDesktopServices
|
||||
from PySide6.QtWidgets import (
|
||||
QDialog,
|
||||
QDialogButtonBox,
|
||||
QHBoxLayout,
|
||||
QLabel,
|
||||
QLineEdit,
|
||||
QPushButton,
|
||||
QVBoxLayout,
|
||||
QWidget,
|
||||
)
|
||||
from shiboken6 import isValid
|
||||
|
||||
from ...config import AppConfig
|
||||
from ...core.esign import (
|
||||
ESIGN_LABELS,
|
||||
authentication_url,
|
||||
certificate_identity_number,
|
||||
esign_identity_status,
|
||||
esign_sms_code,
|
||||
esign_status,
|
||||
signed_pdf_bytes,
|
||||
)
|
||||
from ..design_system import clinical_stylesheet
|
||||
from ..widgets import MessageBanner, first_value, friendly_error, has_permission, run_async
|
||||
from .esign_doctor import EsignDoctorDialog
|
||||
from .esign_webview import create_identity_view
|
||||
|
||||
_ESIGN_WRITE_PERMISSIONS = (
|
||||
"cf.prescription/add",
|
||||
"cf.prescription/edit",
|
||||
"tcm.prescription/add",
|
||||
"tcm.prescription/edit",
|
||||
"tcm.diagnosis/chufang",
|
||||
"tcm.diagnosis/kaifang",
|
||||
)
|
||||
_SIGNABLE_STATES = ("pending", "authenticating", "failed")
|
||||
_BEIJING_TIME = QTimeZone(b"Asia/Shanghai")
|
||||
_SIGNATURE_TIME_SOURCES = {"tsa": "可信时间戳", "local": "签名记录时间"}
|
||||
_QUICK_AUTHORIZATION_STATUS = {
|
||||
"missing": "尚未授权快捷签",
|
||||
"expired": "快捷签授权已过期",
|
||||
"exhausted": "快捷签授权次数已用完",
|
||||
"invalid": "快捷签授权已失效",
|
||||
}
|
||||
|
||||
|
||||
def save_signed_original(
|
||||
repository: Any, prescription_id: int, environment: str, path: str | Path | None = None,
|
||||
) -> Path:
|
||||
content = signed_pdf_bytes(repository.download_prescription_esign(prescription_id))
|
||||
if path is None:
|
||||
base_url = str(getattr(getattr(repository, "client", None), "base_url", ""))
|
||||
site = sha256(base_url.encode()).hexdigest()[:16]
|
||||
digest = sha256(content).hexdigest()
|
||||
folder = AppConfig().config_dir / "prescription-originals" / environment / site / digest
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
path = folder / f"已签处方-{prescription_id}.pdf"
|
||||
output = Path(path)
|
||||
target = QSaveFile(str(output))
|
||||
if not target.open(QIODeviceBase.OpenModeFlag.WriteOnly) or target.write(content) != len(content) or not target.commit():
|
||||
raise OSError(target.errorString())
|
||||
return output
|
||||
|
||||
|
||||
def open_saved_original(path: Path, banner: MessageBanner) -> None:
|
||||
try:
|
||||
if sha256(path.read_bytes()).hexdigest() != path.parent.name:
|
||||
raise OSError
|
||||
except OSError:
|
||||
banner.show_message("已保存的原件无法读取或校验失败,请重新下载。", "warning")
|
||||
return
|
||||
if not QDesktopServices.openUrl(QUrl.fromLocalFile(str(path.resolve()))):
|
||||
banner.show_message("原件已保存,但系统未能打开 PDF 阅读器。", "warning")
|
||||
|
||||
|
||||
def signature_state(prescription: Any) -> dict[str, Any]:
|
||||
value = first_value(prescription, "esign", default={})
|
||||
return dict(value) if isinstance(value, Mapping) else {}
|
||||
|
||||
|
||||
def _format_esign_time(value: Any) -> str:
|
||||
if type(value) is not int or not 0 < value <= 253402300799:
|
||||
return ""
|
||||
return QDateTime.fromSecsSinceEpoch(value, _BEIJING_TIME).toString("yyyy-MM-dd HH:mm:ss")
|
||||
|
||||
|
||||
def signature_time_text(state: Mapping[str, Any]) -> str:
|
||||
"""Display the archived prescription's issue and signing events separately."""
|
||||
status = state.get("status")
|
||||
if status not in ("signed", "voided"):
|
||||
return ""
|
||||
lines = []
|
||||
issued_time = _format_esign_time(state.get("issued_at"))
|
||||
original_date = state.get("prescription_date")
|
||||
if issued_time:
|
||||
lines.append(f"开具确认时间:{issued_time}(北京时间)")
|
||||
elif isinstance(original_date, str) and original_date:
|
||||
date_format = Qt.DateFormat.ISODate
|
||||
if QDate.fromString(original_date, date_format).toString(date_format) == original_date:
|
||||
lines.append(f"原件记载日期:{original_date}(未记录开具时分秒)")
|
||||
|
||||
source = _SIGNATURE_TIME_SOURCES.get(str(state.get("signature_time_source")))
|
||||
signature_time = _format_esign_time(state.get("signature_time")) if source else ""
|
||||
if signature_time:
|
||||
lines.append(f"签署时间:{signature_time}(北京时间 · {source})")
|
||||
else:
|
||||
completed = _format_esign_time(state.get("signed_at"))
|
||||
if completed or status == "signed" or state.get("can_download") is True:
|
||||
lines.append("签署时间待核实")
|
||||
if completed:
|
||||
lines.append(f"系统验签完成时间:{completed}(北京时间)")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def can_continue_prescription_esign(state: Mapping[str, Any], permissions: Any) -> bool:
|
||||
return (
|
||||
state.get("enabled") is True
|
||||
and state.get("required") is True
|
||||
and (
|
||||
(state.get("status") in _SIGNABLE_STATES and state.get("can_sign") is True)
|
||||
or (state.get("status") == "uncertain" and state.get("can_retry_verify") is True)
|
||||
)
|
||||
and has_permission(permissions, _ESIGN_WRITE_PERMISSIONS)
|
||||
)
|
||||
|
||||
|
||||
def can_open_esign_doctor(repository: Any, permissions: Any) -> bool:
|
||||
return callable(getattr(repository, "get_esign_doctor_status", None)) and has_permission(
|
||||
permissions, _ESIGN_WRITE_PERMISSIONS, default=False,
|
||||
)
|
||||
|
||||
|
||||
def saved_prescription_message(prescription: Any, fallback: str) -> tuple[str, str]:
|
||||
try:
|
||||
state = esign_status(signature_state(prescription))
|
||||
except Exception:
|
||||
return "处方已保存,电子签署状态尚未确认,请在处方详情查询。", "warning"
|
||||
if state.get("required") is True and state.get("status") != "signed":
|
||||
if state.get("verification_method") == "quick":
|
||||
return "处方草稿已保存,尚待完成电子签署。可在处方详情继续签署。", "warning"
|
||||
return "处方草稿已保存,尚待完成电子签署。可在处方详情继续验证身份或签名。", "warning"
|
||||
if state.get("status") == "signed":
|
||||
return "处方已保存并完成电子签署,等待审核。", "success"
|
||||
return fallback, "success"
|
||||
|
||||
|
||||
def resume_saved_prescription(repository: Any, prescription: Any, parent: QWidget) -> bool:
|
||||
try:
|
||||
state = esign_status(signature_state(prescription))
|
||||
except Exception:
|
||||
state = {}
|
||||
if state.get("required") is True and state.get("status") != "signed":
|
||||
dialog = PrescriptionEsignDialog(repository, prescription, parent=parent)
|
||||
dialog.exec()
|
||||
return dialog.state.get("status") == "signed"
|
||||
return False
|
||||
|
||||
|
||||
class PrescriptionEsignDialog(QDialog):
|
||||
"""Only a validated identity GET plus explicit user intent can submit once."""
|
||||
|
||||
status_changed = Signal(dict)
|
||||
POLL_INTERVAL_MS = 5_000
|
||||
AUTH_TIMEOUT_SECONDS = 600
|
||||
|
||||
def __init__(self, repository: Any, prescription: Any, *, parent: QWidget | None = None) -> None:
|
||||
super().__init__(parent)
|
||||
self.repository = repository
|
||||
self.prescription_id = int(first_value(prescription, "id", "prescription_id", default=0) or 0)
|
||||
self._system_placeholder = first_value(prescription, "is_system_auto") in (True, 1, "1")
|
||||
self.state: dict[str, Any] = {}
|
||||
self._saved_original: Path | None = None
|
||||
self._busy = False
|
||||
self._confirmed = False
|
||||
self._closed = False
|
||||
self._generation = 0
|
||||
self._intent = False
|
||||
self._completion_sent = False
|
||||
self._identity_ready = False
|
||||
self._identity_details_required = False
|
||||
self._doctor_enrollment_ready = False
|
||||
self._retry_identity = False
|
||||
self._check_identity_on_open = True
|
||||
self._auto_prepare_quick = True
|
||||
self._auth_deadline: float | None = None
|
||||
self._identity_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_identity)
|
||||
self.setWindowTitle("处方电子签署")
|
||||
self.setMinimumSize(900, 700)
|
||||
self.resize(1040, 800)
|
||||
self.setStyleSheet(clinical_stylesheet("QDialog { background:#FFFFFF; }"))
|
||||
layout = QVBoxLayout(self)
|
||||
layout.setContentsMargins(24, 24, 24, 24)
|
||||
layout.setSpacing(12)
|
||||
self.steps = QWidget(self)
|
||||
steps = QHBoxLayout(self.steps)
|
||||
steps.setContentsMargins(0, 0, 0, 0)
|
||||
steps.setSpacing(8)
|
||||
self.step_labels = []
|
||||
for title in ("处方草稿已保存", "验证医生身份", "签名并完成"):
|
||||
if self.step_labels:
|
||||
steps.addWidget(QLabel("→", self))
|
||||
label = QLabel(title, self)
|
||||
label.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
steps.addWidget(label, 1)
|
||||
self.step_labels.append(label)
|
||||
layout.addWidget(self.steps)
|
||||
patient = str(first_value(prescription, "patient_name", default="") or "").strip()
|
||||
reference = str(first_value(prescription, "sn", "prescription_no", default="") or "").strip()
|
||||
if patient or reference:
|
||||
summary = QLabel(" · ".join(text for text in (patient, reference) if text), self)
|
||||
summary.setTextFormat(Qt.TextFormat.PlainText)
|
||||
summary.setWordWrap(True)
|
||||
layout.addWidget(summary)
|
||||
self.status_label = QLabel("正在确认签署状态…")
|
||||
self.status_label.setTextFormat(Qt.TextFormat.PlainText)
|
||||
layout.addWidget(self.status_label)
|
||||
self.signature_time_label = QLabel(self)
|
||||
self.signature_time_label.setTextFormat(Qt.TextFormat.PlainText)
|
||||
self.signature_time_label.setWordWrap(True)
|
||||
self.signature_time_label.hide()
|
||||
layout.addWidget(self.signature_time_label)
|
||||
self.banner = MessageBanner(parent=self)
|
||||
self.banner.label.setTextFormat(Qt.TextFormat.PlainText)
|
||||
layout.addWidget(self.banner)
|
||||
self.identity_details_container = QWidget(self)
|
||||
details_layout = QVBoxLayout(self.identity_details_container)
|
||||
details_layout.setContentsMargins(0, 0, 0, 0)
|
||||
details_hint = QLabel(
|
||||
"首次签名需绑定证书。请输入与本次验证一致的中国大陆居民身份证号码。"
|
||||
"号码仅用于本次证书绑定核验。"
|
||||
)
|
||||
details_hint.setWordWrap(True)
|
||||
details_layout.addWidget(details_hint)
|
||||
self.identity_number_input = QLineEdit(self.identity_details_container)
|
||||
self.identity_number_input.setEchoMode(QLineEdit.EchoMode.Password)
|
||||
self.identity_number_input.setAccessibleName("证书绑定身份证号码")
|
||||
self.identity_number_input.setPlaceholderText("请输入与已完成核身一致的 15 或 18 位身份证号码")
|
||||
self.identity_number_input.setInputMethodHints(Qt.InputMethodHint.ImhSensitiveData | Qt.InputMethodHint.ImhNoPredictiveText)
|
||||
details_layout.addWidget(self.identity_number_input)
|
||||
self.identity_details_container.hide()
|
||||
layout.addWidget(self.identity_details_container)
|
||||
self.sms_container = QWidget(self)
|
||||
sms_layout = QVBoxLayout(self.sms_container)
|
||||
sms_layout.setContentsMargins(0, 0, 0, 0)
|
||||
sms_label = QLabel("本张处方的短信验证码", self.sms_container)
|
||||
self.sms_code_input = QLineEdit(self.sms_container)
|
||||
self.sms_code_input.setEchoMode(QLineEdit.EchoMode.Password)
|
||||
self.sms_code_input.setAccessibleName("本张处方的短信验证码")
|
||||
self.sms_code_input.setPlaceholderText("请输入绑定手机收到的验证码")
|
||||
self.sms_code_input.setInputMethodHints(
|
||||
Qt.InputMethodHint.ImhSensitiveData | Qt.InputMethodHint.ImhNoPredictiveText
|
||||
| Qt.InputMethodHint.ImhDigitsOnly,
|
||||
)
|
||||
sms_label.setBuddy(self.sms_code_input)
|
||||
sms_layout.addWidget(sms_label)
|
||||
sms_layout.addWidget(self.sms_code_input)
|
||||
self.sms_container.hide()
|
||||
layout.addWidget(self.sms_container)
|
||||
self.identity_container = QWidget(self)
|
||||
self.identity_layout = QVBoxLayout(self.identity_container)
|
||||
self.identity_layout.setContentsMargins(0, 0, 0, 0)
|
||||
layout.addWidget(self.identity_container, 1)
|
||||
footer = QHBoxLayout()
|
||||
self.start_button = QPushButton("开始验证")
|
||||
self.start_button.clicked.connect(self.start)
|
||||
self.complete_button = QPushButton("继续验证")
|
||||
self.complete_button.clicked.connect(self.complete)
|
||||
self.sign_button = QPushButton("确认签名")
|
||||
self.sign_button.clicked.connect(self.confirm_sign)
|
||||
self.bind_certificate_button = self.sign_button
|
||||
self.doctor_identity_button = QPushButton("前往认证医生身份")
|
||||
self.doctor_identity_button.clicked.connect(self._open_doctor_identity)
|
||||
self.refresh_button = QPushButton("查询签署结果")
|
||||
self.refresh_button.clicked.connect(self.refresh)
|
||||
self.verify_button = QPushButton("重试验签")
|
||||
self.verify_button.clicked.connect(self.verify_original)
|
||||
self.download_button = QPushButton("下载签署原件")
|
||||
self.download_button.clicked.connect(lambda: self.download_to())
|
||||
self.open_original_button = QPushButton("打开已保存原件")
|
||||
self.open_original_button.clicked.connect(self._open_saved_original)
|
||||
self._action_buttons = (
|
||||
self.start_button, self.complete_button, self.sign_button, self.doctor_identity_button,
|
||||
self.refresh_button, self.verify_button, self.download_button, self.open_original_button,
|
||||
)
|
||||
for button in self._action_buttons:
|
||||
button.setAutoDefault(False)
|
||||
footer.addWidget(button)
|
||||
footer.addStretch(1)
|
||||
self.close_buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Close)
|
||||
self.close_buttons.button(QDialogButtonBox.StandardButton.Close).setText("关闭")
|
||||
self.close_buttons.button(QDialogButtonBox.StandardButton.Close).setAutoDefault(False)
|
||||
self.close_buttons.rejected.connect(self.reject)
|
||||
footer.addWidget(self.close_buttons)
|
||||
layout.addLayout(footer)
|
||||
self.refresh()
|
||||
|
||||
def _sync_actions(self) -> None:
|
||||
available = not self._busy and not self._closed and not self._native_hide_pending
|
||||
status = self.state.get("status")
|
||||
legacy = self._confirmed and status == "legacy" and self.state.get("required") is False
|
||||
incomplete = self._confirmed and self._needs_prescription_content()
|
||||
signer = self._confirmed and self._can_sign() and not self._completion_sent
|
||||
restart = self.state.get("identity_status") in {"FAIL", "EXPIRED"}
|
||||
main = None if legacy or incomplete else self.refresh_button
|
||||
secondary = None
|
||||
sms_input = False
|
||||
if self._confirmed and status in {"signed", "voided"} and self.state.get("can_download") is True:
|
||||
main = self.download_button
|
||||
if self._saved_original is not None:
|
||||
secondary = self.open_original_button
|
||||
elif (self._confirmed and status == "uncertain"
|
||||
and all(self.state.get(key) is True for key in ("enabled", "required", "can_retry_verify"))):
|
||||
main, secondary = self.verify_button, self.refresh_button
|
||||
elif signer:
|
||||
if self._needs_quick_account_setup():
|
||||
main = self.refresh_button
|
||||
elif self._needs_doctor_identity():
|
||||
main = self.doctor_identity_button
|
||||
elif self._identity_ready:
|
||||
main = self.sign_button
|
||||
elif self._uses_quick():
|
||||
if restart or not self._can_resume_identity():
|
||||
self.start_button.setText("重新准备快捷签" if restart or status == "failed" else "准备快捷签")
|
||||
main = self.start_button
|
||||
else:
|
||||
self.complete_button.setText("检查快捷签授权")
|
||||
main = self.complete_button
|
||||
elif self._uses_sms():
|
||||
sms_input = self._can_resume_identity() and self.state.get("sms_sent", True) and not restart
|
||||
self.start_button.setText("重新发送验证码" if sms_input or restart or self.state.get("sms_sent")
|
||||
else "发送短信验证码")
|
||||
if sms_input:
|
||||
self.complete_button.setText("校验验证码")
|
||||
main, secondary = self.complete_button, self.start_button
|
||||
else:
|
||||
main = self.start_button
|
||||
elif restart or not self._can_resume_identity():
|
||||
self.start_button.setText("重新验证" if restart or status == "failed" else "开始验证")
|
||||
main = self.start_button
|
||||
else:
|
||||
if self._retry_identity:
|
||||
self.complete_button.setText("重试验证状态")
|
||||
elif self.identity_view is not None:
|
||||
self.complete_button.setText("检查验证状态")
|
||||
else:
|
||||
self.complete_button.setText("继续验证")
|
||||
main = self.complete_button
|
||||
if signer and self._needs_quick_account_setup():
|
||||
self.refresh_button.setText("重新检查签署条件")
|
||||
elif sms_input:
|
||||
self.refresh_button.setText("检查短信确认状态")
|
||||
else:
|
||||
self.refresh_button.setText("查询签署结果" if self._completion_sent or status in {"signing", "signed", "uncertain"} else "重试查询状态")
|
||||
for button in self._action_buttons:
|
||||
active = button in (main, secondary) or (sms_input and button is self.refresh_button)
|
||||
button.setVisible(active)
|
||||
button.setEnabled(active and available)
|
||||
variant = "primary" if button is main else None
|
||||
if button.property("variant") != variant:
|
||||
button.setProperty("variant", variant)
|
||||
button.style().unpolish(button)
|
||||
button.style().polish(button)
|
||||
self.identity_number_input.setEnabled(available and self._identity_details_required)
|
||||
if not sms_input:
|
||||
self.sms_code_input.setText("")
|
||||
self.sms_container.setVisible(sms_input)
|
||||
self.sms_code_input.setEnabled(available and sms_input)
|
||||
self.steps.setVisible(self._confirmed and not legacy and not incomplete)
|
||||
time_text = signature_time_text(self.state) if self._confirmed else ""
|
||||
self.signature_time_label.setText(time_text)
|
||||
self.signature_time_label.setVisible(bool(time_text))
|
||||
|
||||
finished = status == "signed"
|
||||
signing = self._identity_ready or self._completion_sent or status in {"signing", "uncertain", "signed"}
|
||||
self.step_labels[1].setText("核对快捷签授权" if self._uses_quick() else
|
||||
"短信确认签署意愿" if self._uses_sms() else "验证医生身份")
|
||||
for index, label in enumerate(self.step_labels):
|
||||
complete = index == 0 or finished or (index == 1 and signing)
|
||||
current = not complete and index == (2 if signing else 1)
|
||||
color, background = (("#146452", "#E6F4EF") if complete else
|
||||
("#174B79", "#E9F2FC") if current else ("#526275", "#F2F5F8"))
|
||||
label.setStyleSheet(f"padding: 10px 8px; border-radius: 6px; color: {color}; background: {background};")
|
||||
label.setAccessibleDescription("已完成" if complete else "当前步骤" if current else "待完成")
|
||||
|
||||
def _can_sign(self) -> bool:
|
||||
return (self.state.get("status") in _SIGNABLE_STATES
|
||||
and all(self.state.get(key) is True for key in ("enabled", "required", "can_sign")))
|
||||
|
||||
def _needs_prescription_content(self) -> bool:
|
||||
return self._system_placeholder and self.state.get("status") in {"legacy", "pending"} and not self._can_sign()
|
||||
|
||||
def _uses_sms(self) -> bool:
|
||||
return self.state.get("verification_method") == "sms"
|
||||
|
||||
def _uses_quick(self) -> bool:
|
||||
return self.state.get("verification_method") == "quick"
|
||||
|
||||
def _needs_doctor_identity(self) -> bool:
|
||||
return (not self._uses_quick()
|
||||
and self.state.get("doctor_identity_required") is True and not self._doctor_enrollment_ready)
|
||||
|
||||
def _needs_quick_account_setup(self) -> bool:
|
||||
return self._uses_quick() and (
|
||||
self.state.get("doctor_identity_required") is True
|
||||
or self.state.get("signing_authorization_required") is True
|
||||
)
|
||||
|
||||
def _can_resume_identity(self) -> bool:
|
||||
status = self.state.get("status")
|
||||
can_resume = self.state.get("can_resume_identity", status == "authenticating" and not self._uses_quick())
|
||||
return (self._can_sign() and self.state.get("doctor_identity_required") is not True
|
||||
and not self._needs_quick_account_setup() and status in {"authenticating", "failed"}
|
||||
and can_resume is True)
|
||||
|
||||
def _discard_view(self) -> None:
|
||||
if self.identity_view is not None:
|
||||
view, self.identity_view = self.identity_view, None
|
||||
view.stop()
|
||||
self.identity_layout.removeWidget(view)
|
||||
view.deleteLater()
|
||||
|
||||
def _stop_flow(self) -> None:
|
||||
self.poll_timer.stop()
|
||||
self._intent = False
|
||||
self._auth_deadline = None
|
||||
self._identity_native_window_id = None
|
||||
self._native_hide_pending = False
|
||||
self._identity_ready = False
|
||||
self._identity_details_required = False
|
||||
self.identity_number_input.clear()
|
||||
self.identity_details_container.hide()
|
||||
self.sms_code_input.setText("")
|
||||
self._discard_view()
|
||||
|
||||
def _suspend_hidden_flow(self) -> None:
|
||||
self._generation += 1
|
||||
self._stop_flow()
|
||||
if self._uses_quick():
|
||||
self._check_identity_on_open = True
|
||||
if self._busy and not self._closed:
|
||||
# A discarded callback may have changed server state. Read again before any action.
|
||||
self._confirmed = False
|
||||
self.status_label.setText("处方签署状态尚未确认")
|
||||
self._sync_actions()
|
||||
|
||||
def done(self, result: int) -> None:
|
||||
self._closed = True
|
||||
self._generation += 1
|
||||
self._stop_flow()
|
||||
super().done(result)
|
||||
|
||||
def showEvent(self, event: Any) -> None:
|
||||
super().showEvent(event)
|
||||
self._check_retained_identity()
|
||||
|
||||
def hideEvent(self, event: Any) -> None:
|
||||
if self._identity_native_window_id is not None and not event.spontaneous() and not self._closed:
|
||||
# Adding WebEngine to a visible raster window can asynchronously
|
||||
# recreate its native surface. Suspend work until Qt finishes that
|
||||
# hide/show pair; a genuine hide must still invalidate the request.
|
||||
self._native_hide_pending = True
|
||||
self.poll_timer.stop()
|
||||
native_id = self._identity_native_window_id
|
||||
generation = self._generation
|
||||
QTimer.singleShot(0, lambda: self._resolve_initialization_hide(native_id, generation))
|
||||
self._sync_actions()
|
||||
super().hideEvent(event)
|
||||
return
|
||||
self._suspend_hidden_flow()
|
||||
super().hideEvent(event)
|
||||
|
||||
def hide(self) -> None:
|
||||
# Explicit application/user hide is never a renderer transition.
|
||||
self._suspend_hidden_flow()
|
||||
super().hide()
|
||||
|
||||
def _resolve_initialization_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
|
||||
recreated = (
|
||||
self.identity_view is not None and self.isVisible() and not self.isMinimized()
|
||||
and int(self.winId()) != native_id
|
||||
)
|
||||
self._native_hide_pending = False
|
||||
self._identity_native_window_id = None
|
||||
if recreated:
|
||||
if self._flow_active():
|
||||
self.poll_timer.start()
|
||||
else:
|
||||
self._suspend_hidden_flow()
|
||||
self._sync_actions()
|
||||
|
||||
def _identity_native_ready(self, source: Any) -> None:
|
||||
if isValid(self) and source is self.identity_view and not self._native_hide_pending:
|
||||
self._identity_native_window_id = None
|
||||
|
||||
def _apply_state(self, result: Any, *, after_sign: bool = False) -> None:
|
||||
self.state = esign_status(result)
|
||||
self._confirmed = True
|
||||
status = self.state["status"]
|
||||
self._retry_identity = False
|
||||
if (self._can_sign() and (status == "failed" or self._needs_quick_account_setup())
|
||||
or (after_sign and self._can_resume_identity())):
|
||||
# A definitive pre-sign failure can be retried only after another identity check.
|
||||
self._retry_identity = self._completion_sent and self._can_resume_identity()
|
||||
self._completion_sent = False
|
||||
if not self._can_resume_identity():
|
||||
self._stop_flow()
|
||||
label = str(self.state.get("status_label") or ESIGN_LABELS[status])
|
||||
message = str(self.state.get("message") or {
|
||||
"pending": "请由开方医生验证身份。",
|
||||
"authenticating": "请完成医生身份验证。",
|
||||
"signed": "电子签名已完成,处方等待审核。",
|
||||
}.get(status, ESIGN_LABELS[status]))
|
||||
if self._completion_sent and status in {"pending", "authenticating", "failed"}:
|
||||
label, message = "签署结果待确认", "请查询签署结果。"
|
||||
if status == "legacy" and not self.state["required"]:
|
||||
label = "沿用原有处方流程" if self.state["enabled"] else "电子签署功能已关闭"
|
||||
self.status_label.setText(label)
|
||||
message = "此处方沿用原有处方流程。您可关闭此窗口,返回处方详情或列表。"
|
||||
else:
|
||||
self._show_status("签名已完成" if status == "signed" else label)
|
||||
if self._needs_prescription_content():
|
||||
message = "此处方由系统占号生成。请开方医生先返回列表,编辑并补全处方内容。"
|
||||
elif self._can_sign() and self._needs_quick_account_setup():
|
||||
if self.state.get("doctor_identity_required") is True:
|
||||
if "signing_authorization_required" in self.state:
|
||||
label = "医生签署身份待核验"
|
||||
setup = "完成本人签署身份核验和快捷签授权"
|
||||
else:
|
||||
label = "医生签署身份或快捷签授权待完成"
|
||||
setup = "检查本人签署身份和快捷签授权"
|
||||
else:
|
||||
label = _QUICK_AUTHORIZATION_STATUS.get(
|
||||
self.state.get("signing_authorization_reason"), "快捷签授权待完成",
|
||||
)
|
||||
setup = "授权本人快捷签"
|
||||
self._show_status(label)
|
||||
message = f"请关闭此窗口,在右上角账号菜单的“医生电子签署身份”中{setup},然后回到处方详情继续签署。"
|
||||
elif self._can_sign() and self._needs_doctor_identity():
|
||||
message = "请先完成医生电子签署身份认证,再为这张处方发送短信验证码。"
|
||||
elif self._can_sign() and self._doctor_enrollment_ready and self.state.get("doctor_identity_required"):
|
||||
message = "医生电子签署身份已就绪。请为这张处方发送短信验证码。"
|
||||
elif self._can_sign() and self._uses_quick() and status == "pending" and not self._completion_sent:
|
||||
message = "请核对本张处方。快捷签授权通过核对后,可由开方医生确认签名。"
|
||||
elif self._can_sign() and self._uses_sms() and status == "pending" and not self._completion_sent:
|
||||
message = "请向医生签署身份绑定的手机发送短信验证码,确认本张处方的签署意愿。"
|
||||
warning = status in {"failed", "uncertain", "voided"} or self._needs_quick_account_setup()
|
||||
self.banner.show_message(message, "success" if status == "signed" else "warning" if warning else "info")
|
||||
self._sync_actions()
|
||||
self.status_changed.emit(dict(self.state))
|
||||
|
||||
def _show_status(self, label: str) -> None:
|
||||
environment = "沙箱测试" if self.state["environment"] == "sandbox" else "正式环境"
|
||||
self.status_label.setText(f"{label} · {environment}")
|
||||
|
||||
def _failed(self, error: Exception, method: str, *, proof_supplied: bool = False) -> None:
|
||||
self._generation += 1
|
||||
self._stop_flow()
|
||||
if method == "verify_prescription_esign_willingness":
|
||||
self._show_status("验证码校验状态待确认")
|
||||
self.banner.show_message("暂未确认验证码校验结果。请检查短信、重新输入验证码或重新发送。", "warning")
|
||||
elif method == "get_prescription_esign_identity_status" and self._uses_sms():
|
||||
self._show_status("短信确认状态待查询")
|
||||
self.banner.show_message("暂时无法查询短信确认状态。请重新输入验证码或重新发送。", "warning")
|
||||
elif method == "get_prescription_esign_identity_status" and self._uses_quick():
|
||||
self._show_status("快捷签授权待核对")
|
||||
self.banner.show_message("暂时无法核对快捷签授权,请重新检查。", "warning")
|
||||
elif method == "get_prescription_esign_identity_status":
|
||||
self._retry_identity = True
|
||||
self._show_status("身份验证状态待确认")
|
||||
self.banner.show_message(f"{friendly_error(error)} 请重试验证状态。", "warning")
|
||||
else:
|
||||
self._confirmed = False
|
||||
self.status_label.setText("签署结果尚未确认" if self._completion_sent else "处方签署状态尚未确认")
|
||||
if proof_supplied:
|
||||
message = "签名请求未收到确认。"
|
||||
elif method == "start_prescription_esign" and self._uses_sms():
|
||||
message = "短信发送结果未收到确认。"
|
||||
elif method == "start_prescription_esign" and self._uses_quick():
|
||||
message = "快捷签准备结果未收到确认。"
|
||||
else:
|
||||
message = friendly_error(error)
|
||||
if self._uses_sms() or self._uses_quick():
|
||||
self._check_identity_on_open = True
|
||||
self.banner.show_message(f"{message} 请查询状态后继续。", "danger")
|
||||
self._sync_actions()
|
||||
|
||||
def _request(
|
||||
self, method: str, *, identity_number: str = "", auth_code: str = "",
|
||||
restart_identity: bool = False, check_only: bool = False,
|
||||
) -> None:
|
||||
if self._busy or self._closed:
|
||||
return
|
||||
self._busy = True
|
||||
generation = self._generation
|
||||
proof_supplied = bool(identity_number)
|
||||
self._sync_actions()
|
||||
repository, prescription_id = self.repository, self.prescription_id
|
||||
|
||||
def current() -> bool:
|
||||
return isValid(self) and not self._closed and self._generation == generation
|
||||
|
||||
def loaded(result: Any) -> None:
|
||||
if not current():
|
||||
return
|
||||
if self._native_hide_pending:
|
||||
QTimer.singleShot(0, lambda: loaded(result))
|
||||
return
|
||||
try:
|
||||
readiness_query = method in {"get_prescription_esign_identity_status", "verify_prescription_esign_willingness"}
|
||||
if readiness_query:
|
||||
result = esign_identity_status(result)
|
||||
if readiness_query or method == "start_prescription_esign":
|
||||
mode = self.state.get("verification_method")
|
||||
mode_required = (readiness_query and mode == "sms") or (
|
||||
mode == "quick" and result.get("can_sign") is True
|
||||
)
|
||||
if mode_required and result.get("verification_method") != mode:
|
||||
raise ValueError("签署授权状态格式不正确")
|
||||
if method == "start_prescription_esign":
|
||||
self._doctor_enrollment_ready = False
|
||||
self._apply_state(result, after_sign=method == "complete_prescription_esign")
|
||||
if readiness_query:
|
||||
self._apply_identity_status(
|
||||
check_only=check_only, from_sms_verification=method == "verify_prescription_esign_willingness",
|
||||
)
|
||||
elif method == "start_prescription_esign" and self._uses_sms():
|
||||
self._stop_flow()
|
||||
if self._can_resume_identity() and self.state.get("sms_sent", True):
|
||||
self.banner.show_message("验证码已发送。请输入医生绑定手机收到的验证码。", "info")
|
||||
except Exception as error:
|
||||
self._failed(error, method, proof_supplied=proof_supplied)
|
||||
|
||||
def failed(error: Exception) -> None:
|
||||
if current():
|
||||
if self._native_hide_pending:
|
||||
QTimer.singleShot(0, lambda: failed(error))
|
||||
return
|
||||
self._failed(error, method, proof_supplied=proof_supplied)
|
||||
|
||||
def finished() -> None:
|
||||
if not isValid(self):
|
||||
return
|
||||
if self._native_hide_pending:
|
||||
QTimer.singleShot(0, finished)
|
||||
return
|
||||
self._busy = False
|
||||
if self._closed:
|
||||
return
|
||||
self._sync_actions()
|
||||
if not current():
|
||||
return
|
||||
if method == "get_prescription_esign_status":
|
||||
self._check_retained_identity()
|
||||
elif (method == "get_prescription_esign_identity_status" and check_only and self._uses_quick()
|
||||
and self.state.get("identity_status") in {"FAIL", "EXPIRED"}):
|
||||
self._prepare_quick_on_open()
|
||||
elif method == "start_prescription_esign" and not self._uses_sms() and self._flow_active():
|
||||
self._request("get_prescription_esign_identity_status")
|
||||
|
||||
def work() -> Any:
|
||||
nonlocal identity_number, auth_code
|
||||
try:
|
||||
if identity_number:
|
||||
return getattr(repository, method)(prescription_id, identity_number=identity_number)
|
||||
if auth_code:
|
||||
return getattr(repository, method)(prescription_id, auth_code=auth_code)
|
||||
if restart_identity:
|
||||
return getattr(repository, method)(prescription_id, restart_identity=True)
|
||||
return getattr(repository, method)(prescription_id)
|
||||
finally:
|
||||
identity_number = ""
|
||||
auth_code = ""
|
||||
|
||||
run_async(work,
|
||||
on_success=loaded, on_error=failed, on_finished=finished)
|
||||
|
||||
def refresh(self) -> None:
|
||||
if self._busy or self._closed:
|
||||
return
|
||||
if self._uses_sms() or self._uses_quick():
|
||||
self._check_identity_on_open = True
|
||||
if self._needs_quick_account_setup():
|
||||
self._auto_prepare_quick = True
|
||||
self._stop_flow()
|
||||
self._request("get_prescription_esign_status")
|
||||
|
||||
def _check_retained_identity(self) -> None:
|
||||
if (not self._check_identity_on_open or self._busy or not self.isVisible()
|
||||
or self._closed or not self._confirmed):
|
||||
return
|
||||
self._check_identity_on_open = False
|
||||
if self._completion_sent:
|
||||
return
|
||||
if self._can_resume_identity() and (
|
||||
not self._uses_quick() or self.state.get("identity_status") not in {"FAIL", "EXPIRED"}
|
||||
):
|
||||
self._begin_identity_check()
|
||||
self.banner.show_message(self._identity_check_message(), "info")
|
||||
self._request("get_prescription_esign_identity_status", check_only=True)
|
||||
else:
|
||||
self._prepare_quick_on_open()
|
||||
|
||||
def _prepare_quick_on_open(self) -> None:
|
||||
if (self._auto_prepare_quick and self._uses_quick()
|
||||
and not self._needs_quick_account_setup() and self.start_button.isEnabled()):
|
||||
self.start()
|
||||
|
||||
def _identity_check_message(self) -> str:
|
||||
if self._uses_quick():
|
||||
return "正在核对快捷签授权…"
|
||||
if self._uses_sms():
|
||||
return "正在核对短信确认状态…"
|
||||
return "正在核对医生身份验证状态…"
|
||||
|
||||
def _prepare_identity(self) -> bool:
|
||||
if not self.isVisible() or self._closed:
|
||||
return False
|
||||
if self.identity_view is None:
|
||||
try:
|
||||
self._identity_native_window_id = int(self.winId())
|
||||
self.identity_view = create_identity_view(self.identity_container)
|
||||
view = self.identity_view
|
||||
view.failed.connect(lambda message, source=view: self._web_failed(source, message))
|
||||
view.initialized.connect(lambda source=view: self._identity_native_ready(source))
|
||||
self.identity_layout.addWidget(self.identity_view)
|
||||
except Exception as error:
|
||||
self._stop_flow()
|
||||
self.banner.show_message(friendly_error(error), "warning")
|
||||
self._sync_actions()
|
||||
return False
|
||||
return True
|
||||
|
||||
def _web_failed(self, source: Any, message: str) -> None:
|
||||
if isValid(self) and source is self.identity_view and not self._closed and self._intent:
|
||||
self._failed(ValueError(message), "get_prescription_esign_identity_status")
|
||||
|
||||
def start(self) -> None:
|
||||
if not self.start_button.isEnabled():
|
||||
self.complete()
|
||||
elif self.isVisible():
|
||||
self._begin_identity_check()
|
||||
restart = self.state.get("identity_status") in {"FAIL", "EXPIRED"}
|
||||
if self._uses_sms():
|
||||
self.sms_code_input.setText("")
|
||||
restart = restart or self._can_resume_identity() or self.state.get("sms_sent") is True
|
||||
self.banner.show_message("正在向医生绑定手机发送验证码…", "info")
|
||||
else:
|
||||
if self._uses_quick():
|
||||
self._auto_prepare_quick = False
|
||||
self.banner.show_message(self._identity_check_message(), "info")
|
||||
self._request("start_prescription_esign", restart_identity=restart)
|
||||
|
||||
def complete(self) -> None:
|
||||
"""Check identity readiness, reusing the server's retained flow."""
|
||||
if not self.complete_button.isEnabled() or not self.isVisible():
|
||||
return
|
||||
if self._uses_sms():
|
||||
self._verify_sms()
|
||||
return
|
||||
self._begin_identity_check()
|
||||
self.banner.show_message(self._identity_check_message() if self._uses_quick() else "正在查询身份验证状态…", "info")
|
||||
self._request("get_prescription_esign_identity_status")
|
||||
|
||||
def _verify_sms(self) -> None:
|
||||
try:
|
||||
code = esign_sms_code(self.sms_code_input.text())
|
||||
except ValueError as error:
|
||||
self.sms_code_input.setText("")
|
||||
self.banner.show_message(str(error), "warning")
|
||||
self.sms_code_input.setFocus()
|
||||
return
|
||||
self.sms_code_input.setText("")
|
||||
self._begin_identity_check()
|
||||
self.banner.show_message("正在校验短信验证码…", "info")
|
||||
self._request("verify_prescription_esign_willingness", auth_code=code)
|
||||
|
||||
def _open_doctor_identity(self) -> None:
|
||||
if self._uses_quick() or not self.doctor_identity_button.isEnabled() or not self.isVisible():
|
||||
return
|
||||
dialog = EsignDoctorDialog(self.repository, parent=self)
|
||||
dialog.exec()
|
||||
self._doctor_enrollment_ready = (
|
||||
dialog.state.get("enabled") is True and dialog.state.get("status") == "ready"
|
||||
)
|
||||
dialog.deleteLater()
|
||||
self.refresh()
|
||||
|
||||
def _begin_identity_check(self) -> None:
|
||||
if not self._intent:
|
||||
self._intent = True
|
||||
self._auth_deadline = monotonic() + self.AUTH_TIMEOUT_SECONDS
|
||||
|
||||
def open_authentication(self) -> None:
|
||||
if self._uses_sms() or self._uses_quick() or not self._flow_active() or not self._prepare_identity():
|
||||
return
|
||||
try:
|
||||
self.identity_view.load_authentication(authentication_url(self.state.get("auth_url")))
|
||||
self.identity_view.show()
|
||||
if not self._native_hide_pending:
|
||||
self.poll_timer.start()
|
||||
self.banner.show_message("请在本窗口完成医生身份验证。通过后会显示“确认签名”。", "info")
|
||||
except Exception as error:
|
||||
self._web_failed(self.identity_view, friendly_error(error))
|
||||
|
||||
def _flow_active(self) -> bool:
|
||||
return bool(self._intent and self.isVisible() and not self._closed and self._confirmed
|
||||
and not self._native_hide_pending
|
||||
and not self._identity_ready and not self._completion_sent
|
||||
and self._can_resume_identity())
|
||||
|
||||
def _within_deadline(self) -> bool:
|
||||
if self._auth_deadline is not None and monotonic() < self._auth_deadline:
|
||||
return True
|
||||
self._generation += 1
|
||||
self._stop_flow()
|
||||
self._retry_identity = True
|
||||
self._show_status("身份验证状态待确认")
|
||||
self.banner.show_message("本次验证检查已超过 10 分钟。请重新检查验证状态。", "warning")
|
||||
self._sync_actions()
|
||||
return False
|
||||
|
||||
def _poll_identity(self) -> None:
|
||||
if not self._flow_active():
|
||||
self.poll_timer.stop()
|
||||
return
|
||||
if self._within_deadline() and not self._busy:
|
||||
self._request("get_prescription_esign_identity_status")
|
||||
|
||||
def _apply_identity_status(self, *, check_only: bool, from_sms_verification: bool = False) -> None:
|
||||
if not self._flow_active() or not self._within_deadline():
|
||||
return
|
||||
identity = self.state["identity_status"]
|
||||
if self.state["can_complete"] or self.state["identity_details_required"]:
|
||||
self._await_confirmation()
|
||||
elif self._uses_quick():
|
||||
self._stop_flow()
|
||||
self._show_status("快捷签授权待核对")
|
||||
message = ("本张处方的快捷签准备已失效,请重新准备。" if identity in {"FAIL", "EXPIRED"}
|
||||
else "暂时无法核对快捷签授权,请重新检查。")
|
||||
self.banner.show_message(message, "warning")
|
||||
elif self._uses_sms():
|
||||
self._stop_flow()
|
||||
if identity in {"FAIL", "EXPIRED"}:
|
||||
message = "验证码已失效。请重新发送验证码。"
|
||||
elif from_sms_verification or identity in {"UNAVAILABLE", "SUCCESS"}:
|
||||
message = "验证码未通过。请检查后重试,或重新发送验证码。"
|
||||
else:
|
||||
message = "请输入医生绑定手机收到的验证码。"
|
||||
self.banner.show_message(message, "info")
|
||||
elif identity in {"FAIL", "EXPIRED"}:
|
||||
self._stop_flow()
|
||||
outcome = "身份验证未通过" if identity == "FAIL" else "签署授权已失效"
|
||||
self._show_status(outcome)
|
||||
self.banner.show_message(f"{outcome}。请重新验证医生身份。", "warning")
|
||||
elif identity in {"UNAVAILABLE", "SUCCESS"}:
|
||||
self._stop_flow()
|
||||
self._retry_identity = True
|
||||
self._show_status("身份验证状态待确认")
|
||||
self.banner.show_message("暂时无法确认签名条件,请重试验证状态。", "warning")
|
||||
elif check_only:
|
||||
self._stop_flow()
|
||||
self.banner.show_message("请继续完成医生身份验证。", "info")
|
||||
elif self.identity_view is None:
|
||||
self.open_authentication()
|
||||
else:
|
||||
self.banner.show_message("请在本窗口完成医生身份验证。通过后会显示“确认签名”。", "info")
|
||||
|
||||
def _await_confirmation(self) -> None:
|
||||
deadline = self._auth_deadline
|
||||
self._stop_flow()
|
||||
self._auth_deadline = deadline
|
||||
self._identity_ready = True
|
||||
self._identity_details_required = self.state["identity_details_required"]
|
||||
label = "快捷签授权已核对" if self._uses_quick() else "短信验证码已通过" if self._uses_sms() else (
|
||||
"身份验证已通过,待绑定签署证书" if self._identity_details_required else "身份验证已通过")
|
||||
self._show_status(label)
|
||||
self.identity_details_container.setVisible(self._identity_details_required)
|
||||
self.banner.show_message("请确认签名并完成当前处方。", "info")
|
||||
self._sync_actions()
|
||||
if self._identity_details_required:
|
||||
self.identity_number_input.setFocus()
|
||||
|
||||
def cancel_binding(self) -> None:
|
||||
if not self._identity_details_required or self._busy:
|
||||
return
|
||||
self._generation += 1
|
||||
self._stop_flow()
|
||||
self.banner.show_message("已取消本次证书绑定,可重新检查验证状态。", "info")
|
||||
self._sync_actions()
|
||||
|
||||
def bind_certificate(self) -> None:
|
||||
if self._identity_details_required:
|
||||
self.confirm_sign()
|
||||
|
||||
def confirm_sign(self) -> None:
|
||||
if not (self.sign_button.isEnabled() and self.isVisible() and self._identity_ready):
|
||||
return
|
||||
if not self._within_deadline():
|
||||
return
|
||||
identity_number = ""
|
||||
if self._identity_details_required:
|
||||
try:
|
||||
identity_number = certificate_identity_number(self.identity_number_input.text())
|
||||
except ValueError as error:
|
||||
self.identity_number_input.clear()
|
||||
self.banner.show_message(str(error), "warning")
|
||||
self.identity_number_input.setFocus()
|
||||
return
|
||||
# Latch before dispatch. Only an authoritative recoverable state may re-enable signing.
|
||||
self._completion_sent = True
|
||||
self._stop_flow()
|
||||
self._show_status("正在签名")
|
||||
self.banner.show_message("正在签署处方,请稍候…", "info")
|
||||
self._request("complete_prescription_esign", identity_number=identity_number)
|
||||
|
||||
def verify_original(self) -> None:
|
||||
if self.verify_button.isEnabled() and self.isVisible():
|
||||
self.banner.show_message("正在核验已归档的签署原件…", "info")
|
||||
self._request("verify_prescription_esign")
|
||||
|
||||
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.banner)
|
||||
|
||||
def download_to(self, path: str | Path | None = None, on_success: Callable[[], None] | None = None) -> None:
|
||||
if not self.download_button.isEnabled():
|
||||
return
|
||||
self._busy = True
|
||||
generation = self._generation
|
||||
repository, prescription_id = self.repository, self.prescription_id
|
||||
self._sync_actions()
|
||||
|
||||
def work() -> tuple[dict[str, Any], Path | None]:
|
||||
state = esign_status(repository.get_prescription_esign_status(prescription_id))
|
||||
if not state["can_download"]:
|
||||
return state, None
|
||||
return state, save_signed_original(repository, prescription_id, state["environment"], path)
|
||||
|
||||
def current() -> bool:
|
||||
return isValid(self) and not self._closed and generation == self._generation
|
||||
|
||||
def saved(result: tuple[dict[str, Any], Path | None]) -> None:
|
||||
if current():
|
||||
state, output = result
|
||||
if output is None:
|
||||
self._apply_state(state)
|
||||
return
|
||||
if path is None:
|
||||
self._saved_original = output
|
||||
self.banner.show_message("已保存到工作站,并通过 SHA-256 校验。可打开已保存原件。", "success")
|
||||
else:
|
||||
self.banner.show_message("已签原件已下载,并通过 SHA-256 校验。", "success")
|
||||
if on_success:
|
||||
on_success()
|
||||
|
||||
def failed(error: Exception) -> None:
|
||||
if current():
|
||||
self.banner.show_message(f"下载签署原件失败。{friendly_error(error)} 请重试下载。", "warning")
|
||||
|
||||
def finished() -> None:
|
||||
if isValid(self):
|
||||
self._busy = False
|
||||
if not self._closed:
|
||||
self._sync_actions()
|
||||
|
||||
run_async(work, on_success=saved, on_error=failed, on_finished=finished)
|
||||
@@ -45,15 +45,24 @@ 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 ..icons import icon
|
||||
from ..infinite_list import InfiniteList
|
||||
@@ -240,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:
|
||||
@@ -1858,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:
|
||||
@@ -1943,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:
|
||||
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(
|
||||
@@ -1969,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",
|
||||
@@ -1987,41 +1997,55 @@ 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,
|
||||
),
|
||||
on_success=lambda _result: self._prescription_updated(generation),
|
||||
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),
|
||||
)
|
||||
|
||||
def _prescription_updated(self, generation: int) -> None:
|
||||
def _prescription_updated(self, generation: int, prescription: Any = None) -> None:
|
||||
if generation != self._action_generation:
|
||||
return
|
||||
self.banner.show_message("处方已保存并重新进入待审核。", "success")
|
||||
message, kind = saved_prescription_message(prescription, "处方已保存并重新进入待审核。")
|
||||
self.banner.show_message(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 _begin_case_record_load(self, row: Any) -> None:
|
||||
snapshot = deepcopy(row)
|
||||
diagnosis_id = _diagnosis_id(snapshot)
|
||||
@@ -2098,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)
|
||||
@@ -2111,27 +2146,29 @@ 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),
|
||||
on_success=lambda _result: self._prescription_created(generation),
|
||||
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),
|
||||
)
|
||||
|
||||
def _prescription_created(self, generation: int) -> None:
|
||||
def _prescription_created(self, generation: int, prescription: Any = None) -> None:
|
||||
if generation != self._action_generation:
|
||||
return
|
||||
self.banner.show_message("处方已开具并提交审核。", "success")
|
||||
message, kind = saved_prescription_message(prescription, "处方已开具并提交审核。")
|
||||
self.banner.show_message(message, kind)
|
||||
self.refresh(silent=True)
|
||||
resume_saved_prescription(self.repository, prescription, self)
|
||||
|
||||
def _prescription_error(self, error: Exception, generation: int) -> None:
|
||||
if generation == self._prescription_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,7 +84,19 @@ 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 ..infinite_list import InfiniteList
|
||||
from ..prescriptions_style import prescriptions_stylesheet
|
||||
@@ -363,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)
|
||||
@@ -423,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"
|
||||
|
||||
|
||||
@@ -443,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
|
||||
@@ -451,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 "主方"
|
||||
@@ -592,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:
|
||||
@@ -1197,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
|
||||
@@ -1410,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
|
||||
)
|
||||
@@ -1548,7 +1588,7 @@ class PrescriptionsPage(QWidget):
|
||||
def _action_button(
|
||||
self,
|
||||
text: str,
|
||||
permission: str,
|
||||
permission: str | None,
|
||||
handler: Callable[[], None],
|
||||
*,
|
||||
danger: bool = False,
|
||||
@@ -1561,6 +1601,7 @@ class PrescriptionsPage(QWidget):
|
||||
"查看": "eye",
|
||||
"编辑": "pencil",
|
||||
"删除": "trash",
|
||||
"重新开方": "plus",
|
||||
}.get(text)
|
||||
if icon_kind:
|
||||
button.setIcon(
|
||||
@@ -1569,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
|
||||
@@ -1707,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:
|
||||
@@ -1785,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",
|
||||
@@ -1794,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",
|
||||
@@ -1809,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()
|
||||
|
||||
@@ -1893,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()
|
||||
|
||||
@@ -2090,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
|
||||
@@ -2163,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(
|
||||
@@ -2177,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"):
|
||||
@@ -2230,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()
|
||||
@@ -2248,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(
|
||||
@@ -2258,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)
|
||||
@@ -2301,10 +2430,18 @@ class PrescriptionsPage(QWidget):
|
||||
message = "处方已新增并提交审核。"
|
||||
run_async(
|
||||
operation,
|
||||
on_success=lambda _result: self._mutation_success(message),
|
||||
on_success=lambda result: self._prescription_saved(result, message),
|
||||
on_error=self._mutation_error,
|
||||
on_finished=lambda: self._set_mutation_pending(False),
|
||||
)
|
||||
|
||||
def _prescription_saved(self, prescription: Any, fallback: str) -> None:
|
||||
message, kind = saved_prescription_message(prescription, fallback)
|
||||
self.banner.show_message(message, kind)
|
||||
show_toast(self, message, kind, 3600)
|
||||
self.refresh()
|
||||
if resume_saved_prescription(self.repository, prescription, self):
|
||||
self._mutation_success("电子签署已完成,处方等待审核。")
|
||||
|
||||
def _delete_selected(self) -> None:
|
||||
row = self._selected()
|
||||
@@ -2312,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(
|
||||
@@ -2363,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
|
||||
@@ -929,6 +1129,7 @@ def test_prescription_pdf_export_writes_visible_content(
|
||||
tmp_path: Any,
|
||||
) -> None:
|
||||
prescription = {
|
||||
"esign": {"enabled": False, "required": False, "environment": "sandbox", "status": "legacy", "can_sign": False, "can_download": False},
|
||||
"id": 12,
|
||||
"sn": "CF-12",
|
||||
"patient_name": "林晓岚",
|
||||
|
||||
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,38 @@
|
||||
# Admin 处方 e签宝接入交付
|
||||
|
||||
完成日期:2026-11-17。仅修改 `admin/` 与本文档;未读写密钥、未调用真实签署服务。当前 checkout 无 `.trellis/`。
|
||||
|
||||
## 实现范围
|
||||
|
||||
- `admin/src/api/tcm.ts`:新增有类型的 `esignConfig`、`esignStatus`、`esignStart`、`esignComplete`、`esignDownload` 请求,严格沿用约定 DTO。
|
||||
- `admin/src/components/EsignPrescriptionPanel.vue`:复用电子签面板,展示服务端状态、说明及沙箱标签;按 `can_sign` 发起/重试、获取 HTTPS 核身链接、完成核身后继续签署;按 `can_download` 下载原始已签 PDF;详情重新打开即查状态,可恢复待签。
|
||||
- `admin/src/hooks/usePrescriptionEsignConfig.ts`:加载签署开关,合并并发配置查询;配置失败时禁保存并给重试,不把查询失败当作 disabled。
|
||||
- `admin/src/components/tcm-prescription/index.vue`:覆盖诊单、预约 PC/H5 使用的共享开方入口。enabled 时移除手写必填并显示“保存后核身签署”;保存后保留已保存处方与签署面板。保存成功但详情请求失败时保留 id,避免界面返回新建表单导致重复新增。
|
||||
- `admin/src/views/consumer/prescription/index.vue`:独立新增/编辑入口采用相同开关及保存后签署流程;查看详情承载同一面板,重新进入即可继续。
|
||||
- `admin/src/views/consumer/prescription/order_list.vue`、`order_list_h5.vue`:订单中的处方预览亦有签署面板,PDF 下载走相同原件分流,避免主要开方页修复后订单页继续重绘已签 PDF。
|
||||
- `admin/src/utils/prescription-esign.ts`:HTTPS 链接校验;签后 PDF 下载前查服务端最新状态;只允许 legacy 走本地渲染,其余状态按服务端下载权限处理。对 base64 解码后原始 PDF 字节做 SHA-256 校验,校验成功才创建 PDF Blob;不会经过 canvas/jsPDF。损坏文件、非 PDF、缺失哈希、不支持 Web Crypto 的非安全页面均停止下载并提示。
|
||||
|
||||
核身链接通过明确的“打开核身页面”操作打开新页,包含 `noopener noreferrer`。没有 iframe、postMessage、前端回调成功推断或本地“已签”状态写入;继续签署及刷新只采用后端 DTO。旧手写流程仅在配置明确 disabled 时保留。
|
||||
|
||||
## 验证
|
||||
|
||||
执行:
|
||||
|
||||
```powershell
|
||||
cd D:\web\zyt\admin
|
||||
node --test tests/prescription-esign.test.cjs tests/prescription-aux-bag-count.test.cjs tests/prescription-order-tracking.test.cjs
|
||||
npm run type-check
|
||||
git diff --check -- admin
|
||||
```
|
||||
|
||||
- 39 项 Node 测试通过,其中新增 15 项,覆盖链接协议、PDF 哈希、下载字节原样保留、待签禁止伪下载、legacy 分流、配置失败与重试、核身未完成、网络失败、重复点击、跨处方迟到响应、共享表单启用/禁用分支、保存后详情失败及独立表单保存后留在签署页面。5 个涉及的 Vue SFC 完整 script/template 编译通过。
|
||||
- `git diff --check -- admin` 通过。保留原文件混合换行格式,未制造全文件格式化差异。
|
||||
- 全量 `npm run type-check` 退出码 2,共 62 条诊断。新增电子签组件、工具、hook、API 无诊断;对全部错误定位行与 HEAD 源码逐条比对,均为未修改的原代码行(包含地区数据 `never[]`、`searchPatientsAPI` 缺失、既有 Cascader/Tree 类型等)。未扩大范围修复项目既有类型问题。检查原始输出保留在本地忽略文件 `admin/tests/esign-typecheck.log`。vue-tsc 自动改写的 `tsconfig.tsbuildinfo` 已恢复到任务开始版本。
|
||||
|
||||
## 联调与边界
|
||||
|
||||
- 未进行浏览器登录后的端到端实签或供应商沙箱核身;需要后端部署、迁移与沙箱配置完成后以测试医生/测试处方验证。
|
||||
- 浏览器需 HTTPS(或浏览器认可的 localhost 安全环境)以运行 SHA-256 Web Crypto 校验。
|
||||
- `esignStart`/`esignComplete`/`esignStatus` 的 `can_sign`、`can_download`、`required`、`status`、`environment` 应按约定返回布尔/枚举值;UI 不自行授权签署。
|
||||
- 签后内容修改、审核/药房门禁由服务端负责。本任务未修改这些业务权限判断。
|
||||
- 未改未被主要页面引用的旧 `views/tcm/appointment/components/prescription-drawer.vue`;实际预约、诊单入口使用已覆盖的共享 `tcm-prescription`。
|
||||
@@ -0,0 +1,57 @@
|
||||
# e签宝后端编排审查与修复
|
||||
|
||||
2026-11-17,已完成。范围:`PrescriptionEsignService.php`、`PrescriptionEsignPolicy.php`、`PrescriptionPdf.php`、`PrescriptionEsignFlowTest.php`。本轮未修改处方/订单 Logic、Controller、配置、迁移或部署命令;真实适配器无新增修改。
|
||||
|
||||
## 已修复的问题
|
||||
|
||||
| 问题 | 修复与证据 |
|
||||
| --- | --- |
|
||||
| 每次 start/complete/recover 重复 initialize 全局 SDK | 移除全部业务初始化;只保留部署命令负责显式初始化。流程测试验证 `Fake::$initializes === 0`。SDK 跨应用或环境必须重启 JVM 后初始化。 |
|
||||
| 明确签署业务拒绝与“已签但结果不明”混为一谈 | `PrescriptionEsignService.php:289` 区分 provider 明确拒绝和 `EsignOutcomeUnknownException`;明确拒绝可重新发起新核身,旧 flow 被清空。签后验签、归档失败始终 uncertain,绝不重新签署。 |
|
||||
| unknown 异常中已知供应商流水丢失 | 捕获 `EsignOutcomeUnknownException::signServiceId` 并保存 sign_service_id/account_id。无本地签后文件时 recover 拒绝执行并要求人工核对。 |
|
||||
| 签署成功但磁盘保存失败会丢流水 | `PrescriptionEsignService.php:274` 在写 signed.pdf 之前先通过处方行锁保存供应商流水及账号。文件写入失败仍保留核对依据,临时文件失败时清理。 |
|
||||
| 核身开始后出现新的账号绑定,会错误复用未绑定 flow | start 在证据行记录本次 flow 的预绑定 account_id。complete 校验本次绑定与当前账号一致;并发首次绑定或账号替换必须重新核身,不以姓名相同代替绑定。首次成功 createPerson 后立即记住其 flow→account 绑定。 |
|
||||
| 核身响应未校验对应 flow/app | `PrescriptionEsignService.php:211` 强制响应 flowId 匹配当前记录;出现 appId 时须匹配应用。保留 SUCCESS、INDIVIDUAL、姓名、身份证类型与号码格式检查。每次 signer 锁定都复核当前 Admin.name 与处方医生一致。 |
|
||||
| 签署发送前缺少第二次内容/账号检查 | 在供应商准备结束后重新锁处方,检查 operation_token、signing 状态、snapshot_hash、当前账号;在此之前读取并校验私有 source.pdf 的 SHA-256。准备期间作废/改内容都不会发送签署。 |
|
||||
| 恢复验签后遗漏展示签章图片 | recover 仅读已归档原件并再次验签;从验签返回、证书姓名匹配的签名中恢复 sealData,保留原件,完全不调用 signPdf。 |
|
||||
| 恢复可能面对内容已变的处方 | recover 先锁处方并校验冻结快照;最终 finishOperation 再检查 token/hash 和作废状态。迟到结果可保留证据,但无法把已作废处方恢复为有效 signed。 |
|
||||
| 状态页会把已篡改处方显示为已签 | describe 对当前行与冻结快照再次比较;不匹配显示 uncertain,禁用签署。历史签后原件仍可按授权下载用于核对。 |
|
||||
| 原始 DECIMAL 与 ORM float 指纹可能不同 | `PrescriptionEsignPolicy.php:21` 对 dosage_amount/amount 做稳定十进制规范化;空 JSON 字段统一为空值,hash(snapshot(row)) 保持幂等。 |
|
||||
| 通过审核的证据约束不完整 | `PrescriptionEsignPolicy.php:86` 除状态/hash 外,要求 signed_path、signed_at、account_id、签署流水,并校验 evidence 的处方 ID 和医生 ID 对应当前处方。 |
|
||||
| PDF 金额未输出 | `PrescriptionPdf.php:66` 补充冻结快照中的金额,保持 A4、每页 33 行和页一 x420/y70/width100 签章区域。 |
|
||||
|
||||
## 与真实适配器的契约核对
|
||||
|
||||
- `startIdentity(name, contextId, accountId)` 返回 `flow_id/auth_url`;SDK accountId 在请求 **indivInfo.sdkAccountId** 内,不是顶层字段。
|
||||
- `identityDetail(flowId)` 返回官方 `data`;身份信息为 `data.indivInfo.name/certNo/certType`,主体为 `data.objectType`、状态为 `data.status`。`indivInfo.accountId` 是独立核身服务身份标识,**不能当 SDK 签署 accountId 比较**;业务使用发起核身时明确传入并保存的 SDK 绑定。
|
||||
- `createPerson` 用刚完成的核身信息和 `identityAuthId` 创建/绑定 SDK 账号;证件号只短时存在内存,不入账号表、证据表或日志。测试检查持久化数据中没有合成证件号。
|
||||
- `signPdf` 返回二进制 `pdf` 与 `sign_service_id`。适配器非零明确业务码抛普通 provider 异常;传输/超时/空响应或成功缺文件抛 outcome unknown。
|
||||
- `verifyPdf` 返回 `['signatures' => [...]]`,并已经强制至少一签且所有 `signature.validate === true`;流程测试 fake 已改为此真实结构。
|
||||
- SDK 原始 HTTP、HMAC、multipart 和错误分类仍由 `EsignClientTest.php` 的 158 项离线检查覆盖;流程测试没有把完整真实身份证或服务密钥放入 fixture。
|
||||
|
||||
## 已执行验证
|
||||
|
||||
```powershell
|
||||
Set-Location D:\web\zyt\server
|
||||
php tests/PrescriptionEsignFlowTest.php
|
||||
php tests/EsignClientTest.php
|
||||
php -l app/common/service/esign/PrescriptionEsignService.php
|
||||
php -l app/common/service/esign/PrescriptionEsignPolicy.php
|
||||
php -l app/common/service/esign/PrescriptionPdf.php
|
||||
```
|
||||
|
||||
结果:**64 项流程检查通过**(真实 ORM + 隔离 SQLite + 私有临时目录,只有供应商被替换);**158 项适配器检查通过**;三个修改过的服务文件语法检查通过。
|
||||
|
||||
新增覆盖包括:明确业务拒绝后必须新核身、已知 unknown 流水保留、签后归档失败、验签业务错误仍不允许重签、认证过期、flow 回错、账号替换/首次绑定竞争、超时 signing 租约不释放、签前内容变化/作废、恢复时内容变化、冻结文件篡改、账号改名、证明归属、身份证件不持久化、DECIMAL/float 指纹一致,以及 65 味药的多页 PDF 不截断和金额出现。
|
||||
|
||||
已用桌面环境的 QPdfDocument 加载并渲染测试 PDF,确认 A4 `595×842`、中文内容及固定签章留白正常。预览:`artifacts/esign-backend-review.png`;原 PDF:`artifacts/esign-prescription-test.pdf`。预览仅含合成患者/医生信息。
|
||||
|
||||
## 集成侧仍需保持的边界
|
||||
|
||||
1. **外部审核事务**:处方审核、订单处方审核及发药必须在同一处方行锁事务中执行 `assertSignedById` 和最终业务状态写入。仅调用检查后在另一事务更新,会留下 concurrent void 窗口。此点已通知负责 Logic 的根代理,未越界修改其文件。
|
||||
2. **数据库故障无法提供原子外部签署**:如果供应商已完成签署、同时本地数据库与文件持久化都失败,无法承诺自动恢复。状态必须保持 signing/uncertain,使用供应商流水人工核对,禁止自动重签。
|
||||
3. **真实 SDK 集成尚未验证**:本轮没有运行真实核身或签署。部署实际 PaaS-SDK-Service、初始化应用及完成医生人工核身后,仍需执行沙箱签署/验签/下载闭环;不能用离线测试结果宣称已真实签署成功。
|
||||
|
||||
本轮承诺的审查、修复、回归测试和交付文件均已完成。
|
||||
|
||||
根侧集成修复已完成:处方审核、订单审核、手工调整审核状态在同一事务中锁处方并更新;药房提交占用也在处方锁内检查生产签署。MySQL 增至 18 项检查,独立连接在三个审核写入边界尝试作废均被行锁阻止。适配器补充官方沙箱长链端口校验后增至 168 项检查。完整结果以 `docs/plans/esign-prescription-integration.md` 为准。
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 81 KiB |
@@ -0,0 +1,61 @@
|
||||
# 医生工作站 e签宝桌面接入实现
|
||||
|
||||
日期:2026-11-17。实现范围为 `app/`,与服务端 SDK3.0 沙箱接入共享 API 契约;桌面不保存供应商凭据、不直接请求供应商签署 API。
|
||||
|
||||
## 已实现行为
|
||||
|
||||
- 处方编辑器异步读取 `esignConfig`。启用时隐藏手写板,说明保存后由开方医生核身签署;关闭时保留原手写校验。配置读取失败会禁用保存,并提供重试,避免把未知配置当成未启用。
|
||||
- 新建及编辑返回的 `esign` 在 `Prescription.from_dict`、模型字段和 `to_api_dict` 中保留。Repository 在真正发送 add/edit 请求前剔除该只读字段,客户端不能通过提交 `signed` 宣告完成。
|
||||
- 已开处方页、预约页、诊单中的新建和编辑均使用共享保存提示及签署对话框。待签仅提示“已保存,尚待完成电子签署”;关闭窗口后可以从详情恢复。预约中已有电子签署处方进入详情,避免为继续签署而再次保存处方。
|
||||
- 共享签署对话框提供发起/继续核身、重新打开核身页面、核身后确认签署、查询结果、下载原件。只有服务端状态响应能够显示已签;打开浏览器和点击完成本身不改变签署结果。
|
||||
- 仅允许 HTTPS 官方短链 `smlt.esign.cn`(沙箱)和 `t.esign.cn`(正式),拒绝其他主机、用户名密码、非 443 端口及本地/脚本协议。服务端应返回 shortLink,桌面不接收供应商长链接。
|
||||
- 发起和完成动作均检查服务端 `can_sign`;仅 pending/failed/authenticating 提供发起/继续。uncertain、signed、voided 不会直接重签。网络错误后禁用变更动作,要求先查询恢复;请求进行中防重复点击。
|
||||
- 签署内容冻结与服务端规则一致:`required=true` 且非 pending/legacy 的处方禁止从编辑器提交内容修改,提示作废后新开。
|
||||
- 详情新增电子签署入口和状态提示。电子签署处方的导出直接下载服务端 `content_base64`,检查 PDF 文件头及 SHA-256 后写入用户选择的路径,不使用 `QPdfWriter` 重绘已签原件。普通历史手写方与病历原有导出保留。
|
||||
- Repository protocol、RemoteDoctorRepository、DemoDoctorRepository 同步增加五个签署方法;演示默认 disabled/sandbox/legacy,创建、编辑及详情返回对应状态,不产生虚假已签原件。
|
||||
|
||||
## API 映射
|
||||
|
||||
| Repository 方法 | 请求 |
|
||||
| --- | --- |
|
||||
| `get_prescription_esign_config()` | GET `tcm.prescription/esignConfig` |
|
||||
| `get_prescription_esign_status(id)` | GET `tcm.prescription/esignStatus`,参数 `{id}` |
|
||||
| `start_prescription_esign(id)` | POST `tcm.prescription/esignStart`,正文 `{id}` |
|
||||
| `complete_prescription_esign(id)` | POST `tcm.prescription/esignComplete`,正文 `{id}` |
|
||||
| `download_prescription_esign(id)` | GET `tcm.prescription/esignDownload`,参数 `{id}` |
|
||||
|
||||
## 主要文件
|
||||
|
||||
- `app/src/doctor_workstation/core/esign.py`:DTO 校验、官方短链校验、PDF 原件解码及 SHA-256 校验。
|
||||
- `app/src/doctor_workstation/core/models.py`:保留响应中的 esign。
|
||||
- `app/src/doctor_workstation/services/repository.py`:协议声明及远端五个 API。
|
||||
- `app/src/doctor_workstation/services/mock_repository.py`:默认关闭的演示实现。
|
||||
- `app/src/doctor_workstation/ui/dialogs/prescription_esign.py`:共享签署对话框、保存后待签提示及恢复入口。
|
||||
- `app/src/doctor_workstation/ui/dialogs/prescription.py`:编辑器能力加载、冻结提示、详情状态及原件导出。
|
||||
- `app/src/doctor_workstation/ui/pages/prescriptions.py`、`ui/pages/appointments.py`、`ui/dialogs/diagnosis.py`:新建/编辑保存结果接入。
|
||||
- `app/tests/test_prescription_esign.py`:30 个离线行为及契约测试。
|
||||
|
||||
## 实际验证
|
||||
|
||||
以下命令已执行,未使用真实患者身份、未调用真实供应商:
|
||||
|
||||
```powershell
|
||||
Set-Location D:\web\zyt\app
|
||||
$env:QT_QPA_PLATFORM = 'offscreen'
|
||||
.\.venv\Scripts\python.exe -m pytest tests/test_prescription_esign.py tests/test_prescription_ui.py tests/test_prescription_security_ui.py tests/test_repository_parity.py tests/test_appointments_parity_ui.py tests/test_diagnosis_detail_contract.py -ra
|
||||
```
|
||||
|
||||
结果:`139 passed in 7.46s`,其中新测试 30 个、原有定向回归 109 个。
|
||||
|
||||
覆盖核身页面打开但未签、点击完成仍未通过认证、查询后才确认已签、非签署人权限、uncertain 禁止重签、网络错误后恢复、无效 DTO、恶意链接、签后原件字节保持及哈希不一致不覆盖、配置开关、配置加载错误恢复、冻结状态拦截,以及三个入口向共享流程交付服务器返回的 DTO。
|
||||
|
||||
```powershell
|
||||
.\.venv\Scripts\python.exe -m ruff check src/doctor_workstation/core/esign.py src/doctor_workstation/ui/dialogs/prescription_esign.py tests/test_prescription_esign.py
|
||||
.\.venv\Scripts\python.exe -m ruff check --select F src/doctor_workstation/core/esign.py src/doctor_workstation/core/models.py src/doctor_workstation/services/repository.py src/doctor_workstation/services/mock_repository.py src/doctor_workstation/ui/dialogs/prescription.py src/doctor_workstation/ui/dialogs/prescription_esign.py src/doctor_workstation/ui/dialogs/diagnosis.py src/doctor_workstation/ui/pages/prescriptions.py src/doctor_workstation/ui/pages/appointments.py
|
||||
```
|
||||
|
||||
结果均为 `All checks passed!`。修改模块 Python 编译检查通过;`git diff --check -- app` 无错误。
|
||||
|
||||
## 联调边界
|
||||
|
||||
实际核身和签署结果仍取决于后端沙箱配置、医生账号绑定及供应商响应,本次未运行真实沙箱签署。桌面使用后端 environment 显示沙箱提示,沙箱签署不会由桌面升级为生产签署。服务端仍是签署主体、访问权限、内容冻结、幂等、审核与正式发药门禁的最终执行者。
|
||||
@@ -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)。仅整理证据,未发送对外消息或工单。
|
||||
@@ -0,0 +1,54 @@
|
||||
%PDF-1.4
|
||||
%âãÏÓ
|
||||
1 0 obj
|
||||
<< /Type /Catalog /Pages 2 0 R >>
|
||||
endobj
|
||||
2 0 obj
|
||||
<< /Type /Pages /Kids [6 0 R] /Count 1 >>
|
||||
endobj
|
||||
3 0 obj
|
||||
<< /Type /Font /Subtype /Type0 /BaseFont /STSong-Light /Encoding /UniGB-UCS2-H /DescendantFonts [4 0 R] >>
|
||||
endobj
|
||||
4 0 obj
|
||||
<< /Type /Font /Subtype /CIDFontType0 /BaseFont /STSong-Light /CIDSystemInfo << /Registry (Adobe) /Ordering (GB1) /Supplement 4 >> /FontDescriptor 5 0 R /DW 1000 /W [1 95 500] >>
|
||||
endobj
|
||||
5 0 obj
|
||||
<< /Type /FontDescriptor /FontName /STSong-Light /Flags 6 /FontBBox [-25 -254 1000 880] /ItalicAngle 0 /Ascent 880 /Descent -254 /CapHeight 880 /StemV 80 >>
|
||||
endobj
|
||||
6 0 obj
|
||||
<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] /Resources << /Font << /F1 3 0 R >> >> /Contents 7 0 R >>
|
||||
endobj
|
||||
7 0 obj
|
||||
<< /Length 1501>>
|
||||
stream
|
||||
BT /F1 20 Tf 1 0 0 1 235 795 Tm <4e2d533b590465b97b3a> Tj ET
|
||||
BT /F1 12 Tf 1 0 0 1 170 770 Tm <6c997bb16d4b8bd565874ef6002000b700204e0d75284e8e6b635f0f53d1836f> Tj ET
|
||||
BT /F1 11 Tf 1 0 0 1 45 738 Tm <590465b97f1653f7ff1a00520058002d0054004500530054002d0032> Tj ET
|
||||
BT /F1 11 Tf 1 0 0 1 45 720 Tm <65e5671fff1a0032003000320036002d00310031002d00310037> Tj ET
|
||||
BT /F1 11 Tf 1 0 0 1 45 702 Tm <60a38005ff1a865a67846d4b8bd560a3800500200020002000206027522bff1a753700200020002000205e749f84ff1a00330030> Tj ET
|
||||
BT /F1 11 Tf 1 0 0 1 45 684 Tm <80547cfb75358bddff1a00310033003800300030003000300030003000300030> Tj ET
|
||||
BT /F1 11 Tf 1 0 0 1 45 666 Tm <4e345e8a8bca65adff1a4ec575284e8e8f6f4ef66d4b8bd5> Tj ET
|
||||
BT /F1 11 Tf 1 0 0 1 45 648 Tm <836f54c100200031ff1a752891cf0020003100300020002f0020836f540d00206d4b8bd5836f67500020002f002053554f4d00200067> Tj ET
|
||||
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 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 <0039003300660065006100390065006300610063003400310064003700300031003400370032006200330036003800610036006400350030003000330035003400330033003400620034006300390032003600370035006600320066006100300062003800660033003300370036006100380063006100320036003000300032> Tj ET
|
||||
BT /F1 9 Tf 1 0 0 1 515 30 Tm <00310020002f00200031> Tj ET
|
||||
endstream
|
||||
endobj
|
||||
xref
|
||||
0 8
|
||||
0000000000 65535 f
|
||||
0000000015 00000 n
|
||||
0000000064 00000 n
|
||||
0000000121 00000 n
|
||||
0000000243 00000 n
|
||||
0000000437 00000 n
|
||||
0000000609 00000 n
|
||||
0000000735 00000 n
|
||||
trailer << /Size 8 /Root 1 0 R >>
|
||||
startxref
|
||||
2286
|
||||
%%EOF
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 50 KiB |
@@ -0,0 +1,83 @@
|
||||
# e签宝 SDK3.0 适配层交付
|
||||
|
||||
2026-11-17。仅实现 provider adapter、配置样例及离线测试;未改处方业务文件,未使用真实凭据、医生信息或患者文件,未调用真实核身/签署。
|
||||
|
||||
## 交付文件
|
||||
|
||||
- `server/app/common/service/esign/EsignClient.php`:独立 v2 核身 HTTP API + 本地 PaaS-SDK-Service 的 SDK3.x HTTP API;可注入 transport/毫秒时钟。
|
||||
- `server/config/esign.php`:`enabled`、`environment`、`app_id`、`app_secret`、`sdk_url`、`timeout`,全部从 `env('esign.*')` 读取。
|
||||
- `server/.env.esign.example`:空凭据样例,默认 disabled/sandbox;本地 SDK 默认 `http://127.0.0.1:8091/paas-sdk-service`。
|
||||
- `server/tests/EsignClientTest.php`:纯离线 PHP 测试,无框架初始化、数据库或网络。
|
||||
|
||||
## 业务层调用约定
|
||||
|
||||
```php
|
||||
$client = new \app\common\service\esign\EsignClient();
|
||||
$client->assertConfigured();
|
||||
// initialize() 是 SDK 服务启动后的显式管理操作,非每次业务请求自动调用。
|
||||
$identity = $client->startIdentity($doctorName, $contextId, $existingAccountId);
|
||||
// identity: ['flow_id' => '...', 'auth_url' => '...']
|
||||
$detail = $client->identityDetail($identity['flow_id']); // 官方 data,包含敏感身份信息,不可原样回前端/写日志。
|
||||
$client->checkWillingness($identity['flow_id']);
|
||||
// 业务层必须确认 detail.status === SUCCESS 且身份/姓名与处方创建医生绑定。
|
||||
$accountId = $client->createPerson($nameFromVerifiedDetail, $idNoFromVerifiedDetail, $identity['flow_id']);
|
||||
$seal = $client->createSeal($accountId);
|
||||
$signed = $client->signPdf($accountId, $identity['flow_id'], $seal, $frozenPdf, $fileName);
|
||||
$verification = $client->verifyPdf($signed['pdf']);
|
||||
// signed: ['sign_service_id' => '...', 'pdf' => binary]
|
||||
// verification: ['signatures' => [...]],至少一个签名且所有 signature.validate 必须严格为 true。
|
||||
```
|
||||
|
||||
方法不会自动执行相邻步骤:业务层负责冻结文件、身份与处方绑定、事务状态和持久化。签名位置固定为 `Single`、页 `1`、左下角原点 `x=420,y=70,width=100`;模板必须保持该位置可签。`dstPdfFile` 不传,让 SDK 返回 Base64 `stream`,适配层严格解码为 PDF 二进制。
|
||||
|
||||
`startIdentity` 锁定 name/certType,证件类型为大陆身份证;已有 SDK 账号时放在官方字段 **indivInfo.sdkAccountId**。不主动发送认证短信(没有 receiveUrlMobileNo),不配置通知回调,业务层通过 detail 主动查询。返回认证链接只接受对应环境官方 HTTPS 域名;不接受其它网址或跨环境链接。
|
||||
|
||||
## 初始化、环境及错误处理
|
||||
|
||||
`initialize()` 调用 `/timevale/init`,提交 `projectConfig`、`httpConfig`、`signConfig`。环境严格映射:
|
||||
|
||||
| environment | 独立核身 API | SDK 初始化地址 |
|
||||
| --- | --- | --- |
|
||||
| sandbox | `https://smlopenapi.esign.cn` | `https://smlitsm.tsign.cn:8083/tgmonitor/rest/app!getAPIInfo2` |
|
||||
| production | `https://openapi.esign.cn` | `https://sdkapi.esign.cn/tgmonitor/rest/app!getAPIInfo2` |
|
||||
|
||||
配置不允许自定义这两个云端地址。SDK 云端通信固定 HTTPS、HMACSHA256、retry=0。SDK 本地 URL 的 HTTP 只允许 localhost、loopback 或 RFC1918 IPv4;其它主机须用有效证书的 HTTPS。**已经初始化的 JVM 切换 app/environment 必须先重启**;适配层不能通过重复调用 init 验证服务内部已经切换环境,部署需遵守此约束。
|
||||
|
||||
`EsignProviderException` 和 `EsignOutcomeUnknownException` 均定义在 `EsignClient.php` 中;实例化 client 后可直接 catch。公开错误只有操作名和固定错误码/供应商数值码,不拼接 msg/message、URL、身份证件、响应体或底层异常,且不附 previous exception。
|
||||
|
||||
- 非零明确业务码:`EsignProviderException`,`providerCode=PROVIDER_<number>`。
|
||||
- 签署发出后超时、传输失败、HTTP 非 2xx、空响应、无效 JSON/响应:`EsignOutcomeUnknownException`;不能自动重试签署。
|
||||
- 供应商声称成功但缺失/损坏签后 PDF:同样为 unknown,若已有签署记录 ID 则通过异常的 `signServiceId` 属性保留,供核对恢复。
|
||||
- 普通查询/制章的相同故障为普通 provider exception。
|
||||
- 客户端没有重试循环;原生 cURL 禁止跳转,开启 TLS peer/host 验证,响应上限 64 MiB,输入/签后 PDF 上限 20 MiB,超时配置 1~300 秒。
|
||||
|
||||
适配层不实现供应商签署结果恢复查询,因为本轮提供的 SDK 接口未包含一个可按本地业务请求幂等查询的签署接口。结果不明时应冻结该次请求交由业务层核对,不能直接把记录改成可重新签署。
|
||||
|
||||
## 官方依据
|
||||
|
||||
已阅读仓库保存的核身、有效期、印章、个人签署及验签正文;初始化和个人账户参数另直接读取官方页面核验:
|
||||
|
||||
- [初始化 SDK](https://open.esign.cn/doc/opendoc/paas_sdk_3/hgyqfsg1dgxwgvtc)
|
||||
- [创建个人签署账号](https://open.esign.cn/doc/opendoc/paas_sdk_3/feq5f4b4x450i0ya)
|
||||
- [个人用户 PDF 文件签署](https://open.esign.cn/doc/opendoc/paas_sdk_3/ssfyhyrcpwzlfr6d)
|
||||
- [官方鉴权签名计算工具](https://open.esign.cn/tools/signature)
|
||||
- [请求签名计算规则](https://open.esign.cn/doc/opendoc/paas_api/qudd9a/)
|
||||
|
||||
HTTP 核身鉴权的待签文本按 `method + LF + Accept + LF + Base64(MD5(body)) + LF + Content-Type + LF + empty Date + LF + resource path` 构建,使用 secret 对其 HMAC-SHA256 后 Base64。无 body 的 GET 使用空 MD5。UTF-8 JSON 序列化与发送字节严格一致。这里只复用网关鉴权规范,**没有调用 SaaS 合同或 SaaS 签约流程接口**。
|
||||
|
||||
## 验证结果
|
||||
|
||||
已实际执行:
|
||||
|
||||
```powershell
|
||||
Set-Location D:\web\zyt\server
|
||||
php tests/EsignClientTest.php
|
||||
php -l app/common/service/esign/EsignClient.php
|
||||
php -l config/esign.php
|
||||
```
|
||||
|
||||
结果:**158 checks passed (offline)**;两个 PHP 文件语法检查通过。
|
||||
|
||||
测试包括:禁用与缺失配置零请求、沙箱/生产地址绑定、init 禁用重试、POST/GET 固定 HMAC 向量、核身 SDK 账号嵌套、有效期及剩余次数、账号绑定 flow、制章身份来源、二进制 multipart 保真及 JSON part MIME、固定签名坐标、所有签名强校验、空响应/异常业务码/跳转/超时/传输异常、错误脱敏、签署结果不明且仅发一次请求、已知签署 ID 保留,以及拒绝非法/跨环境认证链接。
|
||||
|
||||
未执行真实集成:当前尚无 PaaS-SDK-Service 可用。本地服务部署、SDK 3.1.13+(有效期接口所需版本)、初始化成功、应用开通核身与签署权限后,再按新造的测试处方完成一次人工核身 → 签署 → 验签 → 原件下载闭环。
|
||||
@@ -0,0 +1,106 @@
|
||||
# e签宝本机 PaaS-SDK-Service 运行环境
|
||||
|
||||
安装日期: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。
|
||||
|
||||
- 下载文件:`C:\Users\pc\Downloads\PaaS-SDK-Service-ForWin.zip`,288,328,759 bytes。
|
||||
- 本机计算的 SHA256:`f107a5f67c0ebf7e1e1e1e0d012b6111637b26ce8599445090ffb931ebcf1b8d`。供应商页面未提供独立校验值,此哈希用于记录取得的文件,不代表独立签名验证。
|
||||
- 删除分发包中的示例应用凭据;`autoInit=false`,改为沙箱 HTTPS 初始化地址,`httpRetryTimes=0`。实际凭据仅由服务端忽略的 `.env` 读取后用于初始化,不写入命令行或启动脚本。
|
||||
- 已在隐藏窗口启动并确认服务首页 HTTP **200**,标题 `PaaS-SDK-Service`;仅 `127.0.0.1:8091` 和 `127.0.0.1:8092` 监听。
|
||||
- 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`;未设置开机自启。
|
||||
|
||||
## 已安装内容与路径
|
||||
|
||||
| 内容 | 版本或位置 |
|
||||
| --- | --- |
|
||||
| 运行目录 | `D:\web\zyt\.spool\esign-runtime` |
|
||||
| Java | Eclipse Temurin OpenJDK `1.8.0_512-b09`,Windows x64 HotSpot JDK |
|
||||
| JAVA_HOME | `D:\web\zyt\.spool\esign-runtime\jdk8u512-b09` |
|
||||
| Tomcat | Apache Tomcat `9.0.124`,通用 ZIP |
|
||||
| CATALINA_HOME/BASE | `D:\web\zyt\.spool\esign-runtime\apache-tomcat-9.0.124` |
|
||||
| 配置文件 | `D:\web\zyt\.spool\esign-runtime\apache-tomcat-9.0.124\conf\server.xml` |
|
||||
| 版本及校验清单 | `D:\web\zyt\.spool\esign-runtime\runtime-info.json` |
|
||||
| 下载包与官方校验文件 | `D:\web\zyt\.spool\esign-runtime\downloads` |
|
||||
|
||||
运行目录已被仓库原有 `/.spool` 规则忽略。没有修改全局 PATH、用户/系统 JAVA_HOME、Windows 服务、开机启动或防火墙规则。
|
||||
|
||||
## 版本选择依据
|
||||
|
||||
供应商下载说明要求 Java 8,列出的 OpenJDK 验证版本是 8u242;Tomcat 基线是 8.5,高版本需自测。该信息来自既有官方页面快照 `D:\web\zyt\.spool\esign-docs\esign-download-compact.txt`;在线 [Java 版 SDK 说明](https://open.esign.cn/doc/opendoc/paas_sdk_3/pi0dag6mcgxvp5zr) 同样确认 Java 8 与其他 OpenJDK 更新需自测。非 Java 项目本地部署 WAR 的方式见[官方接口说明](https://open.esign.cn/doc/opendoc/paas_sdk_3/km7nly0a6hwraeyb),本机部署与路径约定见 [Windows 部署说明](https://open.esign.cn/doc/opendoc/paas_sdk_3/hqcrgtx00y7hhoyf)。
|
||||
|
||||
选择仍维护的 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。
|
||||
|
||||
**兼容性验证范围:** 已完成官方应用部署、真实沙箱初始化和未签 PDF 解析检查。医生核身、实际签署、签后 PDF 验签与下载的完整业务闭环尚待测试医生参与验证。
|
||||
|
||||
## 官方下载和校验
|
||||
|
||||
下载使用 HTTPS,解压前比对官方哈希;没有仅凭文件名接受下载,也没有使用第三方重新打包文件。
|
||||
|
||||
| 组件 | 下载来源 | 校验来源 | 文件大小 |
|
||||
| --- | --- | --- | --- |
|
||||
| Temurin 8u512-b09 | [Adoptium 官方 GitHub Release ZIP](https://github.com/adoptium/temurin8-binaries/releases/download/jdk8u512-b09/OpenJDK8U-jdk_x64_windows_hotspot_8u512b09.zip) | [官方 SHA256 文件](https://github.com/adoptium/temurin8-binaries/releases/download/jdk8u512-b09/OpenJDK8U-jdk_x64_windows_hotspot_8u512b09.zip.sha256.txt)及 [Adoptium API](https://api.adoptium.net/v3/assets/latest/8/hotspot?architecture=x64&image_type=jdk&os=windows&vendor=eclipse) | 106,490,535 bytes |
|
||||
| Tomcat 9.0.124 | [Apache 官方 ZIP](https://dlcdn.apache.org/tomcat/tomcat-9/v9.0.124/bin/apache-tomcat-9.0.124.zip) | [Apache SHA512 文件](https://downloads.apache.org/tomcat/tomcat-9/v9.0.124/bin/apache-tomcat-9.0.124.zip.sha512);入口为[官方下载页](https://tomcat.apache.org/download-90.cgi) | 14,028,067 bytes |
|
||||
|
||||
Java SHA256(实际与两处官方值一致):
|
||||
|
||||
```text
|
||||
20f248ddd600f900cd9b235d50d54cdb27e7b750f140d381176a7612c53663cd
|
||||
```
|
||||
|
||||
Tomcat SHA512(实际与官方值一致):
|
||||
|
||||
```text
|
||||
cfe11a042e5c3acc02ca4715ef80f3de599980e46729556be08e2a4078a61c9fed625cc804b1660b3bdae43f0aa75090cd72cde3e934405234a4fa52624020bc
|
||||
```
|
||||
|
||||
本次完成哈希一致性校验,未执行独立 OpenPGP 签名验证。
|
||||
|
||||
## 监听与启动方式
|
||||
|
||||
- 唯一 HTTP connector:`127.0.0.1:8091`,纯 Java HTTP NIO。
|
||||
- 正常停服监听:`127.0.0.1:8092`,随机停服令牌只存于本地 `server.xml`。
|
||||
- 不配置 AJP、HTTPS、远程 JMX 或外部监听地址。
|
||||
- 移除 `ROOT`、`docs`、`examples`、`manager`、`host-manager`,空根路径只返回 Tomcat 通用错误页且隐藏服务器详情。SDK 应使用 `/paas-sdk-service/`。
|
||||
- 默认 Java 堆为 `-Xms256m -Xmx1024m`,用于本机沙箱起步;如调整,保持 `start-sdk.ps1` 与 `bin\setenv.bat` 一致。
|
||||
- SDK 官方 WAR 的目标位置:`D:\web\zyt\.spool\esign-runtime\apache-tomcat-9.0.124\webapps\paas-sdk-service.war`。
|
||||
- 官方 All-In-One 包也可提供展开的应用目录;对应目标为 `D:\web\zyt\.spool\esign-runtime\apache-tomcat-9.0.124\webapps\paas-sdk-service`,至少应包含 `WEB-INF\web.xml` 和完整依赖。启动脚本同时支持两种分发形式。
|
||||
|
||||
取得并核验官方 WAR、完成必要配置后,从 PowerShell 启动:
|
||||
|
||||
```powershell
|
||||
& 'D:\web\zyt\.spool\esign-runtime\start-sdk.ps1'
|
||||
```
|
||||
|
||||
脚本在没有 WAR 或展开应用时拒绝启动,并检查回环地址、端口和已有进程。Java 在隐藏窗口内运行;进程状态记录于 `D:\web\zyt\.spool\esign-runtime\sdk-process.json`,日志在 `D:\web\zyt\.spool\esign-runtime\apache-tomcat-9.0.124\logs`。输出“已启动进程”不等于应用部署或 SDK 初始化成功,须继续访问 `http://127.0.0.1:8091/paas-sdk-service/` 并检查日志。
|
||||
|
||||
正常关闭:
|
||||
|
||||
```powershell
|
||||
& 'D:\web\zyt\.spool\esign-runtime\stop-sdk.ps1'
|
||||
```
|
||||
|
||||
停服脚本核对 PID、进程创建时间、Java 路径、Tomcat 路径和停服端口所属 PID,然后发送正常停服指令。30 秒仍未退出时报告错误,不强杀进程。应配套使用这两个脚本;若直接使用 Tomcat 原生批处理,其进程不在脚本状态文件中,应配套使用原生 `shutdown.bat`。
|
||||
|
||||
## 已完成检查
|
||||
|
||||
- `java.exe -version` 成功:OpenJDK `1.8.0_512`,Temurin build `1.8.0_512-b09`,64-bit。
|
||||
- 通过 `org.apache.catalina.util.ServerInfo` 读取包版本成功:Tomcat `9.0.124`,构建日期 2026-11-09,APR 未加载。该命令未启动服务器。
|
||||
- 两个 PowerShell 脚本通过语法解析,XML 可解析,只有一个 HTTP connector。
|
||||
- 检查时 `webapps` 为空,8091 和 8092 都没有监听进程。
|
||||
- 后续已完成 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,39 @@
|
||||
# e签宝网页 / 桌面与后端集成审查
|
||||
|
||||
日期:2026-11-17。读取实际 `PrescriptionController.php`、`PrescriptionEsignService.php`、`EsignClient.php` 及两端实现;本轮只修改 admin、app 和本文档,未修改 server、未接触密钥、未进行真实供应商调用。
|
||||
|
||||
## 审查结论与修复
|
||||
|
||||
1. **DTO 解包一致。** 后端五个签署接口通过 `data()` 返回;新增 / 编辑 `success()` 的数据为 `{id, esign}`。admin 全局响应拦截器返回 envelope.data,桌面 `ApiClient._unwrap` 同样解包且 code=0 抛错,不会使用错误响应中的伪 signed。补充实际 `_unwrap` 离线测试。
|
||||
2. **新增 / 编辑正文保留。** 桌面 `_merge_result` 先复制提交正文,再覆盖响应映射,支持直接 `{id, esign}` 及嵌套 data。新增测试证明 patient_name、clinical_diagnosis、herbs、aux_usage、usage_notes 均保留;无须修改此函数。请求 payload 继续剔除只读 esign。缺失状态的保存结果改为“已保存,状态尚未确认”提示,不能误报已签或已提交审核;可在详情查询。已知 required 待签处方仍自动进入共享签署窗口。
|
||||
3. **网页端状态校验补强。** 新增完整枚举、环境和四个布尔字段校验;缺失 required、仅有 legacy 字样等不完整响应不得授权本地 PDF。未知初始 DTO 不显示已签,不授予签署权限。请求错误后取消 confirmed,只能先刷新确认;不将超时推断为可直接重签。初始状态与后续响应均通过校验。
|
||||
4. **preparing 映射正确。** 后端 preparing 返回 authenticating 且 can_sign=false;两端均禁止发起和完成操作,只允许查询。新增行为测试覆盖。
|
||||
5. **每次下载前读最新状态。** 网页原已执行状态查询,本轮加强校验。桌面详情原先只在打开时查询,会把后来转待签 / 已签的旧 legacy 快照继续本地导出;现每次导出处方都先查状态,只有完整确认的 legacy 才调用本地渲染。签署窗口下载同样先查询。查询失败、无 DTO、待签或无下载权限均不创建 / 覆盖目标 PDF。桌面没有 repository 且没有明确 legacy DTO 时也禁止处方导出;独立病历导出保留。
|
||||
6. **配置关闭兼容。** 仅 disabled + 明确 legacy 保留手写 / 本地 PDF;已 required 或已签记录即使 enabled=false 仍走原始 PDF,不由全局开关降级。测试覆盖缓存 legacy 后服务端变 pending、缺失 DTO、disabled 的 signed 三种状态。下载成功后的沙箱提示继续保留。
|
||||
7. **官方核身链接统一。** 后端可能返回 shortLink,也允许官方长链接;桌面原先拒绝长链接。两端现接受与后端一致的四个官方 HTTPS 主机:smlt.esign.cn、smlfront.esign.cn、t.esign.cn、idverify.esign.cn,拒绝凭据、非 443 端口、脚本 / 本地协议、控制字符及反斜杠。
|
||||
8. **签署等待与重发。** admin esignStart / esignComplete 显式 timeout=180000、isOpenRetry=false、retryCount=0、ignoreCancelToken=true;下载 60000。桌面签署变更等待 180 秒,状态 / 下载 60 秒;ApiClient 的 POST 始终只有一次尝试。任何客户端超时都不宣告失败重签,需查询后按服务端权限继续。
|
||||
|
||||
## 验证结果
|
||||
|
||||
```powershell
|
||||
cd D:\web\zyt\admin
|
||||
node --test tests/prescription-esign.test.cjs tests/prescription-aux-bag-count.test.cjs tests/prescription-order-tracking.test.cjs
|
||||
```
|
||||
|
||||
41 passed。最后一次面板初始 DTO 校验小改后又单独执行 `prescription-esign.test.cjs`,17 passed,含 5 个受影响 Vue SFC 编译检查。
|
||||
|
||||
```powershell
|
||||
cd D:\web\zyt\app
|
||||
$env:QT_QPA_PLATFORM = 'offscreen'
|
||||
.\.venv\Scripts\python.exe -m pytest tests/test_prescription_esign.py tests/test_prescription_ui.py tests/test_prescription_security_ui.py tests/test_repository_parity.py tests/test_appointments_parity_ui.py tests/test_diagnosis_detail_contract.py -ra
|
||||
```
|
||||
|
||||
150 passed in 7.45s。现有 PDF 渲染测试改为显式声明服务端 legacy,仍验证历史 PDF 的真实可见内容;未削弱图像 / PDF 断言。新增测试覆盖 DTO 缺失阻止导出、最新状态改变分流、配置关闭已签文件保留、preparing、稀疏 mutation 回包及响应 envelope 拒绝。
|
||||
|
||||
Ruff 对 core/esign.py、ui/dialogs/prescription_esign.py、test_prescription_esign.py 完整检查通过;对 prescription.py、repository.py 的 F 类检查通过。
|
||||
|
||||
`git diff --check -- admin app` 通过。已保持 HEAD 原有混合换行,仅新增 / 改动行使用 LF,未全文件重排格式。
|
||||
|
||||
本轮未重复全量 vue-tsc;前一轮记录的 62 条既有类型诊断仍是全量检查的已知限制。未执行登录浏览器、真实患者或供应商沙箱实签,最终环境联调仍需部署配置与测试身份。
|
||||
|
||||
根侧最终补充:依据官方沙箱长链示例,三端增加 `smlfront.esign.cn:8890` 精确例外,其余非标准端口仍拒绝;新增正反测试后网页仍 41 项通过,桌面增至 153 项通过。以上第 7 条的“非 443 端口”应以此例外为准。
|
||||
@@ -0,0 +1,146 @@
|
||||
# 医生开方 e签宝接入:仓库流程调研
|
||||
|
||||
调研日期:2026-11-17。范围为本地源码只读调研,未读取 `.env`、未访问真实患者记录、未调用签署供应商;仅新增本文档。项目根 `AGENTS.md` 已阅读;当前 checkout 无 `.trellis/`。下列 e签宝相关内容为建议落点,不是已实现能力,也不代表 SDK3.0 接口规范已核验。
|
||||
|
||||
## 结论
|
||||
|
||||
当前处方的“保存/提交”是同一个动作:`tcm.prescription/add` 创建记录后立即进入待审核;没有独立草稿提交 API。`doctor_signature` 只是客户端手写 PNG 的 data URL,后端只校验非空,未做可信电子签署。处方 PDF 由 admin 或桌面端本地渲染生成,未发现服务端统一处方 PDF 生成器或 e签宝服务。
|
||||
|
||||
接入应由后端管理医生身份绑定、处方版本、待签文件、签署流程、回调与签后文件。保留药师审核状态 `audit_status` 的语义,新增签署状态;仅把现有手写图片替换成第三方返回图片不能建立“签署文件与处方内容相同”的保证。
|
||||
|
||||
## 后端开方主流程
|
||||
|
||||
所有业务 API 都在 ThinkPHP `adminapi` 下,桌面端和 Vue 后台复用同一套 API。
|
||||
|
||||
| 环节 | 当前入口及行号 | 行为与接入约束 |
|
||||
| --- | --- | --- |
|
||||
| 新建 | `server/app/adminapi/controller/tcm/PrescriptionController.php:27`;`server/app/adminapi/logic/tcm/PrescriptionLogic.php:254` | Controller 强制 creator_id=当前管理员。Logic 读取当前管理员姓名、生成 SN、持久化处方,并触发处方 AI。签署主体应绑定此 creator_id,不能相信客户端 doctor_name。 |
|
||||
| 身份与病历来源 | `PrescriptionLogic.php:269`、`:327`、`:382`、`:393` | 有 diagnosis_id 时先检查诊单访问权限,patient_id/name/gender/age/phone、case_record 从服务端诊单取值;预约必须绑定该诊单。doctor_name 从 Admin.name 取,creator_id 从登录管理员取。 |
|
||||
| 保存即提交 | `PrescriptionLogic.php:387`、`:398`、`:409`;`PrescriptionController.php:35` | 忽略客户端 audit_status,新方始终 audit_status=0(待审核);返回 `{id}`。事务内锁诊单,防同一诊单/创建人/日期重复;没有独立 submit。 |
|
||||
| 幂等 | `PrescriptionLogic.php:258`、`:399` | 已有 PrescriptionAiRequest::replay/request_key 路径。接入签署必须单独保持“一个处方版本只有一个活动签署流程”的幂等,不能每次详情刷新或重复点击创建新流程。 |
|
||||
| 编辑 | `PrescriptionController.php:41`;`PrescriptionLogic.php:428`、`:445` | 通过 LockedPharmacySnapshotMutation 串行化,拒绝已远端锁定的药房快照;已审核通过且未作废的处方不可编辑。 |
|
||||
| 编辑权限及版本 | `PrescriptionLogic.php:485`、`:491`、`:558`、`:566` | 仅 creator 可编辑;不允许换绑诊单;编辑后清除审核结果重新待审,原作废状态亦可清除。**当前编辑仍使用客户端 doctor_name**,应改为已绑定签署人身份/原创建者身份。签署后编辑必须产生新版本,旧签名和文件保留但不能为新版本背书。 |
|
||||
| 人工审核 | `PrescriptionController.php:105`;`PrescriptionLogic.php:898` | 角色审核权限 + 处方可见性;仅 audit_status=0 可审核。通过设 1;驳回设 2 并置 void_status=1。签署完成门禁应位于业务逻辑,不只在 UI 禁按钮。 |
|
||||
| 作废 | `PrescriptionController.php:171`;`PrescriptionLogic.php:1246` | 与药房快照事务锁联动;有尚未释放的业务订单时禁止作废。成功写 void_status/time/by/by_name,并使 AI 结果失效。需同步失效活动签署版本、停止/关闭可关闭的未完成流程;保留证据。 |
|
||||
| 删除 | `PrescriptionController.php:75`;`PrescriptionLogic.php:740` | 已通过未作废禁止删除;其余为模型软删除。此 Logic 不接收 actor;签署信息的访问与操作不能沿用只传 id 的模式。 |
|
||||
| 详情 | `PrescriptionController.php:88`;`PrescriptionLogic.php:782` | 带可见性检查,并扩展关联业务订单信息。建议在此返回签署状态/是否可签/签后文件授权下载入口,避免客户端自行判断。 |
|
||||
| 预约/诊单查处方 | `PrescriptionController.php:135`、`:151`;`PrescriptionLogic.php:1046`、`:1079` | 查诊单处方列表、按预约优先找有效处方。新增状态需要覆盖这些 DTO 及列表 DTO,避免侧栏继续显示“已开方”却无法签署。 |
|
||||
|
||||
路径表内缩写的 `PrescriptionLogic.php` 和 `PrescriptionController.php` 分别指前两行完整路径。
|
||||
|
||||
校验位于 `server/app/adminapi/validate/tcm/PrescriptionValidate.php:11`,`doctor_name` 为 require、`doctor_signature` 为 require(`:21`、`:22`),无图片真实性或签名证据验证。新建/编辑 scene 在 `:42`、`:55`。接入应通过配置能力/签署模式分支调整这项要求,不能要求 e签宝模式先画本地签名才能保存待签版本。
|
||||
|
||||
模型为 `server/app/common/model/tcm/Prescription.php`;原始表定义 `server/database/migrations/create_tcm_prescription.sql:2`;现有签名字段迁移 `server/database/migrations/add_doctor_signature_to_prescription.sql:2` 将 `doctor_signature` 定义为 longtext/base64。
|
||||
|
||||
## 必须覆盖的旁路与内容修改点
|
||||
|
||||
1. **完诊自动空白方**:`server/app/adminapi/logic/doctor/AppointmentLogic.php:623` 调用 `PrescriptionLogic::createSystemAutoFromCompletedAppointment`;定义在 `PrescriptionLogic.php:1119`,取 appointment.doctor_id 为 creator(`:1137`、`:1233`),`is_system_auto=1`、doctor_signature 为空(`:1223`)、仍待审(`:1228`)。不得自动代表医生签署空白方;转人工完成后再签。
|
||||
2. **订单审核同步通过**:`server/app/adminapi/logic/tcm/PrescriptionOrderLogic.php:2352` 的 `auditPrescription` 在订单保存后,于 `:2408` 调用 `PrescriptionLogic::syncApproveConsumerPrescriptionIfPending`(`:842`),直接将处方设为审核通过。签署门禁必须在订单保存前检查,不能只在同步函数里 return,否则订单已通过而处方没通过。
|
||||
3. **创建业务订单**:`PrescriptionOrderLogic.php:984` 先锁处方行再进入 `createLocked`(`:1016`)。可以按业务决定允许“待签时建单”,但提交药房/审核/发药前必须验证签署完成且对应当前处方版本。不要默认为建单等同处方签署完成。
|
||||
4. **独立患者修正**:`PrescriptionLogic.php:608`/`:631` 的 patchPatientContact 直接改患者姓名、手机、性别,权限以可查看处方为基础(`:645`),且有药房锁检查(`:640`)。这是已签文件内容变化点,需阻止修改或开启重签版本。
|
||||
5. **订单患者修正**:`PrescriptionOrderLogic.php:1377`/`:1404` 的 patchPrescriptionPatient 经订单访问与处方可见性检查后直接改处方信息,同样要检查签署版本。
|
||||
6. **订单用法修正**:`PrescriptionOrderLogic.php:5775`/`:5793` 的 patchPrescriptionUsage 会改主副方次数、天数等,不能允许签后原地改掉已签内容。
|
||||
7. **订单管理审核修正**:`PrescriptionOrderLogic.php:2773` 后的订单管理编辑可写 `prescription_audit_status`(`:2800`、`:2813`)。与上传药房/完成订单的既有状态门禁一起纳入集成测试。
|
||||
8. **药房签名目前仍是图片**:`PrescriptionOrderLogic.php:5109` 将 doctor_signature 转换为药房 payload 的图片数组;`server/app/common/service/pharmacy/EjPharmacyPayload.php:88` 转发该字段。不要把 e签宝签署流水号放入旧图片字段;如果下游仍需图片,使用单独展示图片字段,可信文件另行存储。
|
||||
|
||||
现有锁工具为 `server/app/common/service/pharmacy/LockedPharmacySnapshotMutation.php:65` 的 executeForPrescription。签署回调与处方修改需采用相同处方级事务锁顺序,避免“回调通过旧版、同时医生已保存新版”的竞争。
|
||||
|
||||
## 医生身份、认证和权限
|
||||
|
||||
医生账户本质是管理员 Admin,而非另一个电子签名主体表。`server/app/adminapi/logic/auth/AdminLogic.php:68` 创建账户,包含 `name`、`phone`(`:79`)、`title`、`department`、`license_no`(`:86`)、`qualification_images`(`:87`);详情字段白名单在 `:293`。在这些账户字段中未发现法定身份证件号码、e签宝个人账号 ID、实名认证状态或签署授权有效期。证照号 `license_no` 不可等同身份证号。
|
||||
|
||||
建议独立 `doctor_esign_account`(命名待最终设计):admin_id、供应商个人标识、实名认证状态/时间、姓名/手机的必要快照、绑定版本、授权状态/到期时间、最近错误分类。尽量让供应商完成实名步骤,应用不额外收集完整身份证件;仅保存业务需要的状态与引用。所有状态由可信供应商响应/回调确定。
|
||||
|
||||
认证与授权位置:
|
||||
|
||||
- `server/app/adminapi/http/middleware/LoginMiddleware.php:42` 从 `token` header 取登录令牌;`:52` 从 AdminTokenCache 读取,`:76` 写入 request.adminInfo。`BaseAdminController.php:34` 将 admin_id 注入 controller。
|
||||
- `server/app/adminapi/http/middleware/AuthMiddleware.php:70` root 快速放行;`:80` 读取 AdminAuthCache;`:248` 是处方写权限别名,add/edit 支持 `cf.prescription/add|edit` 和 `tcm.diagnosis/kaifang|chufang`;void 支持 `cf.prescription/del|audit`。
|
||||
- `AuthMiddleware.php:174` 对未登记路由存在兼容放行,`:317` 仅对现有五个处方写动作强制鉴权。**新增签署、重试、身份绑定等路由必须显式列为受控接口,不能依赖路由尚未登记时的默认行为。**
|
||||
- `PrescriptionLogic.php:83` 可见性包括 creator、医助、共享、角色、开方权限和订单管理权限。可见不代表可签;签署发起应只允许处方创建医生,后台管理者只允许查看/运维特定操作。
|
||||
- `PrescriptionLogic.php:61` 审核角色来自 project.prescription_audit_roles,退回处方库全局管理角色配置。电子签名与药师审核权限应分开。
|
||||
- `server/app/adminapi/service/DoctorWebConsultationPolicy.php:36` 的网页面诊限制仅对四个通话签名/发起 action 生效,不等同禁止网页开方。不要误将此处 getDoctorSignature(通话凭证)当电子处方签名。
|
||||
- 桌面 token 注入在 `app/src/doctor_workstation/services/api_client.py:629`;admin 注入在 `admin/src/utils/request/index.ts:25`。供应商 app secret/签名私钥只能留在后端,不下发给这两个客户端。
|
||||
|
||||
## 桌面 app 入口与数据契约
|
||||
|
||||
技术栈为 Python 3.11+、PySide6、httpx;配置见 `app/pyproject.toml:5`。
|
||||
|
||||
| 位置 | 功能 / 接入建议 |
|
||||
| --- | --- |
|
||||
| `app/src/doctor_workstation/ui/dialogs/prescription.py:2832` | PrescriptionEditorDialog;签名板在 `:2245`,payload 在 `:4054` 输出 base64,`:4097` accept() 先验证手写签名。应显示后端签署能力、身份绑定/待签/已签状态,发起签署时打开受信签署 URL。 |
|
||||
| `app/src/doctor_workstation/ui/pages/prescriptions.py:2233`、`:2278` | 已开处方页新增/编辑;保存回调当前直接提示“新增并提交审核”或“重新待审核”(`:2295`、`:2301`),需区分保存成功与签署完成。 |
|
||||
| `app/src/doctor_workstation/ui/pages/appointments.py:2010`、`:2124` | 预约中的编辑和新建处方;需复用同一签署协调逻辑。 |
|
||||
| `app/src/doctor_workstation/ui/dialogs/diagnosis.py:3533`、`:4161` | 诊单中的创建/编辑处方,不能仅改处方列表页。 |
|
||||
| `app/src/doctor_workstation/services/repository.py:1743`、`:1754` | create_prescription/update_prescription 分别 POST `tcm.prescription/add|edit`,用 `_merge_result` 合并返回 DTO;`:1803` 审核,`:1818` 作废。新增签署接口应在 repository protocol 和真实/模拟实现同时声明。 |
|
||||
| `app/src/doctor_workstation/core/models.py:616`、`:689`、`:766` | Prescription 的签名字段、from_dict、to_dict;新增签署状态/版本/已签文件元信息需全部往返。 |
|
||||
| `app/src/doctor_workstation/services/mock_repository.py:1374` | 模拟编辑/审核/作废逻辑;应保持演示和测试的签署状态可预测,不调用真实供应商。 |
|
||||
|
||||
建议签署成功后重新拉服务端详情,不要以浏览器打开或跳回本应用视为已签;可支持“刷新签署结果”并做有限轮询。
|
||||
|
||||
## admin 前端入口
|
||||
|
||||
- 共享开方组件 `admin/src/components/tcm-prescription/index.vue:2034` 的 handleSave 总是 prescriptionAdd;`:2059` 必须本地手写签名;`:2066` 发起创建;`:2106` 保存后查详情;`:2125` 作废。适合承载预约/诊单开方后的签署动作和状态。
|
||||
- 诊单页 `admin/src/views/tcm/diagnosis/index.vue:400` 的 `tcm.diagnosis/kaifang` 按钮,经 `:1873` handlePrescription 打开共享组件(`:460`)。
|
||||
- 预约桌面页 `admin/src/views/tcm/appointment/list.vue:258`、`:1105`;H5 `list_h5.vue:158`、`:687`,都调用共享组件。H5 签署回跳/刷新也需要支持。
|
||||
- 已开处方页面另有独立编辑表单:`admin/src/views/consumer/prescription/index.vue:987` 手写签名;`:3153` PNG 转换;`:3825` handleSubmit;`:3861` add / `:3864` edit。只改共享组件会漏此入口。
|
||||
- API 封装为 `admin/src/api/tcm.ts:377` 到 `:432`。
|
||||
- `admin/src/views/tcm/appointment/components/prescription-drawer.vue:335` 尚有“直接生效”的旧注释且 `:457` 调用 add;实际后端始终待审。已查主要 list/list_h5/diagnosis 使用的是共享 tcm-prescription;若保留此旧组件,不应据其注释设计状态机。
|
||||
|
||||
## 处方 PDF 生成及签后文件
|
||||
|
||||
| 当前实现 | 事实 |
|
||||
| --- | --- |
|
||||
| `admin/src/components/tcm-prescription/index.vue:2274` | html2canvas 将 DOM 截图后用 jsPDF 生成 A5 处方,可追加 A3 病历(`:2290`)。不上传服务器。 |
|
||||
| `admin/src/views/consumer/prescription/index.vue:2624`、`:2690` | 另一路下载:html2canvas + jsPDF,A4。 |
|
||||
| `admin/src/views/consumer/prescription/order_list.vue:5120`、`order_list_h5.vue:5868` | 订单页面也有本地生成 PDF 路径。 |
|
||||
| `admin/src/components/prescription-slip/index.vue:162` | 图像签名展示组件;没有签名时才显示姓名。 |
|
||||
| `app/src/doctor_workstation/ui/dialogs/prescription.py:5391` | 桌面 export_pdf 使用 QPdfWriter,处方 A4/病历 A3,300 DPI,先生成图片后绘制;旧签名只是图片一部分。 |
|
||||
|
||||
本次检索 `server/app`、`server/config`、`server/extend` 未发现 e签宝服务、签署流程或通用 PDF 渲染库;server/composer.json 没有 PDF 生成依赖。当前两端纸张与布局也不一致,因此不能假设“任一客户端下载的 PDF”都是可用于签署的同一原文。
|
||||
|
||||
建议建立后端权威处方快照 → 确定版 PDF → 文件 SHA-256 → 供应商 fileId/流程 ID → 已签 PDF 的链路,并存模板版本。签署固定位置应由该模板控制。若选用供应商模板生成,也必须使用服务端冻结快照填充;不要让客户端自报 PDF 与数据库处方匹配。两端下载已签文件时直接取签后原件,不再截图重绘而丢失数字签名。
|
||||
|
||||
## 推荐实现顺序与边界
|
||||
|
||||
1. 后端增加配置、SDK3.0 客户端适配、医生绑定表、处方签署版本/流程表、状态查询和回调处理。数据库迁移沿用 `server/database/migrations/`。供应商接口名称、鉴权头和回调验签算法需另按官方文档核验。
|
||||
2. 签署行至少绑定 prescription_id、revision、creator_id、内容 hash、原 PDF hash、供应商 file/flow 标识、状态、错误分类、签署完成时间、签后文件引用。唯一约束保证版本幂等;回调需验真、去重、校验 flow 与签署人/版本,不能根据客户端 `signed=true` 改状态。
|
||||
3. 在 add/edit 的保存后建立当前版本,外部网络请求不放在长期数据库锁内。建议保存并进入待签 → 生成文件/创建流程 → 完成后保持待审核。签署未完成时的药师审核、订单审核与药房交付需一致拦截。
|
||||
4. 统一冻结/失效规则,覆盖编辑、患者修正、用法修正、作废、删除及空白转人工;旧版本的迟到回调只能更新旧版本,不能恢复当前版签署状态。
|
||||
5. 桌面和 admin 用同一后端状态契约展示“未开通/待签/签署中/已签/失败/已失效”,按后端 permissions/capabilities 控制动作;保持不含实施细节的用户文案。
|
||||
6. 历史 base64 签名记录应明确为历史手写签名,不能批量标为 e签宝已签。是否强制旧方重签属于迁移策略;可按开关/切换时间仅约束新签署流程,避免误锁历史订单。
|
||||
|
||||
## 测试工具与验证命令
|
||||
|
||||
本次已实际运行,均通过:
|
||||
|
||||
```powershell
|
||||
Set-Location D:\web\zyt\server
|
||||
php tests/PrescriptionAiWriteSafetyContractTest.php
|
||||
php tests/PrescriptionAppointmentScopeContractTest.php
|
||||
```
|
||||
|
||||
以上都是本地源码契约测试,无数据库写入;输出分别为 `Prescription AI write safety contract: OK`、`Prescription appointment scope contract: OK`。没有执行真实签署或远端集成。
|
||||
|
||||
后续实现建议的定向验证(未在本次调研执行):
|
||||
|
||||
```powershell
|
||||
# 后端:现有 PHP 脚本式测试;无 PHPUnit 项目入口
|
||||
Set-Location D:\web\zyt\server
|
||||
php tests/AdminDesktopAuthContractTest.php
|
||||
php -l app/adminapi/logic/tcm/PrescriptionLogic.php
|
||||
php -l app/adminapi/logic/tcm/PrescriptionOrderLogic.php
|
||||
|
||||
# 桌面:项目已经有 .venv;避免修改系统 Python
|
||||
Set-Location D:\web\zyt\app
|
||||
$env:QT_QPA_PLATFORM = 'offscreen'
|
||||
.\.venv\Scripts\python.exe -m pytest tests/test_prescription_ui.py tests/test_prescription_security_ui.py tests/test_repository_parity.py
|
||||
|
||||
# Vue 后台:已有 node:test + Vue SFC 编译/运行式测试
|
||||
Set-Location D:\web\zyt\admin
|
||||
node --test tests/prescription-aux-bag-count.test.cjs tests/prescription-order-tracking.test.cjs
|
||||
npm run type-check
|
||||
```
|
||||
|
||||
现有桌面 PDF 可见性测试在 `app/tests/test_prescription_ui.py:927`(加载 PDF 并渲染校验)、`:1054`(A3 病历);现有 payload 测试在 `:439`;权限与编辑测试在 `app/tests/test_prescription_security_ui.py:126`、`:193`。`app/README.md:115` 的官方命令为 `uv run pytest`,pyproject 配置 pytest pythonpath=src。
|
||||
|
||||
新增接入应重点测:重复发起只产生一个流程、伪造/重放回调、旧版回调晚到、签署期间编辑与作废、非 creator 发起签署、未注册路由不放行、订单审核旁路、签后下载原件、供应商不可用时可重试且不误提交、历史数据策略、桌面和 admin 签署取消后仍保持待签。供应商集成测试使用沙箱和显式配置,不能借现有患者数据/生产医生身份做自动冒烟。
|
||||
@@ -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
@@ -0,0 +1,92 @@
|
||||
# 医生开方 e签宝 SDK 3.0 接入
|
||||
|
||||
日期: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`。
|
||||
|
||||
## 医生操作
|
||||
|
||||
1. **保存处方草稿。** 填完处方后保存,进入同一张处方的签名流程。保存失败时保留表单,可重试。未完成电子签署的草稿不能审核。
|
||||
2. **验证医生身份。** 开方医生在系统内完成核验。系统查询核验结果,核验通过后显示签名步骤。核验失败或授权过期时,可在当前处方上重新验证。
|
||||
3. **确认签名并完成。** 医生核对当前处方后点击“确认签名”。若首次证书绑定所需的个人信息缺失,系统在这一步提示本人补充证件号。服务端再次核对本人授权,对冻结的 PDF 签名并验签。验签通过后,按权限下载已签 PDF 原件,处方可进入审核。
|
||||
|
||||
系统通过只读接口确认核身状态,每 5 秒最多一个请求,单次窗口最长等待 10 分钟。关闭或隐藏核验窗口会停止等待。签署请求必须由开方医生显式确认;权限检查、文件冻结与原始 PDF 验签由服务端执行。身份证号仅用于本次证书绑定,不写入业务库或响应。
|
||||
|
||||
发起身份核验时冻结该处方内容,包括药品、诊断、患者信息和用法。核验前请先检查草稿内容。已冻结处方需要修改时,先作废再新开。原件和签署证据保留。签署期间的迟到结果不能恢复已作废处方。签署开关关闭也不能让已经进入电子签署的处方绕过审核门禁。
|
||||
|
||||
已审核的历史处方保留原记录。启用后,新开处方和仍待审核的旧处方都需要电子签署。旧处方由开方医生开始核验时进入签署流程,继续使用原处方编号。自动生成的空白方必须先补全。
|
||||
|
||||
从处方审核或关联订单的审核入口选择通过时,系统会检查原处方的签署状态。开方医生可继续签署;其他审核人员会看到需要医生签署的提示。验签通过后,再由有审核权限的人员确认审核。发现内容有误时仍可驳回处理。
|
||||
|
||||
## 部署步骤
|
||||
|
||||
1. **取得并部署官方 PaaS-SDK-Service。** PHP 通过内网 HTTP 调用官方 WAR,不能把本应用接成 SaaS 合同签署流程。参见[非 Java 部署包说明](https://open.esign.cn/doc/opendoc/paas_sdk_3/ng140nt1nluvsemf)。官方安装包下载页目前要求登录语雀获取附件;仓库不包含该供应商分发包。选择包含 `queryWillingnessValidity` 的 SDK 3.1.13 或以上版本,按官方说明匹配 JDK/Tomcat。
|
||||
2. 将 SDK 服务置于内网,示例地址为 `http://127.0.0.1:8091/paas-sdk-service`。若 PHP 与 SDK 不同机,填实际内网地址;服务端口不暴露公网。按 e签宝应用后台配置出站 IP 白名单和核身认证能力。
|
||||
3. **备份并执行迁移** `server/database/migrations/2026_11_17_prescription_esign.sql`。默认表前缀 `zyt_`,使用其他表前缀时先调整 SQL。已在隔离 MySQL 5.7 中验证可重复执行,历史记录保持 `esign_required=0`。
|
||||
4. 按 `server/.env.esign.example` 合并 `[ESIGN]` 配置。本地提供的沙箱凭据已写入 Git 忽略的 `server/.env`,不包含在提交代码或配置样例里。部署到服务器时须通过服务器环境配置提供凭据。先保持 `ENABLED=false`。
|
||||
5. 在 `server/` 运行 `php think esign:setup` 检查是否配置凭据;运行 `php think esign:setup --initialize` 初始化已部署的 SDK。此命令不创建医生账号或发起签署。SDK 每次重启后都要初始化;切换应用或沙箱/生产环境必须先重启 SDK JVM,再初始化,不能通过重复调用 init 热切换。参见[初始化说明](https://open.esign.cn/doc/opendoc/paas_sdk_3/hgyqfsg1dgxwgvtc)。
|
||||
6. 准备 PHP 可读写的私有持久存储 `server/storage/esign/`,或设置 `STORAGE_PATH`。不要映射为静态公开目录;多 PHP 实例应共享此存储。原文、签后文件和数据库应一起备份,不能按临时文件清理。
|
||||
7. 初始化和迁移完成后设 `ENABLED=true`,发布后台与医生工作站新版本,重载 PHP 配置缓存。用**专门的测试医生、虚构患者处方**完成人工核身、签署、验签、原件下载及审核联调。
|
||||
|
||||
沙箱 PDF 带测试说明。沙箱签署可验证审核流程,但上传药房与正式发药会被拦截。正式上线需换正式应用凭据、环境和独立 SDK 实例/重启后的初始化,核实医生账号重新认证,按[正式环境切换说明](https://open.esign.cn/doc/opendoc/paas_sdk_3/btvx9owz5ehelqp3)完成开通;已有沙箱处方不能转换成正式签署件。
|
||||
|
||||
## 服务端契约与保存
|
||||
|
||||
所有接口使用现有 `adminapi` 登录和权限校验:
|
||||
|
||||
| 接口 | 方法 | 用途 |
|
||||
| --- | --- | --- |
|
||||
| `tcm.prescription/esignConfig` | GET | 返回开关与环境,无密钥 |
|
||||
| `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 和签署流水。
|
||||
|
||||
审核、手工调整订单审核状态以及药房提交占用记录写入,均在数据库事务中锁定处方并检查签署证据。驳回作废与编辑共用药房占用锁,防止并发改动绕过已冻结的内容。通知在审核事务提交后发送。
|
||||
|
||||
认证链接支持官方短链和长链;沙箱长链 `smlfront.esign.cn:8890` 为明确允许的例外端口。客户端签署调用等待 180 秒且不自动重发;PHP 完成签署接口允许执行 300 秒,并在客户端断开后继续归档。部署时应匹配反向代理及 PHP-FPM 的超时配置;超时后查询服务端状态,不能直接重复签署。
|
||||
|
||||
## 异常恢复
|
||||
|
||||
- 核验结果暂不可用时,点击查询结果。核验失败或过期时,点击重新验证。
|
||||
- 供应商在签署前明确拒绝时,解决界面提示的原因后,回到同一处方继续。仍有效的本人核验授权可复用。
|
||||
- 签署结果不明确时,先查询结果。无法确认结果且缺少原件时,由管理员按供应商流水核实。
|
||||
- 原件已归档但验签失败时,点击重试验签。服务端只校验原件。管理员仍可使用 `php think esign:setup --recover=处方ID` 处理归档故障。
|
||||
- 下载失败时可在已完成页面重新下载。文件缺失或 SHA-256 不匹配时,先恢复备份原件并核对证据。
|
||||
|
||||
## 验证入口
|
||||
|
||||
```powershell
|
||||
# 无网络、无业务库
|
||||
cd D:\web\zyt\server
|
||||
php tests/EsignClientTest.php
|
||||
php tests/PrescriptionEsignFlowTest.php
|
||||
|
||||
# 仅本机隔离 MySQL,测试自行新建并删除随机临时库
|
||||
$env:ZYT_ESIGN_TEST_MYSQL_PORT = '33379'
|
||||
php tests/PrescriptionEsignMysqlTest.php
|
||||
|
||||
cd D:\web\zyt\admin
|
||||
node --test tests/prescription-esign.test.cjs tests/prescription-aux-bag-count.test.cjs tests/prescription-order-tracking.test.cjs
|
||||
|
||||
cd D:\web\zyt\app
|
||||
$env:QT_QPA_PLATFORM = 'offscreen'
|
||||
.\.venv\Scripts\python.exe -m pytest tests/test_prescription_esign.py tests/test_prescription_ui.py tests/test_prescription_security_ui.py tests/test_repository_parity.py tests/test_appointments_parity_ui.py tests/test_diagnosis_detail_contract.py
|
||||
```
|
||||
|
||||
隔离测试使用模拟供应商,不能代替真实签署验收。PDF 排版已以虚构数据渲染查看。完整项目 TypeScript 检查仍有既有诊断,详见 `artifacts/esign-admin-implementation.md`;新增集成行为测试单独运行。
|
||||
|
||||
2026-11-17 最终验证:PHP 适配器 168 项、签署编排 64 项、隔离 MySQL 18 项、网页 41 项、桌面 153 项均通过;变更 PHP 文件语法、Ruff、Git diff 空白检查和凭据泄漏扫描通过。MySQL 测试使用独立连接,在三个审核写入入口尝试并发作废,确认行锁阻止竞态;迁移在临时库中重复执行通过,没有修改业务数据库。
|
||||
|
||||
现有 `PrescriptionOrderTrackingAuditTest.php` 和 `PrescriptionOrderReleaseAndTimeTest.php` 在 `RevisitDueHook` 的日志调用遇到 `Unable to resolve NULL driver`;将 `PrescriptionOrderLogic.php` 换为 Git HEAD 原版后,同一隔离环境也复现该错误。该两项不能报告为通过。处方 AI 写入、预约范围和桌面认证三项既有契约测试通过。
|
||||
|
||||
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.
@@ -0,0 +1,24 @@
|
||||
# Merge this section into deployment environment configuration; never commit real credentials.
|
||||
# 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,6 +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;
|
||||
|
||||
/**
|
||||
* 中医处方单控制器
|
||||
@@ -32,7 +35,7 @@ class PrescriptionController extends BaseAdminController
|
||||
if ($id === null) {
|
||||
return $this->fail(PrescriptionLogic::getError());
|
||||
}
|
||||
return $this->success('保存成功', ['id' => $id]);
|
||||
return $this->success('保存成功', ['id' => $id, 'esign' => PrescriptionEsignService::status($id, (int) $this->adminId, $this->adminInfo)]);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -45,7 +48,7 @@ class PrescriptionController extends BaseAdminController
|
||||
if (!$result) {
|
||||
return $this->fail(PrescriptionLogic::getError());
|
||||
}
|
||||
return $this->success('编辑成功');
|
||||
return $this->success('编辑成功', ['id' => (int) $params['id'], 'esign' => PrescriptionEsignService::status((int) $params['id'], (int) $this->adminId, $this->adminInfo)]);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -170,15 +173,188 @@ 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());
|
||||
}
|
||||
return $this->success('作废成功');
|
||||
}
|
||||
|
||||
public function esignConfig()
|
||||
{
|
||||
return $this->data(PrescriptionEsignService::capability());
|
||||
}
|
||||
|
||||
public function esignStatus()
|
||||
{
|
||||
return $this->esignOperation('status', false);
|
||||
}
|
||||
|
||||
public function esignIdentityStatus()
|
||||
{
|
||||
return $this->esignOperation('identityStatus', false);
|
||||
}
|
||||
|
||||
public function esignStart()
|
||||
{
|
||||
return $this->esignOperation('start', true);
|
||||
}
|
||||
|
||||
public function esignComplete()
|
||||
{
|
||||
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()) {
|
||||
return $this->fail('请使用 POST 请求');
|
||||
}
|
||||
$id = (int) ($post ? $this->request->post('id', 0) : $this->request->get('id', 0));
|
||||
if ($id <= 0) {
|
||||
return $this->fail('处方ID无效');
|
||||
}
|
||||
if ($operation === 'complete') {
|
||||
// A browser disconnect must not interrupt archival after signing.
|
||||
ignore_user_abort(true);
|
||||
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\{
|
||||
@@ -82,6 +83,33 @@ class AuthMiddleware
|
||||
// 当前访问路径
|
||||
$accessUri = strtolower($request->controller() . '/' . $request->action());
|
||||
|
||||
// Explicit gate: these new endpoints must not use unregistered-route bypass.
|
||||
if (str_starts_with($accessUri, 'tcm.prescription/esign')) {
|
||||
$action = substr($accessUri, strlen('tcm.prescription/'));
|
||||
if ($action === 'esignconfig') {
|
||||
return $next($request); // Only exposes enabled + environment, to logged-in users.
|
||||
}
|
||||
$uris = $this->formatUrl($adminAuthCache->getAdminUri() ?? []);
|
||||
$writes = ['tcm.prescription/add', 'tcm.prescription/edit', 'cf.prescription/add', 'cf.prescription/edit',
|
||||
'tcm.diagnosis/chufang', 'tcm.diagnosis/kaifang'];
|
||||
$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']);
|
||||
$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('权限不足,无法访问电子签署');
|
||||
}
|
||||
|
||||
// 患者列表的部门筛选复用列表权限;只允许 GET 查询显式启用数据范围的部门树。
|
||||
// 必须与 DeptController::all 读取同一个 GET 参数,避免请求体参数意外放行全量部门。
|
||||
if ($accessUri === 'dept.dept/all'
|
||||
@@ -246,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,14 @@ 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'] ?? '饭前';
|
||||
$item['usage_way'] = $item['usage_way'] ?? '温水送服';
|
||||
@@ -306,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;
|
||||
@@ -19,9 +20,17 @@ use think\facade\Log;
|
||||
use think\facade\Db;
|
||||
use app\common\service\prescriptionai\PrescriptionAiStore;
|
||||
use app\common\service\prescriptionai\PrescriptionAiRequest;
|
||||
use app\common\service\esign\PrescriptionEsignService;
|
||||
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 最近一次审核成功后的企微通知结果 */
|
||||
@@ -138,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);
|
||||
@@ -394,6 +467,10 @@ class PrescriptionLogic
|
||||
'assistant_id' => $assistantIdForRx,
|
||||
];
|
||||
|
||||
if (PrescriptionEsignService::enabled()) {
|
||||
$data['esign_required'] = 1;
|
||||
$data['esign_status'] = 'pending';
|
||||
}
|
||||
try {
|
||||
return Db::transaction(static function () use ($data, $params, $adminId, $adminInfo, $diagnosisIdRule, $dateYmd): int {
|
||||
$replayed = PrescriptionAiRequest::replay($params, $adminId, true);
|
||||
@@ -457,6 +534,12 @@ class PrescriptionLogic
|
||||
}
|
||||
|
||||
// 已通过且未作废:不可编辑
|
||||
$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;
|
||||
@@ -555,7 +638,7 @@ class PrescriptionLogic
|
||||
'usage_way' => $params['usage_way'] ?? $prescription->usage_way,
|
||||
'dietary_taboo' => is_array($params['dietary_taboo'] ?? null) ? implode(',', $params['dietary_taboo']) : ($params['dietary_taboo'] ?? $prescription->dietary_taboo),
|
||||
'usage_notes' => $params['usage_notes'] ?? $prescription->usage_notes,
|
||||
'doctor_name' => $params['doctor_name'] ?? $prescription->doctor_name,
|
||||
'doctor_name' => (string) $prescription->doctor_name,
|
||||
'doctor_signature' => $params['doctor_signature'] ?? $prescription->doctor_signature,
|
||||
'is_shared' => (int)($params['is_shared'] ?? $prescription->is_shared),
|
||||
'visible_role_ids' => array_key_exists('visible_role_ids', $params)
|
||||
@@ -571,6 +654,10 @@ class PrescriptionLogic
|
||||
'audit_remark' => '',
|
||||
];
|
||||
|
||||
if (PrescriptionEsignService::enabled()) {
|
||||
$data['esign_required'] = 1;
|
||||
$data['esign_status'] = 'pending';
|
||||
}
|
||||
if ($wasVoid) {
|
||||
$data['void_status'] = 0;
|
||||
$data['void_time'] = null;
|
||||
@@ -631,7 +718,7 @@ class PrescriptionLogic
|
||||
private static function patchPatientContactLocked(int $rxId, string $patientName, string $phone, int $gender, int $adminId, array $adminInfo): bool
|
||||
{
|
||||
self::$error = '';
|
||||
$prescription = Prescription::find($rxId);
|
||||
$prescription = Prescription::where('id', $rxId)->lock(true)->find();
|
||||
if (!$prescription) {
|
||||
self::setError('处方不存在');
|
||||
|
||||
@@ -648,6 +735,7 @@ class PrescriptionLogic
|
||||
return false;
|
||||
}
|
||||
|
||||
PrescriptionEsignPolicy::assertMutable($prescription->toArray());
|
||||
$patientName = trim($patientName);
|
||||
$phone = trim($phone);
|
||||
if ($patientName === '') {
|
||||
@@ -767,6 +855,7 @@ class PrescriptionLogic
|
||||
return false;
|
||||
}
|
||||
|
||||
PrescriptionEsignPolicy::assertMutable($prescription->toArray());
|
||||
$prescription->delete();
|
||||
PrescriptionAiStore::invalidate($id, 'deleted');
|
||||
return true;
|
||||
@@ -792,8 +881,8 @@ class PrescriptionLogic
|
||||
return null;
|
||||
}
|
||||
$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)
|
||||
@@ -804,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'] ?? '');
|
||||
|
||||
/**
|
||||
* 处方笺展示所需的"收件信息/订单号/合计"等字段,
|
||||
@@ -848,31 +933,24 @@ class PrescriptionLogic
|
||||
if ($prescriptionId <= 0) {
|
||||
return;
|
||||
}
|
||||
$row = Prescription::find($prescriptionId);
|
||||
if (!$row) {
|
||||
return;
|
||||
}
|
||||
if ((int) ($row->void_status ?? 0) === 1) {
|
||||
return;
|
||||
}
|
||||
if ((int) ($row->audit_status ?? 1) !== 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
self::$lastAuditWecomNotify = null;
|
||||
$name = (string) ($adminInfo['name'] ?? '');
|
||||
$now = time();
|
||||
$finalRemark = trim($remark) !== '' ? trim($remark) : '业务订单处方审核通过';
|
||||
$finalRemark = mb_substr($finalRemark, 0, 500);
|
||||
|
||||
$row->audit_status = 1;
|
||||
$row->audit_time = $now;
|
||||
$row->audit_by = $adminId;
|
||||
$row->audit_by_name = $name;
|
||||
$row->audit_remark = $finalRemark;
|
||||
|
||||
try {
|
||||
if ($row->save()) {
|
||||
$row = Db::transaction(static function () use ($prescriptionId, $adminId, $adminInfo, $finalRemark): ?Prescription {
|
||||
$row = Prescription::where('id', $prescriptionId)->lock(true)->find();
|
||||
if (!$row || (int) ($row->void_status ?? 0) === 1 || (int) ($row->audit_status ?? 1) !== 0) {
|
||||
return null;
|
||||
}
|
||||
PrescriptionEsignService::assertSignedById($prescriptionId, false, $adminId);
|
||||
$row->audit_status = 1;
|
||||
$row->audit_time = time();
|
||||
$row->audit_by = $adminId;
|
||||
$row->audit_by_name = (string) ($adminInfo['name'] ?? '');
|
||||
$row->audit_remark = $finalRemark;
|
||||
return $row->save() ? $row : null;
|
||||
});
|
||||
if ($row && (empty($row->esign_required) || !PrescriptionEsignService::isSandboxTest($prescriptionId))) {
|
||||
self::$lastAuditWecomNotify = self::notifyCreatorAuditResult($row, 'approve', $finalRemark, $adminInfo);
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
@@ -905,7 +983,31 @@ class PrescriptionLogic
|
||||
return false;
|
||||
}
|
||||
|
||||
$row = Prescription::find($id);
|
||||
try {
|
||||
// Keep the signature check and audit write under the same row lock.
|
||||
// Reject also shares pharmacy claim locks with void/edit operations.
|
||||
$mutate = static fn () => self::auditLocked($id, $action, $remark, $adminId, $adminInfo);
|
||||
$row = $action === 'reject'
|
||||
? LockedPharmacySnapshotMutation::executeForPrescription($id, $mutate)
|
||||
: Db::transaction($mutate);
|
||||
} catch (\Throwable $exception) {
|
||||
if (self::getError() === '') {
|
||||
self::setError($exception->getMessage());
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (!$row) {
|
||||
return false;
|
||||
}
|
||||
if (empty($row->esign_required) || !PrescriptionEsignService::isSandboxTest($id)) {
|
||||
self::$lastAuditWecomNotify = self::notifyCreatorAuditResult($row, $action, $remark, $adminInfo);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static function auditLocked(int $id, string $action, string $remark, int $adminId, array $adminInfo): Prescription|false
|
||||
{
|
||||
$row = Prescription::where('id', $id)->lock(true)->find();
|
||||
if (!$row) {
|
||||
self::setError('处方不存在');
|
||||
|
||||
@@ -918,7 +1020,7 @@ class PrescriptionLogic
|
||||
return false;
|
||||
}
|
||||
|
||||
if ((int) ($row->audit_status ?? 1) !== 0) {
|
||||
if ((int) ($row->audit_status ?? 1) !== 0 || !empty($row->void_status)) {
|
||||
self::setError('当前状态不可审核');
|
||||
|
||||
return false;
|
||||
@@ -928,18 +1030,19 @@ class PrescriptionLogic
|
||||
$now = time();
|
||||
|
||||
if ($action === 'approve') {
|
||||
try {
|
||||
PrescriptionEsignService::assertSignedById($id, false, $adminId);
|
||||
} catch (\DomainException $e) {
|
||||
self::setError($e->getMessage());
|
||||
return false;
|
||||
}
|
||||
$row->audit_status = 1;
|
||||
$row->audit_time = $now;
|
||||
$row->audit_by = $adminId;
|
||||
$row->audit_by_name = $name;
|
||||
$row->audit_remark = $remark;
|
||||
|
||||
$ok = (bool) $row->save();
|
||||
if ($ok) {
|
||||
self::$lastAuditWecomNotify = self::notifyCreatorAuditResult($row, 'approve', $remark, $adminInfo);
|
||||
}
|
||||
|
||||
return $ok;
|
||||
return $row->save() ? $row : false;
|
||||
}
|
||||
|
||||
if ($action === 'reject') {
|
||||
@@ -958,19 +1061,11 @@ class PrescriptionLogic
|
||||
$row->void_by = $adminId;
|
||||
$row->void_by_name = $name;
|
||||
|
||||
$ok = Db::transaction(static function () use ($row, $id): bool {
|
||||
Prescription::where('id', $id)->lock(true)->find();
|
||||
$saved = (bool) $row->save();
|
||||
if ($saved) {
|
||||
PrescriptionAiStore::invalidate($id, 'voided');
|
||||
}
|
||||
return $saved;
|
||||
});
|
||||
$ok = (bool) $row->save();
|
||||
if ($ok) {
|
||||
self::$lastAuditWecomNotify = self::notifyCreatorAuditResult($row, 'reject', $remark, $adminInfo);
|
||||
PrescriptionAiStore::invalidate($id, 'voided');
|
||||
}
|
||||
|
||||
return $ok;
|
||||
return $ok ? $row : false;
|
||||
}
|
||||
|
||||
self::setError('无效的审核操作');
|
||||
@@ -1067,10 +1162,14 @@ class PrescriptionLogic
|
||||
*/
|
||||
private static function filterViewablePrescriptions(array $rows, int $viewerAdminId, array $viewerAdminInfo): array
|
||||
{
|
||||
return array_values(array_filter(
|
||||
$visible = array_values(array_filter(
|
||||
$rows,
|
||||
static fn (array $row): bool => self::canViewPrescription($row, $viewerAdminId, $viewerAdminInfo)
|
||||
));
|
||||
return array_map(static function (array $row) use ($viewerAdminId): array {
|
||||
$row['esign'] = PrescriptionEsignService::describe($row, $viewerAdminId);
|
||||
return $row;
|
||||
}, $visible);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1107,7 +1206,9 @@ class PrescriptionLogic
|
||||
return null;
|
||||
}
|
||||
|
||||
return $row->toArray();
|
||||
$result = $row->toArray();
|
||||
$result['esign'] = PrescriptionEsignService::describe($result, $viewerAdminId);
|
||||
return self::withActionAvailability($result, $viewerAdminId, $viewerAdminInfo);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1234,6 +1335,10 @@ class PrescriptionLogic
|
||||
'assistant_id' => $assistantIdForRx,
|
||||
];
|
||||
|
||||
if (PrescriptionEsignService::enabled()) {
|
||||
$data['esign_required'] = 1;
|
||||
$data['esign_status'] = 'pending';
|
||||
}
|
||||
$prescription = new Prescription();
|
||||
$prescription->save($data);
|
||||
|
||||
@@ -1243,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() === '') {
|
||||
@@ -1259,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) {
|
||||
@@ -1283,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');
|
||||
|
||||
@@ -38,6 +38,8 @@ use app\common\service\pharmacy\PharmacySubmissionClaimWorkflow;
|
||||
use app\common\service\pharmacy\PharmacySupplyMode;
|
||||
use app\common\service\tcm\RevisitDueHook;
|
||||
use think\db\Query;
|
||||
use app\common\service\esign\PrescriptionEsignService;
|
||||
use app\common\service\esign\PrescriptionEsignPolicy;
|
||||
use think\facade\Config;
|
||||
use think\facade\Db;
|
||||
use think\facade\Log;
|
||||
@@ -58,6 +60,17 @@ class PrescriptionOrderLogic
|
||||
return self::$error;
|
||||
}
|
||||
|
||||
private static function assertEsignApproved(PrescriptionOrder $order, bool $forDispensing = false, ?int $reviewer = null): bool
|
||||
{
|
||||
try {
|
||||
PrescriptionEsignService::assertSignedById((int) $order->prescription_id, $forDispensing, $reviewer);
|
||||
return true;
|
||||
} catch (\DomainException $e) {
|
||||
self::$error = $e->getMessage();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static function assertTrackingAuditApproved(PrescriptionOrder $order): bool
|
||||
{
|
||||
if ((int) $order->prescription_audit_status !== 1 || (int) $order->payment_slip_audit_status !== 1) {
|
||||
@@ -66,7 +79,7 @@ class PrescriptionOrderLogic
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
return self::assertEsignApproved($order, true);
|
||||
}
|
||||
|
||||
private static function assertRemoteSnapshotMutable(PrescriptionOrder $order): bool
|
||||
@@ -1429,12 +1442,13 @@ class PrescriptionOrderLogic
|
||||
|
||||
return false;
|
||||
}
|
||||
$rx = Prescription::where('id', $rxId)->whereNull('delete_time')->find();
|
||||
$rx = Prescription::where('id', $rxId)->whereNull('delete_time')->lock(true)->find();
|
||||
if (!$rx) {
|
||||
self::setError('处方不存在');
|
||||
|
||||
return false;
|
||||
}
|
||||
PrescriptionEsignPolicy::assertMutable($rx->toArray());
|
||||
if (!PrescriptionLogic::canViewPrescription($rx, $adminId, $adminInfo)) {
|
||||
self::setError('无权限修改此处方');
|
||||
|
||||
@@ -2352,13 +2366,38 @@ class PrescriptionOrderLogic
|
||||
public static function auditPrescription(int $id, string $action, string $remark, int $adminId, array $adminInfo)
|
||||
{
|
||||
self::$error = '';
|
||||
$order = PrescriptionOrder::where('id', $id)->whereNull('delete_time')->find();
|
||||
try {
|
||||
$out = Db::transaction(static function () use ($id, $action, $remark, $adminId, $adminInfo) {
|
||||
$result = self::auditPrescriptionLocked($id, $action, $remark, $adminId, $adminInfo);
|
||||
if ($result === false) {
|
||||
throw new \DomainException(self::$error ?: '审核未完成');
|
||||
}
|
||||
return $result;
|
||||
});
|
||||
} catch (\Throwable $exception) {
|
||||
self::$error = $exception->getMessage();
|
||||
return false;
|
||||
}
|
||||
if ($out !== false && $action === 'approve') {
|
||||
// Notify only after the audit transaction releases its locks.
|
||||
PrescriptionLogic::syncApproveConsumerPrescriptionIfPending(
|
||||
(int) $out['prescription_id'], $adminId, $adminInfo,
|
||||
trim($remark) !== '' ? trim($remark) : '业务订单处方审核通过'
|
||||
);
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
private static function auditPrescriptionLocked(int $id, string $action, string $remark, int $adminId, array $adminInfo)
|
||||
{
|
||||
self::$error = '';
|
||||
$order = PrescriptionOrder::where('id', $id)->whereNull('delete_time')->lock(true)->find();
|
||||
if (!$order) {
|
||||
self::$error = '订单不存在';
|
||||
|
||||
return false;
|
||||
}
|
||||
if (!self::canAuditPrescriptionOrder($adminInfo)) {
|
||||
if (!self::canAuditPrescriptionOrder($adminInfo) || !self::canAccessOrder($order, $adminId, $adminInfo)) {
|
||||
self::$error = '无处方审核权限';
|
||||
|
||||
return false;
|
||||
@@ -2375,9 +2414,17 @@ class PrescriptionOrderLogic
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!in_array($action, ['approve', 'reject'], true)) {
|
||||
self::$error = '无效的审核操作';
|
||||
return false;
|
||||
}
|
||||
if ($action === 'reject' && trim($remark) === '') {
|
||||
self::$error = '驳回时请填写审核意见';
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($action === 'approve' && !self::assertEsignApproved($order, false, $adminId)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -2403,16 +2450,6 @@ class PrescriptionOrderLogic
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($action === 'approve') {
|
||||
$syncRemark = trim($remark) !== '' ? trim($remark) : '业务订单处方审核通过';
|
||||
PrescriptionLogic::syncApproveConsumerPrescriptionIfPending(
|
||||
(int) $order->prescription_id,
|
||||
$adminId,
|
||||
$adminInfo,
|
||||
$syncRemark
|
||||
);
|
||||
}
|
||||
|
||||
$actionName = $action === 'approve' ? 'audit_rx_approve' : 'audit_rx_reject';
|
||||
$summary = $action === 'approve' ? '处方审核通过' . ($remark ? ',意见:' . $remark : '') : '处方审核驳回,意见:' . $remark;
|
||||
self::writeLog((int) $order->id, $adminId, $adminInfo, $actionName, $summary);
|
||||
@@ -2776,6 +2813,23 @@ class PrescriptionOrderLogic
|
||||
public static function addLog(array $params, int $adminId, array $adminInfo)
|
||||
{
|
||||
self::$error = '';
|
||||
try {
|
||||
return Db::transaction(static function () use ($params, $adminId, $adminInfo) {
|
||||
$result = self::addLogLocked($params, $adminId, $adminInfo);
|
||||
if ($result === false) {
|
||||
throw new \DomainException(self::$error ?: '日志变更未完成');
|
||||
}
|
||||
return $result;
|
||||
});
|
||||
} catch (\Throwable $exception) {
|
||||
self::$error = $exception->getMessage();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static function addLogLocked(array $params, int $adminId, array $adminInfo)
|
||||
{
|
||||
self::$error = '';
|
||||
$id = (int) ($params['id'] ?? 0);
|
||||
$summary = mb_substr(trim((string) ($params['summary'] ?? '')), 0, 500);
|
||||
if ($summary === '') {
|
||||
@@ -2784,7 +2838,7 @@ class PrescriptionOrderLogic
|
||||
return false;
|
||||
}
|
||||
|
||||
$order = PrescriptionOrder::where('id', $id)->whereNull('delete_time')->find();
|
||||
$order = PrescriptionOrder::where('id', $id)->whereNull('delete_time')->lock(true)->find();
|
||||
if (!$order) {
|
||||
self::$error = '订单不存在';
|
||||
|
||||
@@ -2814,9 +2868,12 @@ class PrescriptionOrderLogic
|
||||
if (!in_array($newRx, [0, 1, 2], true)) {
|
||||
self::$error = '处方审核状态无效';
|
||||
|
||||
return false;
|
||||
}
|
||||
$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)
|
||||
@@ -4947,6 +5004,9 @@ class PrescriptionOrderLogic
|
||||
self::$error = '无权限操作';
|
||||
return false;
|
||||
}
|
||||
if (!self::assertEsignApproved($order, true)) {
|
||||
return false;
|
||||
}
|
||||
$target = self::normalizeShipMode((string) ($order->ship_mode ?? 'gancao')) === 'direct'
|
||||
? 'direct'
|
||||
: 'gancao';
|
||||
@@ -5083,6 +5143,9 @@ class PrescriptionOrderLogic
|
||||
/** @return array<string,mixed>|false */
|
||||
private static function uploadEjRemote(PrescriptionOrder $order, int $adminId, array $adminInfo, array $claim)
|
||||
{
|
||||
if (!self::assertEsignApproved($order, true)) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
$prescription = PrescriptionLogic::detail((int) $order->prescription_id, $adminId, $adminInfo);
|
||||
if ($prescription === null) {
|
||||
@@ -5203,6 +5266,9 @@ class PrescriptionOrderLogic
|
||||
if (!self::canAccessOrder($order, $adminId, $adminInfo)) {
|
||||
self::$error = '无权限操作';
|
||||
|
||||
return false;
|
||||
}
|
||||
if (!self::assertEsignApproved($order, true)) {
|
||||
return false;
|
||||
}
|
||||
$item = $order->toArray();
|
||||
@@ -5817,6 +5883,7 @@ class PrescriptionOrderLogic
|
||||
|
||||
return false;
|
||||
}
|
||||
PrescriptionEsignPolicy::assertMutable($rx->toArray());
|
||||
if (!PrescriptionLogic::canViewPrescription($rx, $adminId, $adminInfo)) {
|
||||
self::setError('无权限修改此处方');
|
||||
|
||||
|
||||
@@ -41,6 +41,9 @@ class PrescriptionValidate extends BaseValidate
|
||||
|
||||
public function sceneAdd()
|
||||
{
|
||||
if (\app\common\service\esign\PrescriptionEsignService::enabled()) {
|
||||
$this->remove('doctor_signature', 'require');
|
||||
}
|
||||
return $this->only([
|
||||
'prescription_type', 'dosage_amount', 'dosage_unit', 'dosage_bag_count', 'need_decoction', 'bags_per_dose',
|
||||
'prescription_name', 'patient_id', 'patient_name', 'phone', 'gender', 'age',
|
||||
@@ -54,6 +57,9 @@ class PrescriptionValidate extends BaseValidate
|
||||
|
||||
public function sceneEdit()
|
||||
{
|
||||
if (\app\common\service\esign\PrescriptionEsignService::enabled()) {
|
||||
$this->remove('doctor_signature', 'require');
|
||||
}
|
||||
return $this->only([
|
||||
'id', 'prescription_type', 'dosage_amount', 'dosage_unit', 'dosage_bag_count', 'need_decoction', 'bags_per_dose',
|
||||
'prescription_name', 'patient_id', 'patient_name', 'phone', 'gender', 'age',
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\command;
|
||||
|
||||
use app\common\service\esign\EsignClient;
|
||||
use app\common\service\esign\PrescriptionEsignService;
|
||||
use think\console\Command;
|
||||
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
|
||||
{
|
||||
protected function configure(): void
|
||||
{
|
||||
$this->setName('esign:setup')->setDescription('检查 e签宝配置、初始化内网 SDK 或恢复已归档签署结果')
|
||||
->addOption('initialize', null, Option::VALUE_NONE, '初始化已部署的 SDK;不创建医生、认证或处方签署')
|
||||
->addOption('recover', null, Option::VALUE_REQUIRED, '重新验签已归档的处方 ID;不会再次签署')
|
||||
->addOption('backfill-signature-times', null, Option::VALUE_NONE, '从当前签署环境及应用的已验签原件补录签署时间');
|
||||
}
|
||||
|
||||
protected function execute(Input $input, Output $output): int
|
||||
{
|
||||
$config = (array) Config::get('esign', []);
|
||||
$output->writeln('environment=' . ($config['environment'] ?? 'sandbox'));
|
||||
$output->writeln('enabled=' . (PrescriptionEsignService::enabled() ? 'true' : 'false'));
|
||||
$output->writeln('credentials=' . (!empty($config['app_id']) && !empty($config['app_secret']) ? 'configured' : 'missing'));
|
||||
try {
|
||||
if ($input->getOption('recover') !== null) {
|
||||
$id = filter_var($input->getOption('recover'), FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
|
||||
if (!$id) {
|
||||
throw new \DomainException('recover 必须为正整数处方ID');
|
||||
}
|
||||
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]));
|
||||
$client->assertConfigured();
|
||||
$client->initialize();
|
||||
$output->writeln('SDK 初始化成功;尚未执行医生核身或处方签署');
|
||||
} else {
|
||||
$output->writeln('配置检查完成;部署 SDK 后使用 --initialize,完成数据库迁移后再启用签署');
|
||||
}
|
||||
return 0;
|
||||
} catch (\Throwable $e) {
|
||||
$output->writeln('<error>' . ($e instanceof \DomainException ? $e->getMessage() : 'SDK 操作失败,请检查内网服务、应用环境和 e签宝 IP 白名单') . '</error>');
|
||||
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,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,665 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\common\service\esign;
|
||||
|
||||
use Closure;
|
||||
use RuntimeException;
|
||||
use Throwable;
|
||||
|
||||
/** Safe public errors deliberately omit provider messages, bodies and transport diagnostics. */
|
||||
class EsignProviderException extends RuntimeException
|
||||
{
|
||||
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)
|
||||
{
|
||||
$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);
|
||||
}
|
||||
}
|
||||
|
||||
/** Do not retry a signature after this exception without reconciling its outcome. */
|
||||
class EsignOutcomeUnknownException extends EsignProviderException
|
||||
{
|
||||
public function __construct(string $code, public ?string $signServiceId = null)
|
||||
{
|
||||
parent::__construct('signPdf', $code);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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}. 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' => [
|
||||
'identity' => 'https://smlopenapi.esign.cn',
|
||||
'init' => 'https://smlitsm.tsign.cn:8083/tgmonitor/rest/app!getAPIInfo2',
|
||||
'auth_hosts' => ['smlt.esign.cn', 'smlfront.esign.cn'],
|
||||
],
|
||||
'production' => [
|
||||
'identity' => 'https://openapi.esign.cn',
|
||||
'init' => 'https://sdkapi.esign.cn/tgmonitor/rest/app!getAPIInfo2',
|
||||
'auth_hosts' => ['t.esign.cn', 'idverify.esign.cn'],
|
||||
],
|
||||
];
|
||||
|
||||
private array $configuration;
|
||||
private Closure $transport;
|
||||
private Closure $clock;
|
||||
|
||||
public function __construct(?array $configuration = null, ?callable $transport = null, ?callable $clock = null)
|
||||
{
|
||||
$this->configuration = $configuration ?? (array) \think\facade\Config::get('esign', []);
|
||||
$this->transport = $transport !== null ? Closure::fromCallable($transport) : Closure::fromCallable([self::class, 'curlTransport']);
|
||||
$this->clock = $clock !== null ? Closure::fromCallable($clock) : static fn (): int => (int) floor(microtime(true) * 1000);
|
||||
}
|
||||
|
||||
public function isEnabled(): bool
|
||||
{
|
||||
return filter_var($this->configuration['enabled'] ?? false, FILTER_VALIDATE_BOOLEAN);
|
||||
}
|
||||
|
||||
public function environment(): string
|
||||
{
|
||||
return strtolower(trim((string) ($this->configuration['environment'] ?? 'sandbox')));
|
||||
}
|
||||
|
||||
public function assertConfigured(): void
|
||||
{
|
||||
if (!$this->isEnabled()) {
|
||||
throw new EsignProviderException('configuration', 'DISABLED');
|
||||
}
|
||||
if (!isset(self::ENVIRONMENTS[$this->environment()])) {
|
||||
throw new EsignProviderException('configuration', 'ENVIRONMENT_INVALID');
|
||||
}
|
||||
foreach (['app_id', 'app_secret'] as $key) {
|
||||
if (!is_string($this->configuration[$key] ?? null)
|
||||
|| trim($this->configuration[$key]) === ''
|
||||
|| preg_match('/[\x00-\x1f\x7f]/', $this->configuration[$key])) {
|
||||
throw new EsignProviderException('configuration', 'CREDENTIALS_MISSING');
|
||||
}
|
||||
}
|
||||
$timeout = $this->configuration['timeout'] ?? 60;
|
||||
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'])
|
||||
|| !in_array($parts['scheme'] ?? '', ['http', 'https'], true)
|
||||
|| isset($parts['user']) || isset($parts['pass'])
|
||||
|| isset($parts['query']) || isset($parts['fragment'])
|
||||
|| rtrim((string) ($parts['path'] ?? ''), '/') !== '/paas-sdk-service'
|
||||
|| preg_match('/[\x00-\x20\x7f]/', $url)) {
|
||||
throw new EsignProviderException('configuration', 'SDK_URL_INVALID');
|
||||
}
|
||||
// The SDK accepts credentials and patient documents: plain HTTP is local/private only.
|
||||
if ($parts['scheme'] === 'http' && !self::isPrivateHost((string) $parts['host'])) {
|
||||
throw new EsignProviderException('configuration', 'SDK_HTTP_REQUIRES_PRIVATE_HOST');
|
||||
}
|
||||
}
|
||||
|
||||
public function initialize(): void
|
||||
{
|
||||
$this->assertConfigured();
|
||||
$this->sdkJson('initialize', '/timevale/init', [
|
||||
'projectConfig' => [
|
||||
'projectId' => $this->configuration['app_id'],
|
||||
'projectSecret' => $this->configuration['app_secret'],
|
||||
'itsmApiUrl' => self::ENVIRONMENTS[$this->environment()]['init'],
|
||||
],
|
||||
'httpConfig' => ['httpType' => 'HTTPS', 'retry' => 0],
|
||||
'signConfig' => ['algorithm' => 'HMACSHA256'],
|
||||
]);
|
||||
}
|
||||
|
||||
/** @return array{flow_id:string,auth_url:string} */
|
||||
public function startIdentity(string $name, string $contextId, ?string $accountId = null): array
|
||||
{
|
||||
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, $operation);
|
||||
$person['sdkAccountId'] = $accountId;
|
||||
}
|
||||
$uneditable = ['name', 'certType'];
|
||||
if (isset($person['certNo'])) {
|
||||
$uneditable[] = 'certNo';
|
||||
}
|
||||
$response = $this->identityJson($operation, 'POST', '/v2/identity/auth/web/indivAuthUrl', [
|
||||
'indivInfo' => $person,
|
||||
'usageType' => $usageType,
|
||||
'authType' => $authType,
|
||||
'availableAuthTypes' => [$authType],
|
||||
'configParams' => ['indivUneditableInfo' => $uneditable],
|
||||
'contextInfo' => ['contextId' => $contextId, 'showResultPage' => true],
|
||||
]);
|
||||
$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($operation, 'AUTH_URL_INVALID');
|
||||
}
|
||||
return ['flow_id' => $flowId, 'auth_url' => $url];
|
||||
}
|
||||
|
||||
public function identityDetail(string $flowId): array
|
||||
{
|
||||
$this->requireText($flowId, 'identityDetail');
|
||||
$response = $this->identityJson('identityDetail', 'GET', '/v2/identity/auth/api/common/' . rawurlencode($flowId) . '/detail');
|
||||
if (!is_array($response['data'] ?? null) || $response['data'] === []) {
|
||||
throw new EsignProviderException('identityDetail', 'RESPONSE_INVALID');
|
||||
}
|
||||
return $response['data'];
|
||||
}
|
||||
|
||||
public function checkWillingness(string $flowId): void
|
||||
{
|
||||
$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
|
||||
{
|
||||
foreach ([$name, $idNo, $flowId] as $value) {
|
||||
$this->requireText($value, 'createPerson');
|
||||
}
|
||||
$data = $this->sdkJson('createPerson', '/timevale/account/addPerson', [
|
||||
'name' => $name, 'idNo' => $idNo, 'idNoType' => 'MAINLAND', 'identityAuthId' => $flowId,
|
||||
]);
|
||||
return $this->requiredResponseText($data, 'accountId', 'createPerson');
|
||||
}
|
||||
|
||||
public function createSeal(string $accountId): string
|
||||
{
|
||||
$this->requireText($accountId, 'createSeal');
|
||||
$data = $this->sdkJson('createSeal', '/timevale/seal/createPersonSeal', [
|
||||
'accountId' => $accountId, 'type' => 'BORDERLESS', 'color' => 'BLACK', 'stampRule' => 'SEAL_NONE',
|
||||
]);
|
||||
$seal = $this->requiredResponseText($data, 'sealData', 'createSeal');
|
||||
if (base64_decode($seal, true) === false) {
|
||||
throw new EsignProviderException('createSeal', 'RESPONSE_INVALID');
|
||||
}
|
||||
return $seal;
|
||||
}
|
||||
|
||||
/** @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');
|
||||
}
|
||||
$this->requirePdf($pdfBytes, 'signPdf');
|
||||
if (base64_decode($sealData, true) === false) {
|
||||
throw new EsignProviderException('signPdf', 'SEAL_INVALID');
|
||||
}
|
||||
$data = $this->sdkMultipart('signPdf', '/timevale/user/sign/personSign', 'personSignParam', [
|
||||
'accountId' => $accountId, 'willingnessId' => $flowId, 'sealData' => $sealData,
|
||||
'signType' => 'Single', 'fileBean' => ['fileName' => $fileName],
|
||||
'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;
|
||||
if ($serviceId === null || !is_string($pdf) || !str_starts_with($pdf, '%PDF-') || strlen($pdf) > self::MAX_PDF_BYTES) {
|
||||
throw new EsignOutcomeUnknownException('SIGNED_FILE_UNAVAILABLE', $serviceId);
|
||||
}
|
||||
return ['sign_service_id' => $serviceId, 'pdf' => $pdf];
|
||||
}
|
||||
|
||||
public function verifyPdf(string $pdfBytes): array
|
||||
{
|
||||
$this->requirePdf($pdfBytes, 'verifyPdf');
|
||||
$data = $this->sdkMultipart('verifyPdf', '/timevale/verify/pdf', 'verifyPdfParam', ['fileName' => 'prescription.pdf'], $pdfBytes);
|
||||
$signatures = $data['signatures'] ?? null;
|
||||
if (!is_array($signatures) || $signatures === [] || array_keys($signatures) !== range(0, count($signatures) - 1)) {
|
||||
throw new EsignProviderException('verifyPdf', 'NO_SIGNATURES');
|
||||
}
|
||||
foreach ($signatures as $signature) {
|
||||
if (!is_array($signature) || ($signature['signature']['validate'] ?? null) !== true) {
|
||||
throw new EsignProviderException('verifyPdf', 'SIGNATURE_INVALID');
|
||||
}
|
||||
}
|
||||
return ['signatures' => $signatures];
|
||||
}
|
||||
|
||||
private function sdkJson(string $operation, string $path, array $data): array
|
||||
{
|
||||
$this->assertConfigured();
|
||||
return $this->request($operation, 'POST', rtrim($this->configuration['sdk_url'], '/') . $path,
|
||||
['Content-Type' => self::JSON_TYPE, 'Accept' => 'application/json'], $this->json($data, $operation), 'errCode');
|
||||
}
|
||||
|
||||
private function identityJson(string $operation, string $method, string $path, ?array $data = null): array
|
||||
{
|
||||
$this->assertConfigured();
|
||||
$body = $data !== null ? $this->json($data, $operation) : '';
|
||||
$md5 = $body === '' ? '' : base64_encode(md5($body, true));
|
||||
// Official HMACSHA256 canonical form: method, accept, MD5, type, empty date, resource.
|
||||
$canonical = $method . "\n*/*\n" . $md5 . "\n" . self::JSON_TYPE . "\n\n" . $path;
|
||||
$headers = [
|
||||
'Accept' => '*/*', 'Content-Type' => self::JSON_TYPE,
|
||||
'X-Tsign-Open-App-Id' => $this->configuration['app_id'],
|
||||
'X-Tsign-Open-Auth-Mode' => 'Signature',
|
||||
'X-Tsign-Open-Ca-Timestamp' => (string) ($this->clock)(),
|
||||
'X-Tsign-Open-Ca-Signature' => base64_encode(hash_hmac('sha256', $canonical, $this->configuration['app_secret'], true)),
|
||||
];
|
||||
if ($md5 !== '') {
|
||||
$headers['Content-MD5'] = $md5;
|
||||
}
|
||||
return $this->request($operation, $method, self::ENVIRONMENTS[$this->environment()]['identity'] . $path, $headers, $body, 'code');
|
||||
}
|
||||
|
||||
private function sdkMultipart(string $operation, string $path, string $parameter, array $data, string $pdf, bool $signing = false): array
|
||||
{
|
||||
$this->assertConfigured();
|
||||
$boundary = 'esign-' . bin2hex(random_bytes(24));
|
||||
// JSON part needs its own application/json media type; a PHP POSTFIELDS string is insufficient.
|
||||
$body = '--' . $boundary . "\r\nContent-Disposition: form-data; name=\"" . $parameter . "\"\r\nContent-Type: " . self::JSON_TYPE . "\r\n\r\n"
|
||||
. $this->json($data, $operation)
|
||||
. "\r\n--" . $boundary . "\r\nContent-Disposition: form-data; name=\"streamFile\"; filename=\"prescription.pdf\"\r\nContent-Type: application/octet-stream\r\n\r\n"
|
||||
. $pdf . "\r\n--" . $boundary . "--\r\n";
|
||||
return $this->request($operation, 'POST', rtrim($this->configuration['sdk_url'], '/') . $path,
|
||||
['Content-Type' => 'multipart/form-data; boundary=' . $boundary, 'Accept' => 'application/json', 'Expect' => ''], $body, 'errCode', $signing);
|
||||
}
|
||||
|
||||
private function request(string $operation, string $method, string $url, array $headers, string $body, string $codeKey, bool $signing = false): array
|
||||
{
|
||||
try {
|
||||
$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);
|
||||
}
|
||||
if (!is_array($response) || (int) ($response['errno'] ?? 0) !== 0) {
|
||||
$this->fail($operation, is_array($response) && (int) ($response['errno'] ?? 0) === 28 ? 'TIMEOUT' : 'TRANSPORT_ERROR', $signing);
|
||||
}
|
||||
$status = (int) ($response['status'] ?? 0);
|
||||
if ($status < 200 || $status > 299) {
|
||||
$this->fail($operation, 'HTTP_' . $status, $signing);
|
||||
}
|
||||
$raw = $response['body'] ?? null;
|
||||
if (!is_string($raw) || trim($raw) === '') {
|
||||
$this->fail($operation, 'EMPTY_RESPONSE', $signing);
|
||||
}
|
||||
try {
|
||||
$data = json_decode($raw, true, 64, JSON_THROW_ON_ERROR);
|
||||
} catch (Throwable $exception) {
|
||||
$this->fail($operation, 'INVALID_JSON', $signing);
|
||||
}
|
||||
if (!is_array($data) || !array_key_exists($codeKey, $data) || !is_int($data[$codeKey])) {
|
||||
$this->fail($operation, 'RESPONSE_INVALID', $signing);
|
||||
}
|
||||
if ($data[$codeKey] !== 0) {
|
||||
$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) {
|
||||
throw new EsignOutcomeUnknownException($code);
|
||||
}
|
||||
throw new EsignProviderException($operation, $code);
|
||||
}
|
||||
|
||||
private function json(array $data, string $operation): string
|
||||
{
|
||||
try {
|
||||
return json_encode($data, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
|
||||
} catch (Throwable $exception) {
|
||||
throw new EsignProviderException($operation, 'INPUT_INVALID');
|
||||
}
|
||||
}
|
||||
|
||||
private function requireText(string $text, string $operation): void
|
||||
{
|
||||
if (trim($text) === '' || strlen($text) > 1048576 || preg_match('/[\x00-\x1f\x7f]/', $text)) {
|
||||
throw new EsignProviderException($operation, 'INPUT_INVALID');
|
||||
}
|
||||
}
|
||||
|
||||
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) {
|
||||
throw new EsignProviderException($operation, 'PDF_INVALID');
|
||||
}
|
||||
}
|
||||
|
||||
private function requiredResponseText(array $data, string $key, string $operation): string
|
||||
{
|
||||
if (!is_string($data[$key] ?? null) || trim($data[$key]) === '') {
|
||||
throw new EsignProviderException($operation, 'RESPONSE_INVALID');
|
||||
}
|
||||
return $data[$key];
|
||||
}
|
||||
|
||||
private function isTrustedAuthUrl(string $url): bool
|
||||
{
|
||||
$parts = parse_url($url);
|
||||
return is_array($parts) && ($parts['scheme'] ?? '') === 'https'
|
||||
&& !isset($parts['user']) && !isset($parts['pass'])
|
||||
&& !preg_match('/[\x00-\x20\x7f\\\\]/', $url)
|
||||
&& (!isset($parts['port']) || $parts['port'] === 443
|
||||
|| (($parts['host'] ?? '') === 'smlfront.esign.cn' && $parts['port'] === 8890))
|
||||
&& in_array(strtolower((string) ($parts['host'] ?? '')), self::ENVIRONMENTS[$this->environment()]['auth_hosts'], true);
|
||||
}
|
||||
|
||||
private static function isPrivateHost(string $host): bool
|
||||
{
|
||||
$host = strtolower(trim($host, '[]'));
|
||||
if (in_array($host, ['localhost', '::1'], true)) {
|
||||
return true;
|
||||
}
|
||||
if (filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
|
||||
$octets = array_map('intval', explode('.', $host));
|
||||
return $octets[0] === 127 || $octets[0] === 10
|
||||
|| ($octets[0] === 172 && $octets[1] >= 16 && $octets[1] <= 31)
|
||||
|| ($octets[0] === 192 && $octets[1] === 168);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static function curlTransport(array $request): array
|
||||
{
|
||||
if (!function_exists('curl_init')) {
|
||||
throw new RuntimeException('CURL_UNAVAILABLE');
|
||||
}
|
||||
$handle = curl_init($request['url']);
|
||||
$responseBody = '';
|
||||
$headers = [];
|
||||
foreach ($request['headers'] as $name => $value) {
|
||||
$headers[] = $name . ': ' . $value;
|
||||
}
|
||||
curl_setopt_array($handle, [
|
||||
CURLOPT_CUSTOMREQUEST => $request['method'], CURLOPT_HTTPHEADER => $headers,
|
||||
CURLOPT_FOLLOWLOCATION => false, CURLOPT_MAXREDIRS => 0,
|
||||
CURLOPT_SSL_VERIFYPEER => true, CURLOPT_SSL_VERIFYHOST => 2,
|
||||
CURLOPT_PROTOCOLS => CURLPROTO_HTTP | CURLPROTO_HTTPS,
|
||||
CURLOPT_CONNECTTIMEOUT => min(10, $request['timeout']), CURLOPT_TIMEOUT => $request['timeout'],
|
||||
CURLOPT_NOSIGNAL => true,
|
||||
CURLOPT_WRITEFUNCTION => static function ($handle, string $chunk) use (&$responseBody): int {
|
||||
if (strlen($responseBody) + strlen($chunk) > 67108864) {
|
||||
return 0;
|
||||
}
|
||||
$responseBody .= $chunk;
|
||||
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']);
|
||||
}
|
||||
curl_exec($handle);
|
||||
$response = ['status' => (int) curl_getinfo($handle, CURLINFO_HTTP_CODE), 'body' => $responseBody, 'errno' => curl_errno($handle)];
|
||||
curl_close($handle);
|
||||
return $response;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\common\service\esign;
|
||||
|
||||
use DomainException;
|
||||
|
||||
/** Pure rules shared by API, audit and dispensing boundaries. */
|
||||
final class PrescriptionEsignPolicy
|
||||
{
|
||||
public const CONTENT_FIELDS = [
|
||||
'id', 'sn', 'creator_id', 'doctor_name', 'diagnosis_id', 'appointment_id',
|
||||
'patient_id', 'patient_name', 'gender', 'age', 'phone', 'visit_no', 'prescription_date',
|
||||
'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', 'aux_usage', 'usage_instruction', 'usage_time', 'usage_way',
|
||||
'dietary_taboo', 'usage_notes', 'case_record', 'amount',
|
||||
];
|
||||
|
||||
public static function snapshot(array $row): array
|
||||
{
|
||||
$out = [];
|
||||
foreach (self::CONTENT_FIELDS as $key) {
|
||||
$value = $row[$key] ?? null;
|
||||
if (in_array($key, ['herbs', 'aux_usage', 'case_record'], true) && is_string($value)) {
|
||||
$value = trim($value) === '' ? null : json_decode($value, true, 512, JSON_THROW_ON_ERROR);
|
||||
}
|
||||
if (in_array($key, ['dosage_amount', 'amount'], true) && $value !== null && is_numeric($value)) {
|
||||
// ORM float casts and raw DECIMAL strings represent the same clinical quantity.
|
||||
$value = self::decimal((string) $value);
|
||||
}
|
||||
$out[$key] = self::canonical($value);
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
private static function canonical(mixed $value): mixed
|
||||
{
|
||||
if (!is_array($value)) {
|
||||
// DB raw rows and ORM numeric casts must fingerprint identically.
|
||||
return $value === null ? null : (is_bool($value) ? (string) (int) $value : (string) $value);
|
||||
}
|
||||
if ($value !== [] && array_keys($value) !== range(0, count($value) - 1)) {
|
||||
ksort($value);
|
||||
}
|
||||
return array_map([self::class, 'canonical'], $value);
|
||||
}
|
||||
|
||||
private static function decimal(string $value): string
|
||||
{
|
||||
if (strpbrk($value, 'eE') !== false) {
|
||||
$value = sprintf('%.12F', (float) $value);
|
||||
}
|
||||
if (str_contains($value, '.')) {
|
||||
$value = rtrim(rtrim($value, '0'), '.');
|
||||
}
|
||||
return in_array($value, ['-0', '+0'], true) ? '0' : $value;
|
||||
}
|
||||
|
||||
public static function hash(array $row): string
|
||||
{
|
||||
return hash('sha256', json_encode(self::snapshot($row), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR));
|
||||
}
|
||||
|
||||
public static function assertMutable(array $row): void
|
||||
{
|
||||
if (!empty($row['esign_required']) && ($row['esign_status'] ?? 'pending') !== 'pending') {
|
||||
throw new DomainException('处方已进入电子签署,内容已冻结;如需修改请作废后重新开方');
|
||||
}
|
||||
}
|
||||
|
||||
public static function assertSigner(array $row, int $actor): void
|
||||
{
|
||||
if ($actor <= 0 || (int) ($row['creator_id'] ?? 0) !== $actor) {
|
||||
throw new DomainException('仅开方医生本人可以签署此处方');
|
||||
}
|
||||
if (!empty($row['void_status']) || !empty($row['delete_time'])) {
|
||||
throw new DomainException('处方已作废或删除,不能签署');
|
||||
}
|
||||
if (!empty($row['is_system_auto'])) {
|
||||
throw new DomainException('请先补全处方,再进行电子签署');
|
||||
}
|
||||
}
|
||||
|
||||
public static function assertSigned(array $row, ?array $evidence, bool $forDispensing = false): void
|
||||
{
|
||||
if (empty($row['esign_required'])) {
|
||||
return; // Explicit migration boundary: historical handwritten prescriptions.
|
||||
}
|
||||
if (!empty($row['void_status']) || !empty($row['delete_time']) || ($row['esign_status'] ?? '') !== 'signed'
|
||||
|| !$evidence || empty($evidence['signed_hash']) || empty($evidence['sign_service_id'])
|
||||
|| empty($evidence['signed_path']) || empty($evidence['signed_at']) || empty($evidence['account_id'])
|
||||
|| (int) ($evidence['prescription_id'] ?? 0) !== (int) ($row['id'] ?? 0)
|
||||
|| (int) ($evidence['doctor_id'] ?? 0) !== (int) ($row['creator_id'] ?? 0)
|
||||
|| !hash_equals((string) ($evidence['snapshot_hash'] ?? ''), self::hash($row))) {
|
||||
throw new DomainException('处方尚未完成有效电子签署,请开方医生完成签署后重试');
|
||||
}
|
||||
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
@@ -0,0 +1,132 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
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, int $issuedAt = 0, bool $review = false): string
|
||||
{
|
||||
$row = PrescriptionEsignPolicy::snapshot($row);
|
||||
$lines = [];
|
||||
$add = static function (string $label, mixed $value) use (&$lines): void {
|
||||
if ($value === null || $value === '' || $value === []) {
|
||||
return;
|
||||
}
|
||||
if (is_array($value)) {
|
||||
$value = json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR);
|
||||
}
|
||||
$text = $label . ':' . (string) $value;
|
||||
foreach (preg_split('/\R/u', $text) as $paragraph) {
|
||||
$current = '';
|
||||
foreach (mb_str_split($paragraph) as $char) {
|
||||
if (mb_strwidth($current . $char, 'UTF-8') > 84) {
|
||||
$lines[] = $current;
|
||||
$current = ' ';
|
||||
}
|
||||
$current .= $char;
|
||||
}
|
||||
$lines[] = $current;
|
||||
}
|
||||
};
|
||||
$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']);
|
||||
$add('临床诊断', $row['clinical_diagnosis']);
|
||||
$add('舌象', $row['tongue']);
|
||||
$add('脉象', $row['pulse']);
|
||||
$add('脉诊补充', $row['pulse_condition']);
|
||||
$add('方名', $row['prescription_name']);
|
||||
$add('剂型', $row['prescription_type']);
|
||||
$herbLabels = ['name' => '药名', 'dosage' => '用量', 'unit' => '单位', 'remark' => '备注',
|
||||
'usage' => '煎法', 'usage_method' => '煎法', 'method' => '煎法', 'group' => '组别',
|
||||
'group_type' => '组别', 'formula_type' => '方别', 'is_aux' => '辅方', 'price' => '价格'];
|
||||
foreach ((array) $row['herbs'] as $index => $herb) {
|
||||
$parts = [];
|
||||
foreach ((array) $herb as $key => $value) {
|
||||
if (in_array($key, ['id', 'medicine_id', 'herb_id', 'name_pinyin', 'pinyin'], true) || $value === '' || $value === null) {
|
||||
continue;
|
||||
}
|
||||
$parts[] = ($herbLabels[$key] ?? $key) . ' ' . (is_array($value) ? json_encode($value, JSON_UNESCAPED_UNICODE) : $value);
|
||||
}
|
||||
$add('药品 ' . ($index + 1), implode(' / ', $parts));
|
||||
}
|
||||
foreach ([
|
||||
'dose_count' => '总剂数', 'dose_unit' => '剂数单位', 'dosage_amount' => '单次用量',
|
||||
'dosage_unit' => '用量单位', 'dosage_bag_count' => '单次袋数', 'bags_per_dose' => '每剂袋数',
|
||||
'usage_days' => '服用天数', 'times_per_day' => '每日次数', 'usage_instruction' => '服用说明',
|
||||
'usage_time' => '服药时间', 'usage_way' => '服用方式', 'dietary_taboo' => '忌口', 'usage_notes' => '医嘱',
|
||||
] as $key => $label) {
|
||||
$add($label, $row[$key]);
|
||||
}
|
||||
$add('代煎', $row['need_decoction'] === '1' ? '是' : '否');
|
||||
$add('金额(元)', $row['amount']);
|
||||
foreach ((array) $row['aux_usage'] as $key => $value) {
|
||||
$label = ['dosage_amount' => '单次用量', 'dosage_bag_count' => '单次袋数', 'need_decoction' => '代煎',
|
||||
'bags_per_dose' => '每剂袋数', 'times_per_day' => '每日次数', 'usage_days' => '服用天数',
|
||||
'prescription_name' => '方名'][$key] ?? $key;
|
||||
$add('辅方' . $label, $value);
|
||||
}
|
||||
$pages = array_chunk($lines, 33);
|
||||
$objects = [1 => '', 2 => '',
|
||||
3 => '<< /Type /Font /Subtype /Type0 /BaseFont /STSong-Light /Encoding /UniGB-UCS2-H /DescendantFonts [4 0 R] >>',
|
||||
4 => '<< /Type /Font /Subtype /CIDFontType0 /BaseFont /STSong-Light /CIDSystemInfo << /Registry (Adobe) /Ordering (GB1) /Supplement 4 >> /FontDescriptor 5 0 R /DW 1000 /W [1 95 500] >>',
|
||||
5 => '<< /Type /FontDescriptor /FontName /STSong-Light /Flags 6 /FontBBox [-25 -254 1000 880] /ItalicAngle 0 /Ascent 880 /Descent -254 /CapHeight 880 /StemV 80 >>',
|
||||
];
|
||||
$kids = [];
|
||||
foreach ($pages as $index => $pageLines) {
|
||||
$pageId = 6 + $index * 2;
|
||||
$streamId = $pageId + 1;
|
||||
$kids[] = $pageId . ' 0 R';
|
||||
$stream = self::text('中医处方笺', 235, 795, 20);
|
||||
if ($environment === 'sandbox') {
|
||||
$stream .= self::text('沙箱测试文件 · 不用于正式发药', 170, 770, 12);
|
||||
}
|
||||
$y = 738;
|
||||
foreach ($pageLines as $line) {
|
||||
$stream .= self::text($line, 45, $y, 11);
|
||||
$y -= 18;
|
||||
}
|
||||
$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, 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);
|
||||
$stream .= self::text(($index + 1) . ' / ' . count($pages), 515, 30, 9);
|
||||
$objects[$pageId] = '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] /Resources << /Font << /F1 3 0 R >> >> /Contents ' . $streamId . ' 0 R >>';
|
||||
$objects[$streamId] = '<< /Length ' . strlen($stream) . ">>\nstream\n" . $stream . 'endstream';
|
||||
}
|
||||
$objects[1] = '<< /Type /Catalog /Pages 2 0 R >>';
|
||||
$objects[2] = '<< /Type /Pages /Kids [' . implode(' ', $kids) . '] /Count ' . count($pages) . ' >>';
|
||||
ksort($objects);
|
||||
$pdf = "%PDF-1.4\n%\xE2\xE3\xCF\xD3\n";
|
||||
$offsets = [0];
|
||||
foreach ($objects as $id => $object) {
|
||||
$offsets[$id] = strlen($pdf);
|
||||
$pdf .= "$id 0 obj\n$object\nendobj\n";
|
||||
}
|
||||
$xref = strlen($pdf);
|
||||
$pdf .= 'xref' . "\n0 " . (count($objects) + 1) . "\n0000000000 65535 f \n";
|
||||
foreach ($objects as $id => $_) {
|
||||
$pdf .= sprintf("%010d 00000 n \n", $offsets[$id]);
|
||||
}
|
||||
return $pdf . 'trailer << /Size ' . (count($objects) + 1) . " /Root 1 0 R >>\nstartxref\n$xref\n%%EOF\n";
|
||||
}
|
||||
|
||||
private static function text(string $text, int $x, int $y, int $size): string
|
||||
{
|
||||
return "BT /F1 $size Tf 1 0 0 1 $x $y Tm <" . bin2hex(mb_convert_encoding($text, 'UTF-16BE', 'UTF-8')) . "> Tj ET\n";
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -7,6 +7,7 @@ namespace app\common\service\pharmacy;
|
||||
use DomainException;
|
||||
use think\facade\Db;
|
||||
use think\facade\Config;
|
||||
use app\common\service\esign\PrescriptionEsignService;
|
||||
|
||||
final class PharmacySubmissionClaimService
|
||||
{
|
||||
@@ -57,6 +58,9 @@ final class PharmacySubmissionClaimService
|
||||
->where('source_revision', $revision)
|
||||
->lock(true)
|
||||
->find();
|
||||
// Lock the prescription through the claim write; void/edit use the
|
||||
// same order -> claim -> prescription lock order and honor PENDING.
|
||||
PrescriptionEsignService::assertSignedById((int) $order['prescription_id'], true);
|
||||
if ($claim) {
|
||||
$decision = PharmacySubmissionClaimPolicy::existingDecision($claim, $target);
|
||||
if ($decision['action'] === 'IDEMPOTENT') {
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
return [
|
||||
// 指令定义
|
||||
'commands' => [
|
||||
'esign:setup' => 'app\\command\\EsignSetup',
|
||||
'assistant-service:daily' => 'app\\command\\AssistantServiceDaily',
|
||||
'assistant-service:alert' => 'app\\command\\AssistantServiceAlert',
|
||||
'assistant-service:auto' => 'app\\command\\AssistantServiceAuto',
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
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'),
|
||||
];
|
||||
@@ -0,0 +1,82 @@
|
||||
-- e签宝 SDK 3.0。先迁移,再启用 ESIGN_ENABLED;历史处方不回填为已签。
|
||||
SET @exists_column = (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='zyt_tcm_prescription' AND COLUMN_NAME='esign_required');
|
||||
SET @ddl = IF(@exists_column=0, 'ALTER TABLE zyt_tcm_prescription ADD esign_required tinyint NOT NULL DEFAULT 0, ADD esign_status varchar(24) NOT NULL DEFAULT ''legacy''', 'SELECT 1');
|
||||
PREPARE stmt FROM @ddl;
|
||||
EXECUTE stmt;
|
||||
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,
|
||||
`source_hash` char(64) NOT NULL,
|
||||
`source_path` varchar(255) NOT NULL,
|
||||
`signed_path` varchar(255) NOT NULL DEFAULT '',
|
||||
`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`),
|
||||
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,
|
||||
`environment` varchar(16) NOT NULL,
|
||||
`app_id` varchar(64) NOT NULL,
|
||||
`account_id` varchar(128) NOT NULL,
|
||||
`doctor_name` varchar(100) NOT NULL,
|
||||
`create_time` int unsigned NOT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_doctor_app` (`doctor_id`,`environment`,`app_id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='核身后医生签署账号,不保存身份证号码';
|
||||
@@ -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='医师实名在途流程,不保存原始证件号、手机号或验证码';
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user