This commit is contained in:
Your Name
2026-11-17 17:06:05 +08:00
parent 08892f4270
commit 378bf32069
51 changed files with 4656 additions and 103 deletions
+47
View File
@@ -373,6 +373,53 @@ export function getMsgAuditPermitUsers() {
// ========== 中医处方单 ==========
export interface PrescriptionEsignConfig {
enabled: boolean
environment: 'sandbox' | 'production'
}
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
message: string
auth_url?: string
}
export interface PrescriptionEsignFile {
filename: string
content_base64: string
sha256: 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 })
}
export function prescriptionEsignStart(params: { id: number }): Promise<PrescriptionEsignStatus> {
return request.post(
{ url: '/tcm.prescription/esignStart', params, timeout: 180000 },
{ isOpenRetry: false, retryCount: 0, ignoreCancelToken: true }
)
}
export function prescriptionEsignComplete(params: { id: number }): Promise<PrescriptionEsignStatus> {
return request.post(
{ url: '/tcm.prescription/esignComplete', params, 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,140 @@
<template>
<section class="esign-panel" aria-label="处方电子签署" v-loading="busy">
<div class="esign-panel__heading">
<strong>医师电子签署</strong>
<el-tag v-if="state && confirmed" :type="state.status === 'signed' ? 'success' : 'info'" size="small">
{{ state.status_label }}
</el-tag>
<el-tag v-if="state?.environment === 'sandbox' && state?.status !== 'legacy'" type="warning" size="small">
沙箱测试
</el-tag>
</div>
<p v-if="state?.message" class="esign-panel__message">{{ state.message }}</p>
<p v-if="state?.environment === 'sandbox' && state?.status !== 'legacy'" class="esign-panel__message">
当前为沙箱测试签署,仅用于接入验证。
</p>
<p v-if="error" class="esign-panel__error" role="alert">{{ error }}</p>
<div class="esign-panel__actions">
<el-button
v-if="state?.can_sign"
type="primary"
size="small"
:disabled="busy || !confirmed"
@click="start"
>{{ state.status === 'failed' ? '重试核身签署' : authUrl ? '重新获取核身链接' : '发起核身签署' }}</el-button>
<el-link v-if="authUrl && state?.can_sign && confirmed" :href="authUrl" target="_blank" rel="noopener noreferrer" type="primary">
打开核身页面
</el-link>
<el-button
v-if="state?.can_sign && (state.status === 'authenticating' || authUrl)"
size="small"
:disabled="busy || !confirmed"
@click="complete"
>已完成核身,继续签署</el-button>
<el-button size="small" :disabled="busy" @click="refresh">刷新签署状态</el-button>
<el-button v-if="state?.can_download" size="small" :disabled="busy || !confirmed" @click="download">
下载已签原始 PDF
</el-button>
</div>
<p v-if="authUrl && state?.can_sign" class="esign-panel__message">
请在新页面完成核身,然后返回继续签署;关闭页面后可从处方详情继续。
</p>
</section>
</template>
<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import {
prescriptionEsignComplete,
prescriptionEsignStart,
prescriptionEsignStatus,
type PrescriptionEsignStatus
} from '@/api/tcm'
import { downloadPrescriptionPdfIfRequired, safeEsignAuthUrl, validateEsignStatus } from '@/utils/prescription-esign'
const props = defineProps<{ prescriptionId: number; initialState?: PrescriptionEsignStatus }>()
const emit = defineEmits<{ (e: 'status-change', state: PrescriptionEsignStatus): void }>()
function initialStatus(): PrescriptionEsignStatus | null {
try {
return validateEsignStatus(props.initialState)
} catch {
return null
}
}
const state = ref<PrescriptionEsignStatus | null>(initialStatus())
const busy = ref(false)
const confirmed = ref(false)
const error = ref('')
const authUrl = computed(() => safeEsignAuthUrl(state.value?.auth_url))
let generation = 0
async function run(action: 'refresh' | 'start' | 'complete') {
if (busy.value || !props.prescriptionId) return
if (action !== 'refresh' && (!confirmed.value || state.value?.can_sign !== true)) return
const id = props.prescriptionId
const current = generation
busy.value = true
error.value = ''
try {
const api = action === 'start' ? prescriptionEsignStart : action === 'complete' ? prescriptionEsignComplete : prescriptionEsignStatus
const result = validateEsignStatus(await api({ id }))
if (id !== props.prescriptionId || current !== generation) return
state.value = result
confirmed.value = true
emit('status-change', result)
// A browser visit is never evidence of authentication or signing.
if (result.auth_url && !safeEsignAuthUrl(result.auth_url)) {
error.value = '核身链接无效,请重新获取或联系管理员'
}
} catch (e: any) {
if (id === props.prescriptionId && current === generation) {
confirmed.value = false
error.value = e?.msg || e?.message || '签署服务暂时不可用,请刷新状态后重试'
}
} finally {
if (current === generation) busy.value = false
}
}
const refresh = () => run('refresh')
const start = () => run('start')
const complete = () => run('complete')
async function download() {
if (busy.value || !confirmed.value || state.value?.can_download !== true) return
busy.value = true
error.value = ''
try {
await downloadPrescriptionPdfIfRequired(props.prescriptionId)
} catch (e: any) {
confirmed.value = false
error.value = e?.msg || e?.message || '下载签署文件失败,请重试'
} finally {
busy.value = false
}
}
watch(() => props.prescriptionId, () => {
generation++
busy.value = false
confirmed.value = false
error.value = ''
state.value = initialStatus()
void refresh()
}, { immediate: true })
watch(() => props.initialState, (value) => {
if (value) {
state.value = initialStatus()
if (!state.value) confirmed.value = false
}
})
</script>
<style scoped>
.esign-panel { margin: 12px 0; padding: 14px 16px; border: 1px solid var(--el-border-color-light); border-radius: 6px; background: var(--el-fill-color-light); }
.esign-panel__heading, .esign-panel__actions { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
.esign-panel__message { margin: 8px 0; color: var(--el-text-color-secondary); font-size: 13px; }
.esign-panel__error { color: var(--el-color-danger); font-size: 13px; }
@media print { .esign-panel { display: none; } }
</style>
+46 -10
View File
@@ -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,12 @@
</div>
<div v-else class="rx-wrap">
<EsignPrescriptionPanel
: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 +690,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 +725,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 +874,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 +1061,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 +1685,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 +2057,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 +2084,7 @@ const handleSave = async () => {
}
}
if (!formData.doctor_signature?.trim()) {
if (!esignEnabled.value && !formData.doctor_signature?.trim()) {
feedback.msgWarning('请使用电子签名板手写医师签名')
return
}
@@ -2103,8 +2131,14 @@ 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 {
savedPrescription.value = await prescriptionDetail({ id })
} catch {
feedback.msgWarning('处方已保存,详情暂未加载,可从已开处方继续签署')
}
emit('success')
} else {
feedback.msgError('保存失败')
@@ -2156,6 +2190,7 @@ const fetchCaseRecord = async (diagnosisId: number) => {
}
const handleNewPrescription = async () => {
await loadEsignConfig()
const saved = savedPrescription.value
if (saved) {
// 将患者信息、诊断信息填入表单,新建处方时保留
@@ -2273,6 +2308,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 +2337,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
}
}
+80
View File
@@ -0,0 +1,80 @@
import {
prescriptionEsignDownload,
prescriptionEsignStatus,
type PrescriptionEsignFile,
type PrescriptionEsignStatus
} from '@/api/tcm'
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')) {
throw new Error('无法核对处方签署状态,请刷新后重试')
}
return state
}
export function requiresOriginalEsignPdf(status?: PrescriptionEsignStatus | null): boolean {
try {
const value = validateEsignStatus(status)
return value.required || value.status !== 'legacy' || value.can_download
} catch {
return true
}
}
/** 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): Promise<void> {
const file = await prescriptionEsignDownload({ id })
const bytes = await verifyEsignPdf(file)
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
}
+56 -12
View File
@@ -283,6 +283,13 @@
>
<!-- 查看:A4 处方笺(药房联样式) -->
<div v-if="editMode === 'view'" v-loading="viewDetailLoading" class="rx-wrap">
<EsignPrescriptionPanel
v-if="slipView?.id && !viewDetailLoading"
:key="slipView.id"
:prescription-id="Number(slipView.id)"
:initial-state="slipView.esign"
@status-change="onEsignStatusChange"
/>
<!-- 顶部工具栏(不打印 / 不下载) -->
<div class="rx-toolbar">
<el-tag
@@ -309,15 +316,16 @@
>待审核</el-tag>
<el-tag v-else-if="slipView" type="danger" size="small">已驳回</el-tag>
<div class="flex-1" />
<el-button :icon="Printer" size="small" @click="handlePrintSlip">打印</el-button>
<el-button v-if="!requiresOriginalEsignPdf(slipView?.esign)" :icon="Printer" size="small" @click="handlePrintSlip">打印</el-button>
<el-button
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 +992,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 +1022,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>
@@ -1584,6 +1597,10 @@ 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 { 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'
@@ -1768,6 +1785,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 }>>([])
@@ -2622,6 +2645,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 +2914,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()
@@ -3684,6 +3717,7 @@ const resetForm = () => {
// 新增处方
const handleAdd = () => {
void loadEsignConfig()
resetForm()
editForm.doctor_name = String(userStore.userInfo?.name || '')
editingWasVoid.value = false
@@ -3723,6 +3757,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 +3858,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 +3868,7 @@ const handleSubmit = async () => {
// Element Plus:校验失败会 reject,表单项已展示错误,勿再向外抛成 Uncaught
return
}
if (submitLoading.value) return
// 验证药材
if (!editForm.herbs || editForm.herbs.length === 0) {
@@ -3856,16 +3894,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 +3937,7 @@ onActivated(() => {
})
onMounted(async () => {
void loadEsignConfig()
await loadRoleOptions()
await loadRegionData()
await loadServicePackageOptions()
@@ -1786,6 +1786,7 @@
<el-button
size="small"
:loading="prescriptionSlipExporting"
v-if="!requiresOriginalEsignPdf(prescriptionViewData.esign)"
@click="downloadPrescriptionSlipImage"
>
下载图片
@@ -1793,9 +1794,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 +1862,13 @@
<div v-if="prescriptionViewData.audit_remark" class="mt-1">驳回意见:{{ prescriptionViewData.audit_remark }}</div>
</div>
<EsignPrescriptionPanel
v-if="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 +2137,8 @@ import {
getAssistants
} from '@/api/tcm'
import PrescriptionSlip from '@/components/prescription-slip/index.vue'
import EsignPrescriptionPanel from '@/components/EsignPrescriptionPanel.vue'
import { downloadPrescriptionPdfIfRequired, requiresOriginalEsignPdf } from '@/utils/prescription-esign'
import html2canvas from 'html2canvas'
import { jsPDF } from 'jspdf'
import { getDictData } from '@/api/app'
@@ -5110,6 +5121,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 +5153,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
}
@@ -2386,6 +2386,7 @@
<el-button
size="small"
:loading="prescriptionSlipExporting"
v-if="!requiresOriginalEsignPdf(prescriptionViewData.esign)"
@click="downloadPrescriptionSlipImage"
>
下载图片
@@ -2393,9 +2394,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 +2462,13 @@
<div v-if="prescriptionViewData.audit_remark" class="mt-1">驳回意见:{{ prescriptionViewData.audit_remark }}</div>
</div>
<EsignPrescriptionPanel
v-if="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"
@@ -2691,6 +2700,8 @@ import {
supplyModeTagType
} from './components/prescription-order-utils'
import PrescriptionSlip from '@/components/prescription-slip/index.vue'
import EsignPrescriptionPanel from '@/components/EsignPrescriptionPanel.vue'
import { downloadPrescriptionPdfIfRequired, requiresOriginalEsignPdf } from '@/utils/prescription-esign'
import html2canvas from 'html2canvas'
import { jsPDF } from 'jspdf'
import { getDictData } from '@/api/app'
@@ -5858,6 +5869,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 +5901,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
}
+329
View File
@@ -0,0 +1,329 @@
const assert = require('node:assert/strict')
const fs = require('node:fs')
const path = require('node:path')
const test = require('node:test')
const { createHash, webcrypto } = require('node:crypto')
const ts = require('typescript')
const vue = require('vue')
const { parse, compileScript, compileTemplate } = require('@vue/compiler-sfc')
globalThis.crypto ??= webcrypto
function loadModule(filename, imports) {
const code = ts.transpileModule(fs.readFileSync(path.join(__dirname, '../src', filename), 'utf8'), {
compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS }
}).outputText
const exports = {}
new Function('require', 'exports', code)((id) => {
assert.ok(Object.hasOwn(imports, id), `Unexpected import ${id}`)
return imports[id]
}, exports)
return exports
}
const pdfBytes = Buffer.from('%PDF-1.7\nSigned test bytes\n%%EOF')
const file = {
filename: 'signed.pdf',
content_base64: pdfBytes.toString('base64'),
sha256: createHash('sha256').update(pdfBytes).digest('hex')
}
const status = (changes = {}) => ({
enabled: true, required: true, environment: 'sandbox', status: 'pending',
status_label: '待签署', can_sign: true, can_download: false, message: '', ...changes
})
test('signing mutations allow 180 seconds and explicitly disable transport replay', async () => {
const calls = []
const api = loadModule('api/tcm.ts', {
'@/utils/request': { default: {
post: async (config, options) => { calls.push({ config, options }); return status() }
} }
})
await api.prescriptionEsignStart({ id: 17 })
await api.prescriptionEsignComplete({ id: 17 })
assert.equal(calls.length, 2)
for (const { config, options } of calls) {
assert.equal(config.timeout, 180000)
assert.equal(options.isOpenRetry, false)
assert.equal(options.retryCount, 0)
}
})
test('authentication links accept only absolute HTTPS URLs without credentials', () => {
const utils = loadModule('utils/prescription-esign.ts', { '@/api/tcm': {} })
for (const value of ['javascript:alert(1)', 'http://example.test', '//example.test', 'https://user:secret@example.test', '', null]) {
assert.equal(utils.safeEsignAuthUrl(value), '')
}
for (const host of ['smlt.esign.cn', 'smlfront.esign.cn', 't.esign.cn', 'idverify.esign.cn']) {
assert.equal(utils.safeEsignAuthUrl(`https://${host}/verify?token=test`), `https://${host}/verify?token=test`)
}
assert.equal(utils.safeEsignAuthUrl('https://auth.example.test/session'), '')
assert.equal(utils.safeEsignAuthUrl('https://smlfront.esign.cn:8890/identity/login'), 'https://smlfront.esign.cn:8890/identity/login')
assert.equal(utils.safeEsignAuthUrl('https://smlfront.esign.cn:444/x'), '')
assert.equal(utils.safeEsignAuthUrl('https://smlt.esign.cn:8890/x'), '')
})
test('signed PDF preserves original bytes and requires SHA-256 to match', async () => {
const { verifyEsignPdf } = loadModule('utils/prescription-esign.ts', { '@/api/tcm': {} })
assert.deepEqual(Buffer.from(await verifyEsignPdf(file)), pdfBytes)
await assert.rejects(verifyEsignPdf({ ...file, sha256: '0'.repeat(64) }), /校验失败/)
await assert.rejects(verifyEsignPdf({ ...file, sha256: '' }), /校验信息/)
await assert.rejects(verifyEsignPdf({ ...file, content_base64: Buffer.from('<html>Error</html>').toString('base64') }), /PDF/)
})
test('successful download writes the verified server bytes into the PDF Blob unchanged', async () => {
let downloaded
let clicked = false
let requestedId
const previousDocument = globalThis.document
const previousCreate = URL.createObjectURL
const previousRevoke = URL.revokeObjectURL
URL.createObjectURL = (blob) => { downloaded = blob; return 'blob:verified-pdf' }
URL.revokeObjectURL = () => {}
const link = { click: () => { clicked = true }, remove() {} }
globalThis.document = { createElement: () => link, body: { appendChild() {} } }
try {
const { downloadOriginalEsignPdf } = loadModule('utils/prescription-esign.ts', {
'@/api/tcm': { prescriptionEsignDownload: async ({ id }) => { requestedId = id; return file } }
})
await downloadOriginalEsignPdf(17)
assert.equal(requestedId, 17)
assert.equal(clicked, true)
assert.equal(link.download, 'signed.pdf')
assert.equal(downloaded.type, 'application/pdf')
assert.deepEqual(Buffer.from(await downloaded.arrayBuffer()), pdfBytes)
} finally {
globalThis.document = previousDocument
URL.createObjectURL = previousCreate
URL.revokeObjectURL = previousRevoke
}
})
test('download rechecks the server, blocks pending/unknown states and permits legacy rendering only', async () => {
let response = status()
let fileRequests = 0
const { downloadPrescriptionPdfIfRequired } = loadModule('utils/prescription-esign.ts', {
'@/api/tcm': {
prescriptionEsignStatus: async ({ id }) => { assert.equal(id, 17); return response },
prescriptionEsignDownload: async () => { fileRequests++; return { ...file, sha256: '0'.repeat(64) } }
}
})
for (const state of ['pending', 'authenticating', 'signing', 'uncertain', 'failed', 'voided']) {
response = status({ status: state })
await assert.rejects(downloadPrescriptionPdfIfRequired(17), /签署/)
}
assert.equal(fileRequests, 0)
response = null
await assert.rejects(downloadPrescriptionPdfIfRequired(17), /状态/)
response = { status: 'legacy', can_download: false }
await assert.rejects(downloadPrescriptionPdfIfRequired(17), /状态/)
response = status({ enabled: false, required: false, status: 'legacy' })
assert.equal(await downloadPrescriptionPdfIfRequired(17), false)
response = status({ status: 'signed', can_download: true })
await assert.rejects(downloadPrescriptionPdfIfRequired(17), /校验失败/)
assert.equal(fileRequests, 1)
await assert.rejects(downloadPrescriptionPdfIfRequired(0), /编号/)
})
test('configuration failures do not downgrade to handwritten mode; retry can restore explicit disabled mode', async () => {
let fail = true
let calls = 0
const { usePrescriptionEsignConfig } = loadModule('hooks/usePrescriptionEsignConfig.ts', {
vue,
'@/api/tcm': { prescriptionEsignConfig: async () => {
calls++
if (fail) throw new Error('offline')
return { enabled: false, environment: 'sandbox' }
} }
})
const config = usePrescriptionEsignConfig()
assert.equal(config.ready.value, false)
assert.deepEqual(await Promise.all([config.load(), config.load()]), [false, false])
assert.equal(calls, 1)
assert.equal(config.ready.value, false)
assert.ok(config.error.value)
fail = false
assert.equal(await config.load(), true)
assert.equal(config.ready.value, true)
assert.equal(config.enabled.value, false)
})
const panelPath = path.join(__dirname, '../src/components/EsignPrescriptionPanel.vue')
const panelSource = parse(fs.readFileSync(panelPath, 'utf8'), { filename: panelPath }).descriptor.scriptSetup.content
const ast = ts.createSourceFile('panel.ts', panelSource, ts.ScriptTarget.Latest, true)
const panelCode = ast.statements.filter((node) => {
if (ts.isImportDeclaration(node)) return false
if (ts.isVariableStatement(node)) return !node.declarationList.declarations.some((d) => ['props', 'emit'].includes(d.name.getText(ast)))
return true
}).map((node) => node.getText(ast)).join('\n')
const compiledPanel = ts.transpileModule(panelCode, {
compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS }
}).outputText
function panel(initial = status(), api = {}) {
const calls = []
const events = []
const watchers = []
const props = { prescriptionId: 17, initialState: initial }
const globals = {
ref: vue.ref, computed: vue.computed,
watch: (getter, callback) => watchers.push(callback),
props, emit: (_, value) => events.push(value),
safeEsignAuthUrl: (value) => typeof value === 'string' && value.startsWith('https://') ? value : '',
validateEsignStatus: loadModule('utils/prescription-esign.ts', { '@/api/tcm': {} }).validateEsignStatus,
downloadPrescriptionPdfIfRequired: async () => {},
prescriptionEsignStatus: async (p) => { calls.push(['status', p]); return api.refresh ? api.refresh() : initial },
prescriptionEsignStart: async (p) => { calls.push(['start', p]); return api.start ? api.start() : status({ status: 'authenticating', auth_url: 'https://auth.example.test/session' }) },
prescriptionEsignComplete: async (p) => { calls.push(['complete', p]); return api.complete ? api.complete() : status({ status: 'signed', can_sign: false, can_download: true }) }
}
const value = new Function(...Object.keys(globals), `${compiledPanel}\nreturn { state, busy, confirmed, error, authUrl, start, complete, refresh }`)(...Object.values(globals))
value.confirmed.value = true // The existing-state tests begin after a successful initial query.
return { ...value, props, calls, events, watchers }
}
test('opening an authentication URL does not mark signed; complete uses the server result', async () => {
const p = panel()
await p.start()
assert.equal(p.state.value.status, 'authenticating')
assert.equal(p.state.value.can_download, false)
assert.ok(p.authUrl.value)
assert.deepEqual(p.calls, [['start', { id: 17 }]])
await p.complete()
assert.equal(p.state.value.status, 'signed')
assert.equal(p.events.at(-1).can_download, true)
await p.start()
assert.equal(p.calls.length, 2, 'server can_sign=false prevents a new signing request')
})
test('failed or cancelled authentication stays pending and remains recoverable', async () => {
const p = panel(status({ status: 'authenticating' }), {
complete: async () => status({ status: 'authenticating', message: '尚未完成核身' })
})
await p.complete()
assert.equal(p.state.value.status, 'authenticating')
assert.equal(p.state.value.can_download, false)
const offline = panel(status(), { start: async () => { throw new Error('offline') } })
await offline.start()
assert.equal(offline.state.value.status, 'pending')
assert.match(offline.error.value, /offline/)
assert.equal(offline.busy.value, false)
await offline.refresh()
assert.equal(offline.error.value, '')
})
test('double clicks share one active operation and late results cannot replace another prescription', async () => {
let resolve
const deferred = new Promise((done) => { resolve = done })
const p = panel(status(), { start: () => deferred })
const first = p.start()
await p.start()
assert.equal(p.calls.length, 1)
p.props.prescriptionId = 18
p.props.initialState = status({ status_label: 'Another prescription' })
p.watchers[0]()
resolve(status({ status: 'signed', can_download: true }))
await first
await Promise.resolve()
assert.notEqual(p.state.value.status, 'signed')
assert.equal(p.events.some((e) => e.status === 'signed'), false)
})
test('preparing capability and malformed responses disable signing until a validated refresh', async () => {
const preparing = panel(status({ status: 'authenticating', can_sign: false }))
await preparing.start()
await preparing.complete()
assert.deepEqual(preparing.calls, [])
const malformed = panel(status(), { start: async () => ({ status: 'signed', can_download: true }) })
await malformed.start()
assert.equal(malformed.confirmed.value, false)
assert.equal(malformed.state.value.status, 'pending')
await malformed.start()
assert.equal(malformed.calls.length, 1)
await malformed.refresh()
assert.equal(malformed.confirmed.value, true)
})
function pageDeclarations(filename, selected, globals) {
const fullPath = path.join(__dirname, '../src', filename)
const source = parse(fs.readFileSync(fullPath, 'utf8'), { filename: fullPath }).descriptor.scriptSetup.content
const ast = ts.createSourceFile('page.ts', source, ts.ScriptTarget.Latest, true)
const declarations = new Map()
for (const node of ast.statements) {
if (ts.isFunctionDeclaration(node) && node.name) declarations.set(node.name.text, node.getText(ast))
if (ts.isVariableStatement(node)) {
for (const d of node.declarationList.declarations) declarations.set(d.name.getText(ast), `const ${d.getText(ast)}`)
}
}
const compiled = ts.transpileModule(selected.map((key) => {
assert.ok(declarations.has(key), `${filename}: missing ${key}`)
return declarations.get(key)
}).join('\n'), { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS } }).outputText
return new Function(...Object.keys(globals), `${compiled}\nreturn { ${selected.join(', ')} }`)(...Object.values(globals))
}
test('shared editor permits an unsigned save only in enabled mode and retains the saved id after detail failure', async () => {
for (const enabled of [false, true]) {
const requests = []
const messages = []
const savedPrescription = vue.ref(null)
const globals = {
saving: vue.ref(false), esignReady: vue.ref(true), esignEnabled: vue.ref(enabled),
loadEsignConfig: async () => true,
formData: { clinical_diagnosis: 'test diagnosis', herbs: [{ name: 'test herb', dosage: 1 }], doctor_signature: '' },
findDuplicateHerbNames: () => [], normalizeHerbRow: (herb) => herb,
auxHerbRows: vue.ref([]), savedPrescription,
prescriptionAdd: async (payload) => { requests.push(payload); return { id: 17, esign: status() } },
prescriptionDetail: async () => { throw new Error('offline') },
emit: () => {},
feedback: { msgWarning: (m) => messages.push(m), msgSuccess: (m) => messages.push(m), msgError: (m) => messages.push(m) }
}
const { handleSave } = pageDeclarations('components/tcm-prescription/index.vue', ['handleSave'], globals)
await handleSave()
assert.equal(requests.length, enabled ? 1 : 0)
if (enabled) {
assert.equal(savedPrescription.value.id, 17)
assert.equal(savedPrescription.value.esign.status, 'pending')
assert.equal(requests[0].doctor_signature, '')
} else {
assert.match(messages[0], /手写/)
}
}
})
test('consumer editor keeps the saved prescription open for signing instead of reporting audit completion', async () => {
const messages = []
const viewed = []
const globals = {
formRef: vue.ref({ validate: async () => {} }), submitLoading: vue.ref(false),
esignReady: vue.ref(true), esignEnabled: vue.ref(true), loadEsignConfig: async () => true,
editForm: { herbs: [{ name: 'test herb', dosage: 1 }], doctor_signature: '' },
editMode: vue.ref('add'), showEdit: vue.ref(true), herbValidationLabel: () => 'test herb',
prescriptionAdd: async () => ({ id: 17, esign: status() }),
prescriptionEdit: async () => { throw new Error('wrong API') },
handleView: async (row) => viewed.push(row), getLists: () => {},
feedback: { msgSuccess: (m) => messages.push(m), msgError: (m) => messages.push(m) }
}
const { handleSubmit } = pageDeclarations('views/consumer/prescription/index.vue', ['handleSubmit'], globals)
await handleSubmit()
assert.equal(viewed[0].id, 17)
assert.equal(viewed[0].esign.status, 'pending')
assert.equal(globals.showEdit.value, true)
assert.match(messages[0], /核身签署/)
})
for (const filename of [
'components/EsignPrescriptionPanel.vue',
'components/tcm-prescription/index.vue',
'views/consumer/prescription/index.vue',
'views/consumer/prescription/order_list.vue',
'views/consumer/prescription/order_list_h5.vue'
]) {
test(`${filename}: compiles the integrated signing controls`, () => {
const fullPath = path.join(__dirname, '../src', filename)
const { descriptor, errors } = parse(fs.readFileSync(fullPath, 'utf8'), { filename: fullPath })
assert.deepEqual(errors, [])
const script = compileScript(descriptor, { id: filename })
const template = compileTemplate({ source: descriptor.template.content, filename: fullPath, id: filename, compilerOptions: { bindingMetadata: script.bindings } })
assert.deepEqual(template.errors, [])
})
}