From 378bf320691d34b1167fe7f9a5043ab5f9815bfb Mon Sep 17 00:00:00 2001 From: Your Name Date: Tue, 17 Nov 2026 17:06:05 +0800 Subject: [PATCH] =?UTF-8?q?i=E6=9B=B4=E6=96=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 2 + admin/src/api/tcm.ts | 47 ++ .../src/components/EsignPrescriptionPanel.vue | 140 +++++ .../src/components/tcm-prescription/index.vue | 56 +- admin/src/hooks/usePrescriptionEsignConfig.ts | 43 ++ admin/src/utils/prescription-esign.ts | 80 +++ .../src/views/consumer/prescription/index.vue | 68 ++- .../consumer/prescription/order_list.vue | 18 +- .../consumer/prescription/order_list_h5.vue | 18 +- admin/tests/prescription-esign.test.cjs | 329 ++++++++++++ app/src/doctor_workstation/core/esign.py | 78 +++ app/src/doctor_workstation/core/models.py | 3 + .../services/mock_repository.py | 27 +- .../doctor_workstation/services/repository.py | 44 ++ .../ui/dialogs/diagnosis.py | 13 +- .../ui/dialogs/prescription.py | 173 ++++++- .../ui/dialogs/prescription_esign.py | 254 +++++++++ .../ui/pages/appointments.py | 19 +- .../ui/pages/prescriptions.py | 10 +- app/tests/test_prescription_esign.py | 482 ++++++++++++++++++ app/tests/test_prescription_ui.py | 1 + artifacts/esign-admin-implementation.md | 38 ++ artifacts/esign-backend-review.md | 57 +++ artifacts/esign-backend-review.png | Bin 0 -> 82728 bytes artifacts/esign-desktop-implementation.md | 61 +++ artifacts/esign-prescription-test.pdf | 54 ++ artifacts/esign-prescription-test.png | Bin 0 -> 51402 bytes artifacts/esign-provider-implementation.md | 83 +++ artifacts/esign-runtime-install.md | 103 ++++ artifacts/esign-ui-integration-review.md | 39 ++ artifacts/esign-workflow-research.md | 146 ++++++ docs/plans/esign-prescription-integration.md | 83 +++ server/.env.esign.example | 12 + .../controller/tcm/PrescriptionController.php | 51 +- .../http/middleware/AuthMiddleware.php | 18 + .../adminapi/lists/tcm/PrescriptionLists.php | 1 + .../adminapi/logic/tcm/PrescriptionLogic.php | 120 +++-- .../logic/tcm/PrescriptionOrderLogic.php | 95 +++- .../validate/tcm/PrescriptionValidate.php | 6 + server/app/command/EsignSetup.php | 52 ++ .../app/common/service/esign/EsignClient.php | 409 +++++++++++++++ .../service/esign/PrescriptionEsignPolicy.php | 103 ++++ .../esign/PrescriptionEsignService.php | 446 ++++++++++++++++ .../common/service/esign/PrescriptionPdf.php | 125 +++++ .../PharmacySubmissionClaimService.php | 4 + server/config/console.php | 1 + server/config/esign.php | 14 + .../2026_11_17_prescription_esign.sql | 42 ++ server/tests/EsignClientTest.php | 229 +++++++++ server/tests/PrescriptionEsignFlowTest.php | 336 ++++++++++++ server/tests/PrescriptionEsignMysqlTest.php | 126 +++++ 51 files changed, 4656 insertions(+), 103 deletions(-) create mode 100644 admin/src/components/EsignPrescriptionPanel.vue create mode 100644 admin/src/hooks/usePrescriptionEsignConfig.ts create mode 100644 admin/src/utils/prescription-esign.ts create mode 100644 admin/tests/prescription-esign.test.cjs create mode 100644 app/src/doctor_workstation/core/esign.py create mode 100644 app/src/doctor_workstation/ui/dialogs/prescription_esign.py create mode 100644 app/tests/test_prescription_esign.py create mode 100644 artifacts/esign-admin-implementation.md create mode 100644 artifacts/esign-backend-review.md create mode 100644 artifacts/esign-backend-review.png create mode 100644 artifacts/esign-desktop-implementation.md create mode 100644 artifacts/esign-prescription-test.pdf create mode 100644 artifacts/esign-prescription-test.png create mode 100644 artifacts/esign-provider-implementation.md create mode 100644 artifacts/esign-runtime-install.md create mode 100644 artifacts/esign-ui-integration-review.md create mode 100644 artifacts/esign-workflow-research.md create mode 100644 docs/plans/esign-prescription-integration.md create mode 100644 server/.env.esign.example create mode 100644 server/app/command/EsignSetup.php create mode 100644 server/app/common/service/esign/EsignClient.php create mode 100644 server/app/common/service/esign/PrescriptionEsignPolicy.php create mode 100644 server/app/common/service/esign/PrescriptionEsignService.php create mode 100644 server/app/common/service/esign/PrescriptionPdf.php create mode 100644 server/config/esign.php create mode 100644 server/database/migrations/2026_11_17_prescription_esign.sql create mode 100644 server/tests/EsignClientTest.php create mode 100644 server/tests/PrescriptionEsignFlowTest.php create mode 100644 server/tests/PrescriptionEsignMysqlTest.php diff --git a/.gitignore b/.gitignore index 8e57ecb55..223592e1c 100755 --- a/.gitignore +++ b/.gitignore @@ -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/ diff --git a/admin/src/api/tcm.ts b/admin/src/api/tcm.ts index 5a5e35668..6a23e2336 100755 --- a/admin/src/api/tcm.ts +++ b/admin/src/api/tcm.ts @@ -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 { + return request.get({ url: '/tcm.prescription/esignConfig' }) +} + +export function prescriptionEsignStatus(params: { id: number }): Promise { + return request.get({ url: '/tcm.prescription/esignStatus', params }) +} + +export function prescriptionEsignStart(params: { id: number }): Promise { + return request.post( + { url: '/tcm.prescription/esignStart', params, timeout: 180000 }, + { isOpenRetry: false, retryCount: 0, ignoreCancelToken: true } + ) +} + +export function prescriptionEsignComplete(params: { id: number }): Promise { + return request.post( + { url: '/tcm.prescription/esignComplete', params, timeout: 180000 }, + { isOpenRetry: false, retryCount: 0, ignoreCancelToken: true } + ) +} + +export function prescriptionEsignDownload(params: { id: number }): Promise { + return request.get({ url: '/tcm.prescription/esignDownload', params, timeout: 60000 }) +} + // 处方列表 export function prescriptionLists(params: any) { return request.get({ url: '/tcm.prescription/lists', params }) diff --git a/admin/src/components/EsignPrescriptionPanel.vue b/admin/src/components/EsignPrescriptionPanel.vue new file mode 100644 index 000000000..a0eeab861 --- /dev/null +++ b/admin/src/components/EsignPrescriptionPanel.vue @@ -0,0 +1,140 @@ + + + + + diff --git a/admin/src/components/tcm-prescription/index.vue b/admin/src/components/tcm-prescription/index.vue index 7be714ac0..f91e92d03 100755 --- a/admin/src/components/tcm-prescription/index.vue +++ b/admin/src/components/tcm-prescription/index.vue @@ -510,7 +510,12 @@ - + + {{ esignError }} 重试 + + +
+
已作废 已通过 @@ -679,13 +690,14 @@
- + 下载图片 - + - 下载PDF + {{ requiresOriginalEsignPdf(savedPrescription.esign) ? '下载已签原始 PDF' : '下载PDF' }}
取消 - 保存处方 + + {{ esignEnabled ? '保存后核身签署' : '保存处方' }} +
@@ -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(null) const SIGNATURE_CSS_W = 560 const SIGNATURE_CSS_H = 168 const savedPrescription = ref(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失败') } } diff --git a/admin/src/hooks/usePrescriptionEsignConfig.ts b/admin/src/hooks/usePrescriptionEsignConfig.ts new file mode 100644 index 000000000..bd6b447dd --- /dev/null +++ b/admin/src/hooks/usePrescriptionEsignConfig.ts @@ -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(null) + const loading = ref(false) + const error = ref('') + let request: Promise | null = null + + function load(): Promise { + 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 + } +} diff --git a/admin/src/utils/prescription-esign.ts b/admin/src/utils/prescription-esign.ts new file mode 100644 index 000000000..bcfe3c937 --- /dev/null +++ b/admin/src/utils/prescription-esign.ts @@ -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 { + 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 { + 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 { + 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 +} diff --git a/admin/src/views/consumer/prescription/index.vue b/admin/src/views/consumer/prescription/index.vue index 180ccfed0..70b23472f 100755 --- a/admin/src/views/consumer/prescription/index.vue +++ b/admin/src/views/consumer/prescription/index.vue @@ -283,6 +283,13 @@ >
+
待审核 已驳回
- 打印 + 打印 - 下载 PDF (A4) + {{ requiresOriginalEsignPdf(slipView?.esign) ? '下载已签原始 PDF' : '下载 PDF (A4)' }}
@@ -984,7 +992,12 @@ - + + {{ esignError }} 重试 + + +
@@ -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 | 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>([]) @@ -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 = { ...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() diff --git a/admin/src/views/consumer/prescription/order_list.vue b/admin/src/views/consumer/prescription/order_list.vue index 227818ee1..fc4137f85 100755 --- a/admin/src/views/consumer/prescription/order_list.vue +++ b/admin/src/views/consumer/prescription/order_list.vue @@ -1786,6 +1786,7 @@ 下载图片 @@ -1793,9 +1794,10 @@ - 下载PDF + {{ requiresOriginalEsignPdf(prescriptionViewData.esign) ? '下载已签原始 PDF' : '下载PDF' }}
@@ -1860,6 +1862,13 @@
驳回意见:{{ prescriptionViewData.audit_remark }}
+ 下载图片 @@ -2393,9 +2394,10 @@ - 下载PDF + {{ requiresOriginalEsignPdf(prescriptionViewData.esign) ? '下载已签原始 PDF' : '下载PDF' }}
@@ -2460,6 +2462,13 @@
驳回意见:{{ prescriptionViewData.audit_remark }}
+ { + 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('Error').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, []) + }) +} diff --git a/app/src/doctor_workstation/core/esign.py b/app/src/doctor_workstation/core/esign.py new file mode 100644 index 000000000..6493489f4 --- /dev/null +++ b/app/src/doctor_workstation/core/esign.py @@ -0,0 +1,78 @@ +"""Server-authoritative electronic signature DTOs and original-file validation.""" + +from __future__ import annotations + +import base64 +import binascii +import hashlib +import hmac +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": "历史手写签名", +} + + +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"} + ): + 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") + ): + raise ApiProtocolError("电子签署状态格式不正确") + return result + + +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 diff --git a/app/src/doctor_workstation/core/models.py b/app/src/doctor_workstation/core/models.py index 038253365..76c60f17a 100755 --- a/app/src/doctor_workstation/core/models.py +++ b/app/src/doctor_workstation/core/models.py @@ -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, diff --git a/app/src/doctor_workstation/services/mock_repository.py b/app/src/doctor_workstation/services/mock_repository.py index abdcd18ad..7e37fcc97 100755 --- a/app/src/doctor_workstation/services/mock_repository.py +++ b/app/src/doctor_workstation/services/mock_repository.py @@ -1303,8 +1303,31 @@ 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() + return result raise RepositoryNotFoundError(f"prescription {prescription_id} not found") + + 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 _disabled_prescription_esign(self) -> dict[str, Any]: + return {**self.get_prescription_esign_config(), "required": False, + "status": "legacy", "status_label": "历史手写签名", + "can_sign": False, "can_download": False, + "message": "演示模式未启用电子签署。"} + + def start_prescription_esign(self, prescription_id: int) -> dict[str, Any]: + return self.get_prescription_esign_status(prescription_id) + + def complete_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 +1346,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 +1385,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) diff --git a/app/src/doctor_workstation/services/repository.py b/app/src/doctor_workstation/services/repository.py index 85200053a..82fe80830 100755 --- a/app/src/doctor_workstation/services/repository.py +++ b/app/src/doctor_workstation/services/repository.py @@ -250,6 +250,21 @@ 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 start_prescription_esign(self, prescription_id: int) -> dict[str, Any]: + """Start or resume the creator's identity authentication flow.""" + + def complete_prescription_esign(self, prescription_id: int) -> dict[str, Any]: + """Ask the server to verify authentication and perform signing.""" + + def 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 +1711,33 @@ 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) -> dict[str, Any]: + from ..core.esign import esign_status + if prescription_id <= 0: + raise ValueError("prescription id is required") + endpoint = f"tcm.prescription/{action}" + result = _client_request(self.client, "post" if mutation else "get", endpoint, {"id": prescription_id}, timeout=180.0 if mutation else 60.0) + return esign_status(result) + + def get_prescription_esign_status(self, prescription_id: int) -> dict[str, Any]: + return self._prescription_esign_request("esignStatus", prescription_id) + + def start_prescription_esign(self, prescription_id: int) -> dict[str, Any]: + return self._prescription_esign_request("esignStart", prescription_id, mutation=True) + + def complete_prescription_esign(self, prescription_id: int) -> dict[str, Any]: + return self._prescription_esign_request("esignComplete", prescription_id, mutation=True) + + def 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 +3668,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( diff --git a/app/src/doctor_workstation/ui/dialogs/diagnosis.py b/app/src/doctor_workstation/ui/dialogs/diagnosis.py index 99129ee5d..899e4a47b 100755 --- a/app/src/doctor_workstation/ui/dialogs/diagnosis.py +++ b/app/src/doctor_workstation/ui/dialogs/diagnosis.py @@ -3740,8 +3740,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 +3753,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 +3774,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)}") diff --git a/app/src/doctor_workstation/ui/dialogs/prescription.py b/app/src/doctor_workstation/ui/dialogs/prescription.py index bd69d795a..4e58210c8 100755 --- a/app/src/doctor_workstation/ui/dialogs/prescription.py +++ b/app/src/doctor_workstation/ui/dialogs/prescription.py @@ -116,6 +116,8 @@ from ..widgets import ( show_toast, ) from .diagnosis import DiagnosisDialog as _StructuredDiagnosisDialog +from ...core.esign import esign_config, esign_status, signed_pdf_bytes +from .prescription_esign import PrescriptionEsignDialog, signature_state PRESCRIPTION_DRAWER_QSS = clinical_stylesheet(r""" QFrame#PrescriptionDrawerSurface { @@ -2874,6 +2876,8 @@ 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._loading_data = False @@ -2996,6 +3000,48 @@ class PrescriptionEditorDialog(QDialog): self.tabs = _PrescriptionSectionNavigator(self) self._load_values() self._load_editor_context() + self._load_esign_config() + + 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.setEnabled(not self._esign_content_locked()) + self.signature_field.setVisible(not self._esign_enabled) + self.esign_retry_button.hide() + self.esign_hint.setVisible(self._esign_enabled) + environment = "(沙箱测试)" if config["environment"] == "sandbox" else "" + self.esign_hint.setText(f"已启用 e签宝电子签署{environment}。保存后由开方医生完成核身并确认签署,无需手写签名。") + if self._esign_content_locked(): + self.esign_hint.setText("处方已进入电子签署,内容已冻结;如需修改,请先作废后重新开方。") + self.esign_hint.show() + + def _esign_content_locked(self) -> bool: + state = signature_state(self.prescription) + return state.get("required") is True and state.get("status") not in {"pending", "legacy"} + + 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 +3520,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 +4107,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(), @@ -4096,6 +4152,12 @@ class PrescriptionEditorDialog(QDialog): def accept(self) -> None: 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 +4170,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, @@ -5229,11 +5291,21 @@ class PrescriptionDetailDialog(QDialog): initial_tab: str = "prescription", can_open_diagnosis: bool = True, can_open_orders: bool = False, + repository: Any = None, 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.document = QTextDocument(self) self.document.setDocumentMargin(0) self.document.setHtml(render_prescription_html(prescription, variant="internal")) @@ -5254,11 +5326,16 @@ 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) 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 +5368,8 @@ class PrescriptionDetailDialog(QDialog): ) self.status_banner.show_message(" ".join(status_lines), banner_kind) root.addWidget(self.status_banner) + self.esign_banner = MessageBanner(parent=self) + root.addWidget(self.esign_banner) self.preview = _PrescriptionPaperPreview(prescription, variant="internal") self.preview.setObjectName("PrescriptionPaperPreview") self.preview.setOpenExternalLinks(False) @@ -5335,6 +5414,57 @@ class PrescriptionDetailDialog(QDialog): close.button(QDialogButtonBox.StandardButton.Close).setText("关闭") close.rejected.connect(self.reject) root.addWidget(close) + self.tabs.currentChanged.connect(self._sync_esign_export) + self._sync_esign_export() + if callable(getattr(self.repository, "get_prescription_esign_status", None)): + self.refresh_esign() + + 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 + label = str(self.esign.get("status_label") or self.esign["status"]) + environment = " · 沙箱测试" if self.esign["environment"] == "sandbox" and self.esign["status"] != "legacy" else "" + if self.esign["enabled"] or self.esign["required"]: + self.esign_banner.show_message(f"电子签署:{label}{environment} {self.esign.get('message') or ''}", "success" if self.esign["status"] == "signed" else "info") + else: + self.esign_banner.clear() + self._sync_esign_export() + + 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) + self.esign_button.setEnabled(not self._esign_busy) + self.tabs.setEnabled(not self._esign_busy) + + def open_esign(self) -> None: + dialog = PrescriptionEsignDialog(self.repository, {"id": first_value(self.prescription, "id"), "esign": self.esign}, parent=self) + 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" @@ -5392,6 +5522,43 @@ class PrescriptionDetailDialog(QDialog): output = str(path) if not output.lower().endswith(".pdf"): output += ".pdf" + if self._esign_busy: + return + if self._is_case_record_selected(): + self._export_rendered_pdf(output) + return + if callable(getattr(self.repository, "get_prescription_esign_status", None)): + self._esign_busy = True + self._sync_esign_export() + prescription_id = _int(first_value(self.prescription, "id", default=0)) + + def check_and_download() -> dict[str, Any]: + 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: + raise ValueError(current.get("message") or "当前尚无可下载的已签原件,请先完成签署。") + result = self.repository.download_prescription_esign(prescription_id) + Path(output).write_bytes(signed_pdf_bytes(result)) + return current + + def checked(current: dict[str, Any]) -> None: + self._esign_loaded(current) + if current["can_download"]: + prefix = "沙箱测试:" if current["environment"] == "sandbox" else "" + self.esign_banner.show_message(prefix + "已签原件已下载,并通过 SHA-256 校验。", "success") + else: + self._export_rendered_pdf(output) + + run_async(check_and_download, on_success=checked, on_error=self._esign_failed, on_finished=self._esign_finished) + return + if self._esign_unconfirmed or self.esign.get("status") != "legacy" or self.esign.get("required") is not False: + self.esign_banner.show_message("请先查询并确认电子签署状态,再下载处方。", "warning") + return + self._export_rendered_pdf(output) + + 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() diff --git a/app/src/doctor_workstation/ui/dialogs/prescription_esign.py b/app/src/doctor_workstation/ui/dialogs/prescription_esign.py new file mode 100644 index 000000000..ffbc8446b --- /dev/null +++ b/app/src/doctor_workstation/ui/dialogs/prescription_esign.py @@ -0,0 +1,254 @@ +"""Shared saved-prescription authentication, signing and original download flow.""" + +from __future__ import annotations + +from collections.abc import Callable, Mapping +from pathlib import Path +from typing import Any + +from PySide6.QtCore import QUrl, Signal +from PySide6.QtGui import QDesktopServices +from PySide6.QtWidgets import ( + QDialog, + QDialogButtonBox, + QFileDialog, + QHBoxLayout, + QLabel, + QPushButton, + QVBoxLayout, + QWidget, +) + +from ...core.esign import ESIGN_LABELS, authentication_url, esign_status, signed_pdf_bytes +from ..design_system import clinical_stylesheet +from ..widgets import MessageBanner, first_value, friendly_error, run_async + + +def signature_state(prescription: Any) -> dict[str, Any]: + value = first_value(prescription, "esign", default={}) + return dict(value) if isinstance(value, Mapping) else {} + + +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": + return "处方已保存,尚待完成电子签署。可在处方详情继续签署或查询结果。", "warning" + if state.get("status") == "signed": + return "处方已保存并完成电子签署,等待审核。", "success" + return fallback, "success" + + +def resume_saved_prescription(repository: Any, prescription: Any, parent: QWidget) -> None: + try: + state = esign_status(signature_state(prescription)) + except Exception: + state = {} + if state.get("required") is True and state.get("status") != "signed": + PrescriptionEsignDialog(repository, prescription, parent=parent).exec() + + +class PrescriptionEsignDialog(QDialog): + """Every displayed completion comes from a validated server response.""" + + status_changed = Signal(dict) + + 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.state: dict[str, Any] = {} + self._busy = False + self._confirmed = False + self.setWindowTitle("处方电子签署") + self.resize(580, 310) + self.setStyleSheet(clinical_stylesheet("QDialog { background:#FFFFFF; }")) + layout = QVBoxLayout(self) + layout.setContentsMargins(24, 24, 24, 24) + layout.setSpacing(16) + self.status_label = QLabel("正在确认签署状态…") + layout.addWidget(self.status_label) + hint = QLabel( + "请由开方医生在浏览器中完成核身,再返回此处确认。\n关闭窗口不会撤销已保存的处方,可从处方详情继续。" + ) + hint.setWordWrap(True) + layout.addWidget(hint) + self.banner = MessageBanner(parent=self) + layout.addWidget(self.banner) + actions = QHBoxLayout() + self.start_button = QPushButton("开始核身签署") + self.start_button.setProperty("variant", "primary") + self.start_button.clicked.connect(self.start) + self.browser_button = QPushButton("重新打开核身页面") + self.browser_button.clicked.connect(self.open_authentication) + self.complete_button = QPushButton("已完成核身,确认签署") + self.complete_button.clicked.connect(self.complete) + for button in (self.start_button, self.browser_button, self.complete_button): + actions.addWidget(button) + layout.addLayout(actions) + footer = QHBoxLayout() + self.refresh_button = QPushButton("查询签署结果") + self.refresh_button.clicked.connect(self.refresh) + self.download_button = QPushButton("下载已签原件") + self.download_button.clicked.connect(self.choose_download) + footer.addWidget(self.refresh_button) + footer.addWidget(self.download_button) + footer.addStretch(1) + self.close_buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Close) + self.close_buttons.button(QDialogButtonBox.StandardButton.Close).setText("关闭") + self.close_buttons.rejected.connect(self.reject) + footer.addWidget(self.close_buttons) + layout.addLayout(footer) + initial = signature_state(prescription) + if initial: + try: + self._apply_state(initial) + except Exception as error: + self._failed(error) + self.refresh() + + def _sync_actions(self) -> None: + available = self._confirmed and not self._busy + status = self.state.get("status") + signer = available and self.state.get("can_sign") is True + self.start_button.setEnabled(signer and status in {"pending", "failed", "authenticating"}) + self.start_button.setText("重试核身签署" if status == "failed" else "开始 / 继续核身") + self.complete_button.setEnabled(signer and status in {"authenticating", "signing"}) + self.browser_button.setEnabled( + signer and status == "authenticating" and bool(self.state.get("auth_url")) + ) + self.download_button.setEnabled(available and self.state.get("can_download") is True) + self.refresh_button.setEnabled(not self._busy) + self.close_buttons.setEnabled(not self._busy) + + def reject(self) -> None: + # Keep mutation callbacks attached to a live dialog until the result arrives. + if not self._busy: + super().reject() + + def _apply_state(self, result: Any) -> None: + self.state = esign_status(result) + self._confirmed = True + status = self.state["status"] + label = str(self.state.get("status_label") or ESIGN_LABELS[status]) + environment = "沙箱测试" if self.state["environment"] == "sandbox" else "正式环境" + self.status_label.setText(f"{label} · {environment}") + message = str(self.state.get("message") or ESIGN_LABELS[status]) + if self.state["environment"] == "sandbox": + message += "\n当前为沙箱测试签署。" + self.banner.show_message( + message, + "success" + if status == "signed" + else "warning" + if status in {"failed", "uncertain", "voided"} + else "info", + ) + self._sync_actions() + self.status_changed.emit(dict(self.state)) + + def _failed(self, error: Exception) -> None: + self._confirmed = False + self.status_label.setText("签署结果尚未确认") + self.banner.show_message( + f"{friendly_error(error)}\n请查询签署结果后再继续;当前未确认签署完成。", "danger" + ) + self._sync_actions() + + def _finished(self) -> None: + self._busy = False + self._sync_actions() + + def _request(self, method: str, *, open_browser: bool = False) -> None: + if self._busy: + return + self._busy = True + self._sync_actions() + self.banner.show_message( + "正在查询…" if method == "get_prescription_esign_status" else "正在处理,请稍候…", + "info", + ) + + def loaded(result: Any) -> None: + try: + self._apply_state(result) + if ( + open_browser + and self.state.get("auth_url") + and self.state.get("can_sign") is True + and self.state.get("status") == "authenticating" + ): + self.open_authentication() + except Exception as error: + self._failed(error) + + run_async( + lambda: getattr(self.repository, method)(self.prescription_id), + on_success=loaded, + on_error=self._failed, + on_finished=self._finished, + ) + + def refresh(self) -> None: + self._request("get_prescription_esign_status") + + def start(self) -> None: + if self.start_button.isEnabled(): + self._request("start_prescription_esign", open_browser=True) + + def complete(self) -> None: + if self.complete_button.isEnabled(): + self._request("complete_prescription_esign") + + def open_authentication(self) -> None: + if ( + not self._confirmed + or self.state.get("can_sign") is not True + or self.state.get("status") != "authenticating" + ): + return + try: + url = authentication_url(self.state.get("auth_url")) + if not QDesktopServices.openUrl(QUrl(url)): + raise ValueError("无法打开浏览器,请重试打开核身页面。") + self.banner.show_message( + "已打开核身页面。完成后请返回并点击“已完成核身,确认签署”。", "info" + ) + except Exception as error: + self.banner.show_message(str(error), "danger") + + def choose_download(self) -> None: + if not self.download_button.isEnabled(): + return + path, _ = QFileDialog.getSaveFileName( + self, "下载已签原件", f"已签处方-{self.prescription_id}.pdf", "PDF 文件 (*.pdf)" + ) + if path: + self.download_to(path) + + def download_to(self, path: str | Path, on_success: Callable[[], None] | None = None) -> None: + if self._busy or not self._confirmed or self.state.get("can_download") is not True: + return + self._busy = True + self._sync_actions() + + def work() -> None: + current = esign_status(self.repository.get_prescription_esign_status(self.prescription_id)) + if current["can_download"] is not True: + raise ValueError("已签原件尚不可下载,请查询签署结果。") + result = self.repository.download_prescription_esign(self.prescription_id) + content = signed_pdf_bytes(result) + Path(path).write_bytes(content) + + def saved(_result: Any) -> None: + self.banner.show_message("已签原件已下载,并通过 SHA-256 校验。", "success") + if on_success: + on_success() + + run_async(work, on_success=saved, on_error=self._failed, on_finished=self._finished) diff --git a/app/src/doctor_workstation/ui/pages/appointments.py b/app/src/doctor_workstation/ui/pages/appointments.py index 38a4a682d..a970c9e45 100755 --- a/app/src/doctor_workstation/ui/pages/appointments.py +++ b/app/src/doctor_workstation/ui/pages/appointments.py @@ -55,6 +55,7 @@ from ..dialogs.prescription_ai import ( present_diagnosis_ai_report, ) from ..filter_disclosure import FilterDisclosure +from ..dialogs.prescription_esign import resume_saved_prescription, saved_prescription_message, signature_state from ..icons import icon from ..infinite_list import InfiniteList from ..reception_style import heading_family @@ -1961,7 +1962,7 @@ class AppointmentsPage(QWidget): "warning", ) return - if not approved or voided: + if (not approved or voided) and not (signature_state(existing).get("required") is True and not voided): self._open_existing_prescription_editor(existing) else: dialog = PrescriptionDetailDialog( @@ -2011,16 +2012,18 @@ class AppointmentsPage(QWidget): prescription=prescription_id, changes=frozen_payload, ), - on_success=lambda _result: self._prescription_updated(generation), + 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 _begin_case_record_load(self, row: Any) -> None: snapshot = deepcopy(row) @@ -2122,16 +2125,18 @@ class AppointmentsPage(QWidget): self.banner.show_message("正在提交处方…", "info") run_async( lambda: invoke(self.repository, "create_prescription", prescription=frozen_payload), - on_success=lambda _result: self._prescription_created(generation), + 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: diff --git a/app/src/doctor_workstation/ui/pages/prescriptions.py b/app/src/doctor_workstation/ui/pages/prescriptions.py index 069a3769a..633872508 100755 --- a/app/src/doctor_workstation/ui/pages/prescriptions.py +++ b/app/src/doctor_workstation/ui/pages/prescriptions.py @@ -84,6 +84,7 @@ from ..dialogs.prescription import ( PrescriptionOrderListDialog, ) from ..filter_disclosure import FilterDisclosure +from ..dialogs.prescription_esign import resume_saved_prescription, saved_prescription_message from ..infinite_list import InfiniteList from ..prescriptions_style import prescriptions_stylesheet from ..reception_style import body_family, heading_family @@ -2301,10 +2302,17 @@ 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() + resume_saved_prescription(self.repository, prescription, self) def _delete_selected(self) -> None: row = self._selected() diff --git a/app/tests/test_prescription_esign.py b/app/tests/test_prescription_esign.py new file mode 100644 index 000000000..76ae381ad --- /dev/null +++ b/app/tests/test_prescription_esign.py @@ -0,0 +1,482 @@ +"""No-network signature contracts and real offscreen Qt workflow behavior.""" + +from __future__ import annotations + +import base64 +import hashlib +import os +from pathlib import Path +from types import SimpleNamespace +from typing import Any + +os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") + +import httpx +import pytest +from PySide6.QtWidgets import QApplication, QDialog + +from doctor_workstation.core.errors import ApiBusinessError, ApiProtocolError +from doctor_workstation.core.esign import authentication_url, esign_status, signed_pdf_bytes +from doctor_workstation.core.models import Prescription +from doctor_workstation.services.api_client import ApiClient +from doctor_workstation.services.mock_repository import DemoDoctorRepository +from doctor_workstation.services.repository import DoctorRepository, RemoteDoctorRepository +from doctor_workstation.ui.dialogs import diagnosis as diagnosis_module +from doctor_workstation.ui.dialogs import prescription as prescription_module +from doctor_workstation.ui.dialogs import prescription_esign as esign_module +from doctor_workstation.ui.pages import appointments as appointments_module +from doctor_workstation.ui.pages import prescriptions as page_module + + +def state(status: str = "pending", **fields: Any) -> dict[str, Any]: + return { + "enabled": True, + "required": True, + "environment": "sandbox", + "status": status, + "status_label": status, + "message": "服务端确认", + "can_sign": status in {"pending", "failed", "authenticating"}, + "can_download": status == "signed", + **fields, + } + + +PDF = b"%PDF-1.7\noriginal signed bytes: do not redraw\n%%EOF" + + +def download() -> dict[str, str]: + return { + "filename": "signed.pdf", + "content_base64": base64.b64encode(PDF).decode(), + "sha256": hashlib.sha256(PDF).hexdigest(), + } + + +class Repository: + def __init__(self) -> None: + self.status = state() + self.calls: list[str] = [] + self.error: Exception | None = None + + def get_prescription_esign_status(self, prescription_id: int) -> dict[str, Any]: + assert prescription_id == 7 + self.calls.append("status") + if self.error: + raise self.error + return dict(self.status) + + def start_prescription_esign(self, prescription_id: int) -> dict[str, Any]: + self.calls.append("start") + self.status = state("authenticating", auth_url="https://smlt.esign.cn/abc") + return dict(self.status) + + def complete_prescription_esign(self, prescription_id: int) -> dict[str, Any]: + self.calls.append("complete") + # A click is not proof of identity; the server can still report unauthenticated. + return dict(self.status) + + def download_prescription_esign(self, prescription_id: int) -> dict[str, str]: + self.calls.append("download") + return download() + + +@pytest.fixture(scope="module") +def application() -> QApplication: + return QApplication.instance() or QApplication([]) + + +@pytest.fixture +def immediate(monkeypatch: pytest.MonkeyPatch, application: QApplication) -> None: + def execute( + function: Any, + *args: Any, + on_success: Any = None, + on_error: Any = None, + on_finished: Any = None, + **kwargs: Any, + ) -> object: + try: + value = function(*args, **kwargs) + except Exception as error: + if on_error: + on_error(error) + else: + raise + else: + if on_success: + on_success(value) + finally: + if on_finished: + on_finished() + return object() + + for module in ( + esign_module, + prescription_module, + page_module, + appointments_module, + diagnosis_module, + ): + monkeypatch.setattr(module, "run_async", execute) + + +def test_repository_endpoints_and_response_only_state() -> None: + calls: list[tuple[str, str, dict[str, Any]]] = [] + + def request(verb: str, endpoint: str, body: Any = None, **_kwargs: Any) -> Any: + calls.append((verb, endpoint, dict(body or {}))) + if endpoint.endswith(("esignStart", "esignComplete")): + assert _kwargs["timeout"] == 180.0 + if endpoint.endswith("esignConfig"): + return {"enabled": True, "environment": "sandbox"} + if endpoint.endswith("esignDownload"): + return download() + if endpoint.endswith(("add", "edit", "detail")): + return {"id": 7, "esign": state()} + return state() + + client = SimpleNamespace( + get=lambda endpoint, body=None, **kwargs: request("GET", endpoint, body, **kwargs), + post=lambda endpoint, body=None, **kwargs: request("POST", endpoint, body, **kwargs), + ) + repository = RemoteDoctorRepository(client) + assert repository.get_prescription_esign_config()["enabled"] + assert repository.get_prescription_esign_status(7)["status"] == "pending" + repository.start_prescription_esign(7) + repository.complete_prescription_esign(7) + assert signed_pdf_bytes(repository.download_prescription_esign(7)) == PDF + expected = [ + ("GET", "esignConfig", {}), + ("GET", "esignStatus", {"id": 7}), + ("POST", "esignStart", {"id": 7}), + ("POST", "esignComplete", {"id": 7}), + ("GET", "esignDownload", {"id": 7}), + ] + assert calls == [ + (verb, "tcm.prescription/" + action, params) for verb, action, params in expected + ] + created = repository.create_prescription({"patient_name": "测试", "esign": state("signed")}) + updated = repository.update_prescription(created) + detail = repository.get_prescription(7) + for model in (created, updated, detail): + assert model.esign == state() + assert Prescription.from_dict(model.to_api_dict()).esign == state() + assert all("esign" not in payload for verb, _, payload in calls if verb == "POST") + + +def test_actual_api_envelope_unwrap_never_returns_failed_status() -> None: + client = object.__new__(ApiClient) + assert client._unwrap(httpx.Response(200, json={"code": 1, "data": state()})) == state() + with pytest.raises(ApiBusinessError): + client._unwrap(httpx.Response(200, json={"code": 0, "msg": "签署服务不可用", "data": state("signed")})) + + +def test_demo_and_protocol_have_matching_disabled_methods() -> None: + repository = DemoDoctorRepository() + prescription = repository.create_prescription({"patient_name": "演示"}) + assert repository.get_prescription_esign_config() == { + "enabled": False, + "environment": "sandbox", + } + for name in ( + "get_prescription_esign_config", + "get_prescription_esign_status", + "start_prescription_esign", + "complete_prescription_esign", + "download_prescription_esign", + ): + assert callable(getattr(DoctorRepository, name)) + assert callable(getattr(repository, name)) + assert callable(getattr(RemoteDoctorRepository, name)) + assert repository.get_prescription_esign_status(prescription.id)["required"] is False + + +@pytest.mark.parametrize( + "url", + [ + "http://smlt.esign.cn/abc", + "javascript:alert(1)", + "https://smlt.esign.cn.evil.test/x", + "https://evil.test/x", + "https://user@smlt.esign.cn/x", + "https://smlt.esign.cn:444/x", + "https://smlfront.esign.cn:444/x", + "https://smlt.esign.cn:8890/x", + "file:///tmp/a", + ], +) +def test_authentication_rejects_nonprovider_urls(url: str) -> None: + with pytest.raises(ValueError): + authentication_url(url) + + +@pytest.mark.parametrize("host", ["smlt.esign.cn", "smlfront.esign.cn", "t.esign.cn", "idverify.esign.cn"]) +def test_official_short_urls_allowed(host: str) -> None: + assert authentication_url(f"https://{host}/abc") == f"https://{host}/abc" + + +def test_official_sandbox_long_url_port_allowed() -> None: + url = "https://smlfront.esign.cn:8890/identity/login" + assert authentication_url(url) == url + + +def test_authentication_browser_open_and_complete_never_assume_signed( + immediate: None, monkeypatch: pytest.MonkeyPatch +) -> None: + opened: list[str] = [] + monkeypatch.setattr( + esign_module.QDesktopServices, "openUrl", lambda url: opened.append(url.toString()) or True + ) + repository = Repository() + dialog = esign_module.PrescriptionEsignDialog(repository, {"id": 7, "esign": state()}) + assert dialog.start_button.isEnabled() + dialog.start_button.click() + assert opened == ["https://smlt.esign.cn/abc"] + assert dialog.state["status"] == "authenticating" + dialog.complete_button.click() + assert repository.calls == ["status", "start", "complete"] + assert dialog.state["status"] == "authenticating" + assert not dialog.download_button.isEnabled() + repository.status = state("signed") + dialog.refresh_button.click() + assert dialog.state["status"] == "signed" + assert dialog.download_button.isEnabled() + assert not dialog.start_button.isEnabled() + dialog.close() + + +@pytest.mark.parametrize( + "status,can_sign", [("pending", False), ("uncertain", True), ("signed", True), ("voided", True)] +) +def test_server_capabilities_and_uncertain_state_block_signing( + immediate: None, status: str, can_sign: bool +) -> None: + repository = Repository() + repository.status = state(status, can_sign=can_sign) + dialog = esign_module.PrescriptionEsignDialog(repository, {"id": 7, "creator_id": 1}) + dialog.start() + dialog.complete() + assert repository.calls == ["status"] + dialog.close() + + +def test_failed_query_requires_refresh_before_any_retry(immediate: None) -> None: + repository = Repository() + repository.error = RuntimeError("network unavailable") + dialog = esign_module.PrescriptionEsignDialog(repository, {"id": 7, "esign": state("signed")}) + assert not dialog.start_button.isEnabled() + assert not dialog.download_button.isEnabled() + assert "尚未确认" in dialog.status_label.text() + repository.error = None + repository.status = state("failed") + dialog.refresh() + assert dialog.start_button.isEnabled() + dialog.close() + + +def test_invalid_state_cannot_claim_completion() -> None: + with pytest.raises(ApiProtocolError): + esign_status(state("signed", can_download="true")) + + +def test_download_validates_original_and_hash_before_writing( + immediate: None, tmp_path: Path +) -> None: + repository = Repository() + repository.status = state("signed") + dialog = esign_module.PrescriptionEsignDialog(repository, {"id": 7}) + target = tmp_path / "original.pdf" + dialog.download_to(target) + assert target.read_bytes() == PDF + repository.download_prescription_esign = lambda _id: {**download(), "sha256": "0" * 64} + dialog.download_to(target) + assert target.read_bytes() == PDF + assert not dialog._confirmed + dialog.close() + + +def test_detail_export_downloads_signed_original_without_rendering( + immediate: None, monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + repository = Repository() + repository.status = state("signed") + dialog = prescription_module.PrescriptionDetailDialog( + {"id": 7, "esign": state("signed")}, repository=repository + ) + monkeypatch.setattr( + dialog, "_current_output_image", lambda: pytest.fail("must never redraw a signed PDF") + ) + target = tmp_path / "signed.pdf" + dialog.export_pdf(target) + assert target.read_bytes() == PDF + assert repository.calls == ["status", "status", "download"] + dialog.close() + + +@pytest.mark.parametrize("new_status", [state(), {}, state("signed", enabled=False)]) +def test_detail_download_rechecks_stale_legacy_before_rendering( + immediate: None, monkeypatch: pytest.MonkeyPatch, tmp_path: Path, new_status: dict[str, Any] +) -> None: + repository = Repository() + repository.status = state("legacy", enabled=False, required=False, can_sign=False) + dialog = prescription_module.PrescriptionDetailDialog({"id": 7}, repository=repository) + assert dialog.pdf_button.isEnabled() + repository.status = new_status + monkeypatch.setattr(dialog, "_current_output_image", lambda: pytest.fail("stale legacy must not render")) + target = tmp_path / "export.pdf" + dialog.export_pdf(target) + if new_status.get("can_download"): + assert target.read_bytes() == PDF + assert "沙箱测试" in dialog.esign_banner.label.text() + else: + assert not target.exists() + assert dialog._esign_unconfirmed + dialog.close() + + +def test_missing_state_without_repository_cannot_export( + immediate: None, monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + dialog = prescription_module.PrescriptionDetailDialog({"id": 7}) + monkeypatch.setattr(dialog, "_current_output_image", lambda: pytest.fail("unknown state must not render")) + target = tmp_path / "unknown.pdf" + dialog.export_pdf(target) + assert not target.exists() + assert not dialog.pdf_button.isEnabled() + dialog.close() + + +def test_preparing_cannot_start_or_complete(immediate: None) -> None: + repository = Repository() + repository.status = state("authenticating", can_sign=False, message="正在准备认证链接") + dialog = esign_module.PrescriptionEsignDialog(repository, {"id": 7}) + dialog.start() + dialog.complete() + assert repository.calls == ["status"] + dialog.close() + + +def test_saved_response_without_state_warns_without_claiming_completion( + immediate: None, monkeypatch: pytest.MonkeyPatch +) -> None: + resumed = [] + monkeypatch.setattr(esign_module.PrescriptionEsignDialog, "exec", lambda self: resumed.append(self.prescription_id)) + record = {"id": 7} + message, kind = esign_module.saved_prescription_message(record, "已提交审核") + assert kind == "warning" and "尚未确认" in message + esign_module.resume_saved_prescription(Repository(), record, None) + assert resumed == [] + + +@pytest.mark.parametrize("nested", [False, True]) +def test_partial_mutation_response_preserves_prescription_content(nested: bool) -> None: + payload = { + "id": 7, "patient_name": "测试患者", "clinical_diagnosis": "脾气虚", + "herbs": [{"name": "黄芪", "dosage": 15, "formula_type": "主方"}], + "aux_usage": {"times_per_day": 2}, "usage_notes": "测试医嘱", + } + response = {"id": 7, "esign": state()} + client = SimpleNamespace(post=lambda *_args: {"data": response} if nested else response) + repository = RemoteDoctorRepository(client) + for result in (repository.create_prescription(payload), repository.update_prescription(payload)): + rendered = result.to_api_dict() + assert result.id == 7 and result.esign == state() + for field in ("patient_name", "clinical_diagnosis", "herbs", "aux_usage", "usage_notes"): + assert rendered[field] == payload[field] + + +def make_editor( + config: Any, *, esign: dict[str, Any] | None = None +) -> prescription_module.PrescriptionEditorDialog: + repository = SimpleNamespace( + get_prescription_esign_config=config, + list_medicines=lambda **kwargs: {"lists": [{"id": 31, "name": "黄芪"}], "count": 1}, + ) + editor = prescription_module.PrescriptionEditorDialog( + repository, + {"esign": esign} if esign else None, + mode="edit" if esign else "add", + current_user={"id": 1, "name": "医生"}, + ) + 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) + return editor + + +@pytest.mark.parametrize("enabled", [True, False]) +def test_editor_requires_handwriting_only_when_disabled(immediate: None, enabled: bool) -> None: + editor = make_editor(lambda: {"enabled": enabled, "environment": "sandbox"}) + editor.accept() + assert (editor.result() == QDialog.DialogCode.Accepted) is enabled + assert editor.signature_field.isHidden() is enabled + assert editor.payload()["doctor_signature"] == "" + editor.close() + + +@pytest.mark.parametrize( + "status", ["authenticating", "signing", "signed", "failed", "uncertain", "voided"] +) +def test_editor_blocks_frozen_signature_content(immediate: None, status: str) -> None: + editor = make_editor(lambda: {"enabled": True, "environment": "sandbox"}, esign=state(status)) + assert not editor.save_button.isEnabled() + editor.accept() + assert editor.result() != QDialog.DialogCode.Accepted + assert "冻结" in editor.validation.label.text() + editor.close() + + +def test_editor_configuration_failure_blocks_save_and_can_retry(immediate: None) -> None: + def fail() -> Any: + raise RuntimeError("network unavailable") + + editor = make_editor(fail) + assert not editor.save_button.isEnabled() + editor.accept() + assert editor.result() != QDialog.DialogCode.Accepted + editor.repository.get_prescription_esign_config = lambda: { + "enabled": True, + "environment": "sandbox", + } + editor.esign_retry_button.click() + assert editor.save_button.isEnabled() + editor.accept() + assert editor.result() == QDialog.DialogCode.Accepted + editor.close() + + +def test_all_save_entrypoints_pass_returned_dto_to_shared_flow( + immediate: None, monkeypatch: pytest.MonkeyPatch +) -> None: + resumed: list[Any] = [] + messages: list[tuple[str, str]] = [] + record = Prescription.from_dict({"id": 7, "esign": state()}) + + def resume(repository: Any, result: Any, parent: Any) -> None: + resumed.append(result) + + for module in (esign_module, page_module, appointments_module): + monkeypatch.setattr(module, "resume_saved_prescription", resume) + monkeypatch.setattr(page_module, "show_toast", lambda *args: None) + owner = SimpleNamespace( + repository=object(), + banner=SimpleNamespace(show_message=lambda text, kind: messages.append((text, kind))), + refresh=lambda **kwargs: None, + _action_generation=1, + _media_generation=1, + _diagnosis_id=2, + _show_message=lambda text, kind: messages.append((text, kind)), + _loaded_tabs=set(), + _ensure_tab_loaded=lambda *args, **kwargs: None, + ) + page_module.PrescriptionsPage._prescription_saved(owner, record, "saved") + appointments_module.AppointmentsPage._prescription_created(owner, 1, record) + appointments_module.AppointmentsPage._prescription_updated(owner, 1, record) + diagnosis_module.DiagnosisDialog._media_mutation_success( + owner, "saved", "prescription", 2, 1, record + ) + assert resumed == [record] * 4 + assert all(kind == "warning" and "尚待完成电子签署" in text for text, kind in messages) diff --git a/app/tests/test_prescription_ui.py b/app/tests/test_prescription_ui.py index 9c71315be..73bc97ab6 100755 --- a/app/tests/test_prescription_ui.py +++ b/app/tests/test_prescription_ui.py @@ -929,6 +929,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": "林晓岚", diff --git a/artifacts/esign-admin-implementation.md b/artifacts/esign-admin-implementation.md new file mode 100644 index 000000000..86012fbc4 --- /dev/null +++ b/artifacts/esign-admin-implementation.md @@ -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`。 diff --git a/artifacts/esign-backend-review.md b/artifacts/esign-backend-review.md new file mode 100644 index 000000000..ee415f499 --- /dev/null +++ b/artifacts/esign-backend-review.md @@ -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` 为准。 diff --git a/artifacts/esign-backend-review.png b/artifacts/esign-backend-review.png new file mode 100644 index 0000000000000000000000000000000000000000..23303be6c1e46f14d19f7da436e51ee2a815eeb8 GIT binary patch literal 82728 zcmeFZhdr>JHX$n` z<9D2WzW486xbMf~zR$<^dtEMZI^Xa2a~#j(IG(RiH5FOX{WSZDh=@q#<)k%;h=^Yh z5$$BtQ4bQsf9-RU({&*tI#fgW{~ZrG4$%@3F%rp3OKN#0{_68EIJz<{{=1Qp zk(NR?@a|oG1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=94wxt4fpxA6z6|YYD;4Q31F*ot*Vz~0PZva+6u`9@GiS(EefKmW z2N!v(k(H5QP7*^|4e9Ayq(5NK#dV`ei;0!NcXgwihWuGx=fA(`fw`d6@V4w3baQ}t zpoy2&&aR0EiLz+-#Cw0>lO4o+lKMUL_R~x%pOc$0P}_;!Bvy6Vv7KRiL@I9Y=qaBFS_Yhr<|O%JT0J5b+p54s-6s z-r!0>cugw%{V%m19gIDy5HJ<2k_G8-KG?`tXiyb-%Yk;jLXdp_zWX0*zKV$SS|{iN z+;2`AdquM6k?)1#Lb&V;;Y_oHZ~On}i_G`(>LNPjOQOuW$>+%(>9(oU+%~m%Mm8L^ zI@g}1EH(g*6Y!;kEvG;+G0|W@WI~J-J7X^pNl6^&C!=k+t0etF$#T%&_LAR(P3T?^ zC!ar>EpLAXkxnb>weiOpa@-|x#y{D*#rS*lQ=`#+`g@n69y|1&Bh z|9`%{JEn8)F#%~BR^jOBA2YSr9{Ea=#Mg$L>;I0w?RUF!N5IHe0iMEc>1yjQygq-8 G&;JEsk|lBg literal 0 HcmV?d00001 diff --git a/artifacts/esign-desktop-implementation.md b/artifacts/esign-desktop-implementation.md new file mode 100644 index 000000000..9551c403b --- /dev/null +++ b/artifacts/esign-desktop-implementation.md @@ -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 显示沙箱提示,沙箱签署不会由桌面升级为生产签署。服务端仍是签署主体、访问权限、内容冻结、幂等、审核与正式发药门禁的最终执行者。 diff --git a/artifacts/esign-prescription-test.pdf b/artifacts/esign-prescription-test.pdf new file mode 100644 index 000000000..7d759706c --- /dev/null +++ b/artifacts/esign-prescription-test.pdf @@ -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 117 Tm <533b5e0875355b507b7e7ae0> Tj ET +BT /F1 8 Tf 1 0 0 1 45 58 Tm <590465b95feb71670020005300480041002d003200350036> Tj ET +BT /F1 7 Tf 1 0 0 1 45 44 Tm <0063006200660063003000640039003500630062006600620062003600360037006400620062006500300064003400390038003700320064003500350030006300660062006200360031003400310063003900650066006100640036003200370032003100320038003200620038006100340038006400650036006600650030> Tj ET +BT /F1 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 diff --git a/artifacts/esign-prescription-test.png b/artifacts/esign-prescription-test.png new file mode 100644 index 0000000000000000000000000000000000000000..9127e2b44e82e783dbbfb7d9ee03cf45ded1b0a8 GIT binary patch literal 51402 zcmc$`XH-<(wk?Vo6QGD7Q4~RmisY!Jh=`I=GKvV25kWvg=_iPa1Op&R3?LaK=OCyE z2uKpiS(4`dE+ER1|mbVBSGRMYUV$ z{8zFl9m_u;!ybUorz)-UeSC)U zf9{oTqx?hd{y+KR|GQuQ&jtL?F6008U!JOqkBd7hAn@hZ61$w7oV8d%hWXB&JIl+< z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ul>F{%W; z5Z9fsKIFR#2+xkD0Iqyy{BW1_IIV(^&hoiAsxD};Ncviy9d_S+=O6ov@2c*2zOMyd z)|c>c!NWfHmVVlv`>UX@^eRR<04dH#iYR#Z{8(B!H%#H^d8xpzBa>i*q8Jkx0qX}h z8ME-DK}HdP#71yNxfRj)jQK$KMAc%kA`auTI#TlbBr7r&n5BJVIA-6*t5G^3Vf$U zP&bL27kH*ZD1*w2H0GbiApUh$i5(0+MDpE80}2VB*!XNi?=LQxM&|IuIAZbCm!Nth z@e}|Z22P-$0Ew70Z{BCI^Jvq|_}c36MZT;ka3SIR3O~fUqFaw35*g$lk6Jjpz-KD$ z+t{TuJ2US2W#;K_+dTQ#I6&7f%{IlzGTDFu9Z(nOD6lxW6JyMki$9z$Ac+e43si77w^4ZJD5=eBJ zmMe4YJnd<=<$cF&W!3YLq1t!`_0sK9G-@NK)qMfHOj(R5>MI|mdBdFi;hVn~z5_N!aPOCM#52c!kv&*N;`qv!%k` zMk;L2Goz&C#W0r$~r^v1zw-hhj$5-L@S)T4*oEh_$PYj spO8WSWc1=cCWHRWD7DKqOS@=PY#(<`B?i-(E?vHzxxny(!3y911K^w!x&QzG literal 0 HcmV?d00001 diff --git a/artifacts/esign-provider-implementation.md b/artifacts/esign-provider-implementation.md new file mode 100644 index 000000000..dd7aa14b7 --- /dev/null +++ b/artifacts/esign-provider-implementation.md @@ -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_`。 +- 签署发出后超时、传输失败、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+(有效期接口所需版本)、初始化成功、应用开通核身与签署权限后,再按新造的测试处方完成一次人工核身 → 签署 → 验签 → 原件下载闭环。 diff --git a/artifacts/esign-runtime-install.md b/artifacts/esign-runtime-install.md new file mode 100644 index 000000000..2dd21bef1 --- /dev/null +++ b/artifacts/esign-runtime-install.md @@ -0,0 +1,103 @@ +# e签宝本机 PaaS-SDK-Service 运行环境 + +准备日期:2026-11-17。完成便携 Java 与 Tomcat 下载、校验、解压和本机配置;本次没有取得或启动 SDK WAR,没有初始化应用或读取 `.env`。以下状态是运行环境准备完成时的快照,不代表后续 SDK 部署结果。 + +## 同日后续部署结果 + +根侧已通过用户登录后的[供应商官方附件页](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` 监听。 +- 已通过项目真实 PHP 适配器请求初始化,SDK 联系到 e签宝云端,返回 **338005:应用 IP 白名单未配置**。尚不能宣称初始化成功或完成签署。等待用户配置云端应用的白名单。 +- 初始化后的本地日志未检出应用 secret。未连接业务数据库、创建签署账号或签署处方;业务开关仍为关闭。 +- 已实际验证正常停服和再次隐藏启动,重启后首页仍为 HTTP 200;修正 PowerShell JSON 自动日期转换造成的进程时间比较问题,PID 与 Java 路径核验保持有效。 + +白名单配置完成后运行: + +```powershell +php 'D:\web\zyt\.spool\esign-runtime\initialize-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。 + +**尚待验证:** 这个组合符合 Java 8 与 Java EE 的运行时基线,但并非供应商列出的精确测试组合。须拿到官方 WAR 后验证部署、SDK 沙箱初始化、调用及 PDF 输出,不能由 Java/Tomcat 版本检查推断业务兼容性。 + +## 官方下载和校验 + +下载使用 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 启动、SDK 初始化、核身、签署或真实业务调用。 diff --git a/artifacts/esign-ui-integration-review.md b/artifacts/esign-ui-integration-review.md new file mode 100644 index 000000000..0a715eea9 --- /dev/null +++ b/artifacts/esign-ui-integration-review.md @@ -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 端口”应以此例外为准。 diff --git a/artifacts/esign-workflow-research.md b/artifacts/esign-workflow-research.md new file mode 100644 index 000000000..c54d92295 --- /dev/null +++ b/artifacts/esign-workflow-research.md @@ -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 签署取消后仍保持待签。供应商集成测试使用沙箱和显式配置,不能借现有患者数据/生产医生身份做自动冒烟。 diff --git a/docs/plans/esign-prescription-integration.md b/docs/plans/esign-prescription-integration.md new file mode 100644 index 000000000..7a16a68af --- /dev/null +++ b/docs/plans/esign-prescription-integration.md @@ -0,0 +1,83 @@ +# 医生开方 e签宝 SDK 3.0 接入 + +日期:2026-11-17。用户确认使用沙箱。代码覆盖 PHP 后端、Vue 后台及 Python 医生工作站。真实沙箱核身和签署仍待 SDK 服务部署后联调。 + +## 医生操作 + +启用后,保存处方进入待电子签署,手写图片不再必填。医生从保存后的面板或处方详情打开 e签宝核身页面,完成认证后点击“完成核身/继续签署”。服务端主动核实认证结果、绑定医生账号,使用冻结的处方 PDF 签署并验签,成功后允许药师审核。医生与药师均可按原处方查看权限下载已签 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/esignStart` | POST `{id}` | 冻结处方,返回当前医生的核身链接 | +| `tcm.prescription/esignComplete` | POST `{id}` | 查询核身、签署、验签及归档 | +| `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 与签署流水共同归档。 + +临床审核与发药前复查签署状态及内容摘要;发药额外要求 production 环境。已签 PDF 不再通过截图、canvas 或 QPdfWriter 重绘,以免丢失数字签名。旧手写图字段可保存签章展示图,可信证据是已签 PDF 和签署流水。 + +审核、手工调整订单审核状态以及药房提交占用记录写入,均在数据库事务中锁定处方并检查签署证据。驳回作废与编辑共用药房占用锁,防止并发改动绕过已冻结的内容。通知在审核事务提交后发送。 + +认证链接支持官方短链和长链;沙箱长链 `smlfront.esign.cn:8890` 为明确允许的例外端口。客户端签署调用等待 180 秒且不自动重发;PHP 完成签署接口允许执行 300 秒,并在客户端断开后继续归档。部署时应匹配反向代理及 PHP-FPM 的超时配置;超时后查询服务端状态,不能直接重复签署。 + +## 异常恢复 + +- 核身未完成:回到原核身链接,完成后查询/继续;不要新建重复处方。 +- 核身失败/超期或供应商明确拒绝:界面保留失败状态,可根据提示重新核身。内容仍冻结;如处方有误,作废后新开。 +- 签署调用超时、响应损坏或结果不明:置为 `uncertain`,阻止自动重签,避免重复收费或重复消费认证 ID。由管理员依据签署流水与供应商核实。 +- 已取得并归档签后文件,但验签服务暂不可用:服务恢复后运行 `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-17 后续安装:已取得官方 3.1.26 包并在本机部署,`http://127.0.0.1:8091/paas-sdk-service/` 返回 HTTP 200。真实沙箱初始化返回 `338005`(应用 IP 白名单未配置),需先在 e签宝后台配置当前国内出口 IP,再重试初始化。功能仍保持关闭;未执行真实医生核身、实际签署、生产库迁移或线上发布。安装与启停方法见 `artifacts/esign-runtime-install.md`。该地址仅对这台 Windows 机器有效,线上 PHP 服务器不能通过它访问本机 SDK。 diff --git a/server/.env.esign.example b/server/.env.esign.example new file mode 100644 index 000000000..22ad42c63 --- /dev/null +++ b/server/.env.esign.example @@ -0,0 +1,12 @@ +# 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] +ENABLED = false +ENVIRONMENT = sandbox +APP_ID = +APP_SECRET = +SDK_URL = http://127.0.0.1:8091/paas-sdk-service +TIMEOUT = 60 +# Optional private persistent directory; default is server/storage/esign. +# STORAGE_PATH = /srv/zyt-private/esign diff --git a/server/app/adminapi/controller/tcm/PrescriptionController.php b/server/app/adminapi/controller/tcm/PrescriptionController.php index 3d80a2019..07b26d20a 100755 --- a/server/app/adminapi/controller/tcm/PrescriptionController.php +++ b/server/app/adminapi/controller/tcm/PrescriptionController.php @@ -7,6 +7,7 @@ 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\PrescriptionEsignService; /** * 中医处方单控制器 @@ -32,7 +33,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 +46,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)]); } /** @@ -181,4 +182,50 @@ class PrescriptionController extends BaseAdminController } return $this->success('作废成功'); } + + public function esignConfig() + { + return $this->data(PrescriptionEsignService::capability()); + } + + public function esignStatus() + { + return $this->esignOperation('status', false); + } + + public function esignStart() + { + return $this->esignOperation('start', true); + } + + public function esignComplete() + { + return $this->esignOperation('complete', true); + } + + public function esignDownload() + { + return $this->esignOperation('download', false); + } + + 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 { + return $this->data(PrescriptionEsignService::{$operation}($id, (int) $this->adminId, $this->adminInfo)); + } catch (\Throwable $e) { + return $this->fail($e instanceof \DomainException ? $e->getMessage() : '电子签署暂不可用,请联系管理员'); + } + } } diff --git a/server/app/adminapi/http/middleware/AuthMiddleware.php b/server/app/adminapi/http/middleware/AuthMiddleware.php index 8ec54daa0..61e7b257f 100755 --- a/server/app/adminapi/http/middleware/AuthMiddleware.php +++ b/server/app/adminapi/http/middleware/AuthMiddleware.php @@ -82,6 +82,24 @@ 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']); + $grants = in_array($action, ['esignstart', 'esigncomplete'], true) ? $writes : $reads; + return in_array($action, ['esignstart', 'esigncomplete', 'esignstatus', 'esigndownload'], true) + && array_intersect($grants, $uris) !== [] + ? $next($request) : JsonService::fail('权限不足,无法访问电子签署'); + } + // 患者列表的部门筛选复用列表权限;只允许 GET 查询显式启用数据范围的部门树。 // 必须与 DeptController::all 读取同一个 GET 参数,避免请求体参数意外放行全量部门。 if ($accessUri === 'dept.dept/all' diff --git a/server/app/adminapi/lists/tcm/PrescriptionLists.php b/server/app/adminapi/lists/tcm/PrescriptionLists.php index 0297ca0bd..138b79b48 100755 --- a/server/app/adminapi/lists/tcm/PrescriptionLists.php +++ b/server/app/adminapi/lists/tcm/PrescriptionLists.php @@ -296,6 +296,7 @@ class PrescriptionLists extends BaseAdminDataLists implements ListsSearchInterfa // 处理字段格式 foreach ($lists as &$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'] ?? '温水送服'; diff --git a/server/app/adminapi/logic/tcm/PrescriptionLogic.php b/server/app/adminapi/logic/tcm/PrescriptionLogic.php index 30e9ac482..aade8e0b6 100755 --- a/server/app/adminapi/logic/tcm/PrescriptionLogic.php +++ b/server/app/adminapi/logic/tcm/PrescriptionLogic.php @@ -19,6 +19,8 @@ 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 { @@ -394,6 +396,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 +463,7 @@ class PrescriptionLogic } // 已通过且未作废:不可编辑 + PrescriptionEsignPolicy::assertMutable($prescription->toArray()); if ((int) ($prescription->audit_status ?? 1) === 1 && (int) ($prescription->void_status ?? 0) === 0) { self::setError('该处方已通过审核,不可编辑'); return false; @@ -555,7 +562,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 +578,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 +642,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 +659,7 @@ class PrescriptionLogic return false; } + PrescriptionEsignPolicy::assertMutable($prescription->toArray()); $patientName = trim($patientName); $phone = trim($phone); if ($patientName === '') { @@ -767,6 +779,7 @@ class PrescriptionLogic return false; } + PrescriptionEsignPolicy::assertMutable($prescription->toArray()); $prescription->delete(); PrescriptionAiStore::invalidate($id, 'deleted'); return true; @@ -792,6 +805,7 @@ 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'] ?? ''); @@ -848,31 +862,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); + $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) { self::$lastAuditWecomNotify = self::notifyCreatorAuditResult($row, 'approve', $finalRemark, $adminInfo); } } catch (\Throwable $e) { @@ -905,7 +912,29 @@ 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; + } + 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 +947,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 +957,19 @@ class PrescriptionLogic $now = time(); if ($action === 'approve') { + try { + PrescriptionEsignService::assertSignedById($id); + } 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 +988,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 +1089,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 +1133,9 @@ class PrescriptionLogic return null; } - return $row->toArray(); + $result = $row->toArray(); + $result['esign'] = PrescriptionEsignService::describe($result, $viewerAdminId); + return $result; } /** @@ -1234,6 +1262,10 @@ class PrescriptionLogic 'assistant_id' => $assistantIdForRx, ]; + if (PrescriptionEsignService::enabled()) { + $data['esign_required'] = 1; + $data['esign_status'] = 'pending'; + } $prescription = new Prescription(); $prescription->save($data); diff --git a/server/app/adminapi/logic/tcm/PrescriptionOrderLogic.php b/server/app/adminapi/logic/tcm/PrescriptionOrderLogic.php index e3b92f40a..e041d91a5 100755 --- a/server/app/adminapi/logic/tcm/PrescriptionOrderLogic.php +++ b/server/app/adminapi/logic/tcm/PrescriptionOrderLogic.php @@ -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): bool + { + try { + PrescriptionEsignService::assertSignedById((int) $order->prescription_id, $forDispensing); + 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,7 +2366,32 @@ 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 = '订单不存在'; @@ -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)) { 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,6 +2868,9 @@ class PrescriptionOrderLogic if (!in_array($newRx, [0, 1, 2], true)) { self::$error = '处方审核状态无效'; + return false; + } + if ($newRx === 1 && !self::assertEsignApproved($order)) { return false; } $oldRx = (int) $order->prescription_audit_status; @@ -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|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('无权限修改此处方'); diff --git a/server/app/adminapi/validate/tcm/PrescriptionValidate.php b/server/app/adminapi/validate/tcm/PrescriptionValidate.php index 741f23002..c2dcef454 100755 --- a/server/app/adminapi/validate/tcm/PrescriptionValidate.php +++ b/server/app/adminapi/validate/tcm/PrescriptionValidate.php @@ -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', diff --git a/server/app/command/EsignSetup.php b/server/app/command/EsignSetup.php new file mode 100644 index 000000000..f7c26bdf0 --- /dev/null +++ b/server/app/command/EsignSetup.php @@ -0,0 +1,52 @@ +setName('esign:setup')->setDescription('检查 e签宝配置、初始化内网 SDK 或恢复已归档签署结果') + ->addOption('initialize', null, Option::VALUE_NONE, '初始化已部署的 SDK;不创建医生、认证或处方签署') + ->addOption('recover', null, Option::VALUE_REQUIRED, '重新验签已归档的处方 ID;不会再次签署'); + } + + 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('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('' . ($e instanceof \DomainException ? $e->getMessage() : 'SDK 操作失败,请检查内网服务、应用环境和 e签宝 IP 白名单') . ''); + return 1; + } + } +} diff --git a/server/app/common/service/esign/EsignClient.php b/server/app/common/service/esign/EsignClient.php new file mode 100644 index 000000000..2499f3808 --- /dev/null +++ b/server/app/common/service/esign/EsignClient.php @@ -0,0 +1,409 @@ + [ + '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'); + } + $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 + { + $this->requireText($name, 'startIdentity'); + $this->requireText($contextId, 'startIdentity'); + $person = ['name' => $name, 'certType' => 'INDIVIDUAL_CH_IDCARD']; + if ($accountId !== null) { + $this->requireText($accountId, 'startIdentity'); + $person['sdkAccountId'] = $accountId; + } + $response = $this->identityJson('startIdentity', 'POST', '/v2/identity/auth/web/indivAuthUrl', [ + 'indivInfo' => $person, + 'configParams' => ['indivUneditableInfo' => ['name', 'certType']], + 'contextInfo' => ['contextId' => $contextId, 'showResultPage' => true], + ]); + $data = $response['data'] ?? null; + if (!is_array($data) || !is_string($data['flowId'] ?? null) || trim($data['flowId']) === '') { + throw new EsignProviderException('startIdentity', 'RESPONSE_INVALID'); + } + $url = !empty($data['shortLink']) ? $data['shortLink'] : ($data['url'] ?? ''); + if (!is_string($url) || !$this->isTrustedAuthUrl($url)) { + throw new EsignProviderException('startIdentity', 'AUTH_URL_INVALID'); + } + return ['flow_id' => $data['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->requireText($flowId, 'checkWillingness'); + $data = $this->sdkJson('checkWillingness', '/timevale/auth/queryWillingnessValidity', ['willingnessId' => $flowId]); + if (($data['status'] ?? null) !== 1 + || !is_int($data['remainingTimes'] ?? null) || $data['remainingTimes'] < 1 + || !is_int($data['expireAt'] ?? null) || $data['expireAt'] <= ($this->clock)()) { + throw new EsignProviderException('checkWillingness', 'WILLINGNESS_INVALID'); + } + } + + 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 + { + 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' => 420, 'posY' => 70, 'width' => 100]], + ], $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 { + $response = ($this->transport)([ + 'method' => $method, 'url' => $url, 'headers' => $headers, 'body' => $body, + 'timeout' => (int) ($this->configuration['timeout'] ?? 60), + ]); + } 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) { + throw new EsignProviderException($operation, 'PROVIDER_' . $data[$codeKey]); + } + return $data; + } + + 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 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 ($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; + } +} diff --git a/server/app/common/service/esign/PrescriptionEsignPolicy.php b/server/app/common/service/esign/PrescriptionEsignPolicy.php new file mode 100644 index 000000000..061d6d721 --- /dev/null +++ b/server/app/common/service/esign/PrescriptionEsignPolicy.php @@ -0,0 +1,103 @@ + self::enabled(), 'environment' => (string) Config::get('esign.environment', 'sandbox')]; + } + + public static function status(int $id, int $actor, array $adminInfo): array + { + $model = Prescription::find($id); + if (!$model || !PrescriptionLogic::canViewPrescription($model, $actor, $adminInfo)) { + throw new DomainException('处方不存在或无权查看'); + } + return self::describe($model->toArray(), $actor); + } + + public static function describe(array $row, int $actor): array + { + $required = !empty($row['esign_required']); + $e = $required ? Db::name('prescription_esign')->where('prescription_id', (int) $row['id'])->find() : null; + $state = $required ? (string) ($row['esign_status'] ?? 'pending') : 'legacy'; + $voided = !empty($row['void_status']) || !empty($row['delete_time']); + if ($voided && $required) { + $state = 'voided'; + } + $sameApp = !$e || ($e['app_id'] === (string) Config::get('esign.app_id', '') + && $e['environment'] === (string) Config::get('esign.environment', 'sandbox')); + $canSign = self::enabled() && $required && !$voided && $sameApp + && (int) ($row['creator_id'] ?? 0) === $actor && empty($row['is_system_auto']); + $message = (string) ($e['error_message'] ?? ''); + if ($state === 'signing' && time() - (int) ($e['started_at'] ?? time()) > 180) { + // Never release an expired signing lease to another sign request. + $state = 'uncertain'; + $message = '签署结果待核实,请联系管理员核对签署流水,不要重复签署'; + } + if (!$sameApp) { + $message = '此处方属于其他签署环境或应用,请恢复对应配置后处理'; + } + if ($e && !$voided && !hash_equals((string) $e['snapshot_hash'], PrescriptionEsignPolicy::hash($row))) { + $state = 'uncertain'; + $message = '处方与冻结原文不一致,请管理员核实'; + $canSign = false; + } + if ($state === 'preparing') { + $canSign = $canSign && time() - (int) ($e['started_at'] ?? time()) > 90; + $state = 'authenticating'; + $message = '正在准备认证链接,请稍后刷新'; + } + $labels = ['legacy' => '历史手写签名', 'pending' => '待电子签署', 'authenticating' => '待医生核身', + 'signing' => '签署中', 'signed' => '已电子签署', 'failed' => '签署未完成', 'uncertain' => '签署结果待核实', 'voided' => '已作废']; + $out = [ + 'enabled' => self::enabled(), 'required' => $required, 'status' => $state, + 'status_label' => $labels[$state] ?? '待电子签署', + 'environment' => $e['environment'] ?? Config::get('esign.environment', 'sandbox'), + 'can_sign' => $canSign && in_array($state, ['pending', 'authenticating', 'failed'], true), + 'can_download' => !empty($e['signed_path']) && !empty($e['signed_at']), + 'message' => $message, 'signed_at' => (int) ($e['signed_at'] ?? 0), + ]; + if ($canSign && $state === 'authenticating' && !empty($e['auth_url'])) { + $out['auth_url'] = $e['auth_url']; + } + return $out; + } + + public static function assertSignedById(int $id, bool $forDispensing = false): void + { + // Audit/dispatch callers retain this lock through their state write. + $row = Db::name('tcm_prescription')->where('id', $id)->lock(true)->find(); + if (!$row) { + throw new DomainException('处方不存在'); + } + if (empty($row['esign_required'])) { + return; + } + $e = Db::name('prescription_esign')->where('prescription_id', $id)->find(); + PrescriptionEsignPolicy::assertSigned($row, $e ?: null, $forDispensing); + self::readPdf((string) $e['signed_path'], (string) $e['signed_hash']); + } + + public static function start(int $id, int $actor, array $adminInfo): array + { + $client = new EsignClient(); + $client->assertConfigured(); + $token = bin2hex(random_bytes(16)); + $work = Db::transaction(static function () use ($id, $actor, $token): ?array { + $row = self::lockSigner($id, $actor); + $e = Db::name('prescription_esign')->where('prescription_id', $id)->find(); + if ($e) { + if ((int) $e['doctor_id'] !== $actor) { + throw new DomainException('处方签署人与冻结记录不一致'); + } + self::assertEnvironment($e); + if (!hash_equals($e['snapshot_hash'], PrescriptionEsignPolicy::hash($row))) { + throw new DomainException('处方内容与签署原文不一致,请作废后重新开方'); + } + if (in_array($row['esign_status'], ['signed', 'signing', 'uncertain'], true)) { + return null; + } + if ($row['esign_status'] === 'authenticating' && $e['flow_id'] !== '') { + return null; + } + if ($row['esign_status'] === 'preparing' && time() - (int) $e['started_at'] < 90) { + return null; + } + } else { + $name = trim((string) Admin::where('id', $actor)->value('name')); + if ($name === '' || $name !== trim((string) $row['doctor_name'])) { + throw new DomainException('医师姓名与当前账号不一致,请修正处方后签署'); + } + $herbs = is_string($row['herbs']) ? json_decode($row['herbs'], true) : $row['herbs']; + if (empty($herbs) || trim((string) $row['clinical_diagnosis']) === '') { + throw new DomainException('请先补全处方药品和临床诊断'); + } + $snapshotHash = PrescriptionEsignPolicy::hash($row); + $pdf = PrescriptionPdf::render($row, (string) Config::get('esign.environment', 'sandbox')); + $path = $id . '-' . $snapshotHash . '/source.pdf'; + self::writePdf($path, $pdf); + $e = [ + 'prescription_id' => $id, 'doctor_id' => $actor, + 'environment' => Config::get('esign.environment', 'sandbox'), + 'app_id' => (string) Config::get('esign.app_id', ''), + 'snapshot_hash' => $snapshotHash, 'source_hash' => hash('sha256', $pdf), 'source_path' => $path, + 'create_time' => time(), 'update_time' => time(), + ]; + Db::name('prescription_esign')->insert($e); + } + Db::name('prescription_esign')->where('prescription_id', $id)->update([ + 'operation_token' => $token, 'started_at' => time(), 'error_message' => '', 'update_time' => time(), + 'flow_id' => '', 'auth_url' => '', + ]); + Db::name('tcm_prescription')->where('id', $id)->update(['esign_status' => 'preparing']); + return $row; + }); + if ($work === null) { + return self::status($id, $actor, $adminInfo); + } + try { + $account = self::account($actor); + if ($account && $account['doctor_name'] !== $work['doctor_name']) { + throw new DomainException('医师姓名已变更,请先由管理员核实签署账号'); + } + $auth = $client->startIdentity($work['doctor_name'], 'prescription-' . $id, $account['account_id'] ?? null); + self::finishOperation($id, $token, 'authenticating', [ + 'flow_id' => $auth['flow_id'], 'auth_url' => $auth['auth_url'], + // Records whether this particular authentication was bound to an existing SDK account. + 'account_id' => $account['account_id'] ?? '', + ]); + } catch (\Throwable $e) { + self::finishOperation($id, $token, 'failed', ['error_message' => self::safeError($e)]); + } + return self::status($id, $actor, $adminInfo); + } + + public static function complete(int $id, int $actor, array $adminInfo): array + { + $client = new EsignClient(); + $client->assertConfigured(); + $token = bin2hex(random_bytes(16)); + $work = Db::transaction(static function () use ($id, $actor, $token): ?array { + $row = self::lockSigner($id, $actor); + $e = Db::name('prescription_esign')->where('prescription_id', $id)->find(); + if (!$e) { + throw new DomainException('请先发起电子签署'); + } + if ((int) $e['doctor_id'] !== $actor) { + throw new DomainException('处方签署人与冻结记录不一致'); + } + self::assertEnvironment($e); + if (in_array($row['esign_status'], ['signed', 'signing', 'uncertain'], true)) { + return null; + } + if (!in_array($row['esign_status'], ['authenticating', 'failed'], true) || $e['flow_id'] === '') { + throw new DomainException('请先完成医生核身认证'); + } + if (!hash_equals($e['snapshot_hash'], PrescriptionEsignPolicy::hash($row))) { + throw new DomainException('处方内容已变化,请作废后重新开方'); + } + Db::name('prescription_esign')->where('prescription_id', $id)->update([ + 'operation_token' => $token, 'started_at' => time(), 'error_message' => '', 'update_time' => time(), + ]); + Db::name('tcm_prescription')->where('id', $id)->update(['esign_status' => 'signing']); + return ['row' => $row, 'evidence' => $e]; + }); + if ($work === null) { + return self::status($id, $actor, $adminInfo); + } + $attempted = false; + $signedReceived = false; + $accountId = ''; + try { + $row = $work['row']; + $e = $work['evidence']; + $identity = $client->identityDetail($e['flow_id']); + if (($identity['flowId'] ?? '') !== $e['flow_id'] + || (isset($identity['appId']) && (string) $identity['appId'] !== (string) $e['app_id'])) { + throw new DomainException('核身流程与本次处方签署不一致,请重新认证'); + } + if (($identity['status'] ?? '') !== 'SUCCESS') { + $failed = ($identity['status'] ?? '') === 'FAIL'; + self::finishOperation($id, $token, $failed ? 'failed' : 'authenticating', [ + 'error_message' => $failed ? '核身未通过,请重新发起认证' : '尚未完成核身,请在认证页面完成后重试', + ...($failed ? ['flow_id' => '', 'auth_url' => ''] : []), + ]); + return self::status($id, $actor, $adminInfo); + } + $person = $identity['indivInfo'] ?? []; + if (($identity['objectType'] ?? '') !== 'INDIVIDUAL' || ($person['name'] ?? '') !== $row['doctor_name'] + || ($person['certType'] ?? '') !== 'INDIVIDUAL_CH_IDCARD' || empty($person['certNo']) + || !preg_match('/^(?:\d{15}|\d{17}[\dXx])$/', (string) $person['certNo'])) { + throw new DomainException('核身信息与开方医生不一致或证件类型不支持'); + } + $client->checkWillingness($e['flow_id']); + $account = self::account($actor); + if ($account) { + if ($account['doctor_name'] !== $row['doctor_name'] + || empty($e['account_id']) || $account['account_id'] !== $e['account_id']) { + // A concurrent first-time binding must not turn an unbound flow into a bound one. + throw new DomainException('签署账号绑定已变化,请重新发起核身认证'); + } + $accountId = $account['account_id']; + } else { + if (!empty($e['account_id'])) { + throw new DomainException('签署账号绑定已变化,请联系管理员核实'); + } + $accountId = $client->createPerson($person['name'], $person['certNo'], $e['flow_id']); + try { + Db::name('doctor_esign_account')->insert([ + 'doctor_id' => $actor, 'environment' => $e['environment'], 'app_id' => $e['app_id'], + 'account_id' => $accountId, 'doctor_name' => $row['doctor_name'], 'create_time' => time(), + ]); + } catch (\Throwable $insertError) { + $existing = self::account($actor); + if (!$existing || $existing['account_id'] !== $accountId) { + throw new DomainException('签署账号绑定冲突,请联系管理员核实'); + } + } + } + unset($person, $identity); // Full identity document numbers are never persisted or logged. + self::finishOperation($id, $token, 'signing', ['account_id' => $accountId]); + $seal = $client->createSeal($accountId); + $pdf = self::readPdf($e['source_path'], $e['source_hash']); + // Recheck after authentication: a prescription may have been voided meanwhile. + Db::transaction(static function () use ($id, $actor, $token, $accountId): void { + $currentRow = self::lockSigner($id, $actor); + $current = Db::name('prescription_esign')->where('prescription_id', $id)->find(); + $boundAccount = self::account($actor); + if (!$current || !hash_equals($current['operation_token'], $token) + || $currentRow['esign_status'] !== 'signing' + || !hash_equals($current['snapshot_hash'], PrescriptionEsignPolicy::hash($currentRow)) + || !$boundAccount || $boundAccount['account_id'] !== $accountId) { + throw new DomainException('签署状态已变化,请刷新'); + } + }); + $attempted = true; + $signed = $client->signPdf($accountId, $e['flow_id'], $seal, $pdf, 'prescription-' . $id . '.pdf'); + $signedReceived = true; + // Save the supplier reference first: disk/archive failure must not lose a completed sign. + self::finishOperation($id, $token, 'signing', [ + 'sign_service_id' => $signed['sign_service_id'], 'account_id' => $accountId, + ]); + $path = $id . '-' . $e['snapshot_hash'] . '/signed.pdf'; + self::writePdf($path, $signed['pdf']); + // Persist the result before verification, so a verification outage cannot lose evidence. + $proof = ['signed_path' => $path, 'signed_hash' => hash('sha256', $signed['pdf']), + 'sign_service_id' => $signed['sign_service_id'], 'account_id' => $accountId]; + self::finishOperation($id, $token, 'signing', $proof); + $client->verifyPdf($signed['pdf']); + self::finishOperation($id, $token, 'signed', $proof + ['signed_at' => time(), 'error_message' => ''], $seal); + } catch (\Throwable $error) { + // A definite provider rejection before a result can retry with a fresh auth flow. + // Once bytes were signed, verification/storage failure must never re-enable signing. + $unknown = $attempted && ($signedReceived || !($error instanceof EsignProviderException) + || $error instanceof EsignOutcomeUnknownException); + $failure = ['error_message' => $unknown + ? '签署结果待核实,请管理员核对签署流水;不要重复签署' : self::safeError($error)]; + if ($error instanceof EsignOutcomeUnknownException && $error->signServiceId !== null) { + $failure['sign_service_id'] = $error->signServiceId; + $failure['account_id'] = $accountId; + } + if (!$unknown && ($attempted || $error instanceof DomainException + || ($error instanceof EsignProviderException && $error->providerCode === 'WILLINGNESS_INVALID'))) { + $failure += ['flow_id' => '', 'auth_url' => '']; + } + self::finishOperation($id, $token, $unknown ? 'uncertain' : 'failed', $failure); + } + return self::status($id, $actor, $adminInfo); + } + + public static function download(int $id, int $actor, array $adminInfo): array + { + $status = self::status($id, $actor, $adminInfo); + if (!$status['can_download']) { + throw new DomainException('已签原件尚不可下载'); + } + $e = Db::name('prescription_esign')->where('prescription_id', $id)->find(); + $pdf = self::readPdf($e['signed_path'], $e['signed_hash']); + return ['filename' => 'prescription-' . $id . '-signed.pdf', 'sha256' => $e['signed_hash'], 'content_base64' => base64_encode($pdf)]; + } + + /** Reverify an already archived result; never sends a second signature request. CLI only. */ + public static function recover(int $id): void + { + $work = Db::transaction(static function () use ($id): array { + $row = Db::name('tcm_prescription')->where('id', $id)->lock(true)->find(); + $e = Db::name('prescription_esign')->where('prescription_id', $id)->find(); + if (!$row || !$e || empty($e['signed_path']) || empty($e['sign_service_id']) || empty($e['account_id'])) { + throw new DomainException('本地没有可恢复的签署原件,请依据供应商签署流水人工核实;禁止自动重签'); + } + if (!hash_equals($e['snapshot_hash'], PrescriptionEsignPolicy::hash($row))) { + throw new DomainException('处方与冻结原文不一致,不能恢复签署状态'); + } + return ['row' => $row, 'evidence' => $e]; + }); + $e = $work['evidence']; + self::assertEnvironment($e); + $client = new EsignClient(); + $client->assertConfigured(); + $pdf = self::readPdf($e['signed_path'], $e['signed_hash']); + $verified = $client->verifyPdf($pdf); + $seal = ''; + foreach ($verified['signatures'] ?? [] as $signature) { + if (($signature['cert']['cn'] ?? '') === $work['row']['doctor_name'] + && is_string($signature['sealData'] ?? null) && $signature['sealData'] !== '' + && base64_decode($signature['sealData'], true) !== false) { + $seal = $signature['sealData']; + } + } + self::finishOperation($id, $e['operation_token'], 'signed', ['signed_at' => time(), 'error_message' => ''], $seal); + } + + private static function lockSigner(int $id, int $actor): array + { + if (!self::enabled()) { + throw new DomainException('电子签署尚未启用,请联系管理员'); + } + $row = Db::name('tcm_prescription')->where('id', $id)->lock(true)->find(); + if (!$row || empty($row['esign_required'])) { + throw new DomainException('此处方不属于电子签署流程'); + } + PrescriptionEsignPolicy::assertSigner($row, $actor); + if (trim((string) Admin::where('id', $actor)->value('name')) !== trim((string) $row['doctor_name'])) { + throw new DomainException('医师姓名已变更,请作废原处方后重新开方'); + } + return $row; + } + + private static function assertEnvironment(array $e): void + { + if ($e['environment'] !== Config::get('esign.environment', 'sandbox') || $e['app_id'] !== (string) Config::get('esign.app_id', '')) { + throw new DomainException('签署环境或应用与原处方不一致'); + } + } + + private static function account(int $actor): ?array + { + return Db::name('doctor_esign_account')->where('doctor_id', $actor) + ->where('environment', Config::get('esign.environment', 'sandbox')) + ->where('app_id', (string) Config::get('esign.app_id', ''))->find() ?: null; + } + + private static function finishOperation(int $id, string $token, string $state, array $data, string $seal = ''): void + { + Db::transaction(static function () use ($id, $token, $state, $data, $seal): void { + $row = Db::name('tcm_prescription')->where('id', $id)->lock(true)->find(); + $e = Db::name('prescription_esign')->where('prescription_id', $id)->find(); + if (!$row || !$e || !hash_equals($e['operation_token'], $token)) { + return; + } + if (!hash_equals($e['snapshot_hash'], PrescriptionEsignPolicy::hash($row))) { + $state = 'uncertain'; + $data['error_message'] = '处方与冻结原文不一致,请管理员核实'; + unset($data['signed_at']); + } + Db::name('prescription_esign')->where('prescription_id', $id)->update($data + ['update_time' => time()]); + $updates = ['esign_status' => (!empty($row['void_status']) || !empty($row['delete_time'])) ? 'voided' : $state]; + if ($state === 'signed' && $seal !== '') { + $updates['doctor_signature'] = 'data:image/png;base64,' . $seal; + } + Db::name('tcm_prescription')->where('id', $id)->update($updates); + }); + } + + private static function safeError(\Throwable $error): string + { + return $error instanceof DomainException || $error instanceof EsignProviderException + ? mb_substr($error->getMessage(), 0, 240) : '电子签署服务暂不可用,请稍后重试或联系管理员'; + } + + private static function filePath(string $relative): string + { + if (!preg_match('#^\d+-[a-f0-9]{64}/(?:source|signed)\.pdf$#D', $relative)) { + throw new DomainException('签署文件引用无效'); + } + return rtrim((string) Config::get('esign.storage_path', root_path() . 'storage/esign'), '/\\') . DIRECTORY_SEPARATOR . $relative; + } + + private static function writePdf(string $relative, string $bytes): void + { + if (!str_starts_with($bytes, '%PDF-') || strlen($bytes) > 20 * 1024 * 1024) { + throw new DomainException('签署服务返回的 PDF 无效或超出大小限制'); + } + $path = self::filePath($relative); + $dir = dirname($path); + if (!is_dir($dir) && !mkdir($dir, 0700, true) && !is_dir($dir)) { + throw new DomainException('签署文件存储不可用'); + } + $tmp = $path . '.' . bin2hex(random_bytes(8)) . '.tmp'; + if (file_put_contents($tmp, $bytes, LOCK_EX) !== strlen($bytes)) { + @unlink($tmp); + throw new DomainException('签署文件保存失败'); + } + @chmod($tmp, 0600); + if (!rename($tmp, $path)) { + @unlink($tmp); + throw new DomainException('签署文件归档失败'); + } + } + + private static function readPdf(string $relative, string $hash): string + { + $path = self::filePath($relative); + $bytes = is_file($path) && filesize($path) <= 20 * 1024 * 1024 ? file_get_contents($path) : false; + if ($bytes === false || !str_starts_with($bytes, '%PDF-') || !hash_equals($hash, hash('sha256', $bytes))) { + throw new DomainException('签署原件缺失或校验失败,请管理员恢复原件'); + } + return $bytes; + } +} diff --git a/server/app/common/service/esign/PrescriptionPdf.php b/server/app/common/service/esign/PrescriptionPdf.php new file mode 100644 index 000000000..512c2e0eb --- /dev/null +++ b/server/app/common/service/esign/PrescriptionPdf.php @@ -0,0 +1,125 @@ + 84) { + $lines[] = $current; + $current = ' '; + } + $current .= $char; + } + $lines[] = $current; + } + }; + $add('处方编号', $row['sn']); + $add('日期', $row['prescription_date']); + $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, 117, 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"; + } +} diff --git a/server/app/common/service/pharmacy/PharmacySubmissionClaimService.php b/server/app/common/service/pharmacy/PharmacySubmissionClaimService.php index e70ce883f..90c3f1790 100755 --- a/server/app/common/service/pharmacy/PharmacySubmissionClaimService.php +++ b/server/app/common/service/pharmacy/PharmacySubmissionClaimService.php @@ -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') { diff --git a/server/config/console.php b/server/config/console.php index 212a28efc..6edc17e09 100755 --- a/server/config/console.php +++ b/server/config/console.php @@ -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', diff --git a/server/config/esign.php b/server/config/esign.php new file mode 100644 index 000000000..6027d6f7f --- /dev/null +++ b/server/config/esign.php @@ -0,0 +1,14 @@ + env('esign.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'), + 'timeout' => env('esign.timeout', 60), + 'storage_path' => env('esign.storage_path', dirname(__DIR__) . '/storage/esign'), +]; diff --git a/server/database/migrations/2026_11_17_prescription_esign.sql b/server/database/migrations/2026_11_17_prescription_esign.sql new file mode 100644 index 000000000..2242c44a8 --- /dev/null +++ b/server/database/migrations/2026_11_17_prescription_esign.sql @@ -0,0 +1,42 @@ +-- 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, + `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, + `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, + `signed_at` int unsigned NOT NULL DEFAULT 0, + `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`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='冻结处方原文及签署证据,文件保存于私有存储'; + +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='核身后医生签署账号,不保存身份证号码'; diff --git a/server/tests/EsignClientTest.php b/server/tests/EsignClientTest.php new file mode 100644 index 000000000..2261797e1 --- /dev/null +++ b/server/tests/EsignClientTest.php @@ -0,0 +1,229 @@ +providerCode === $code, 'exception code ' . $code); + esignExpect($exception->getPrevious() === null, 'no sensitive previous exception'); + return $exception; + } + throw new RuntimeException('Expected exception: ' . $code); +} + +function esignConfig(array $overrides = []): array +{ + return array_replace([ + 'enabled' => true, 'environment' => 'sandbox', 'app_id' => 'test-app', 'app_secret' => 'test-secret', + 'sdk_url' => 'http://127.0.0.1:8091/paas-sdk-service', 'timeout' => 45, + ], $overrides); +} + +function esignResponse(array $data, int $status = 200): array +{ + return ['status' => $status, 'body' => json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)]; +} + +/** @return array */ +function esignMultipartParts(array $request): array +{ + $contentType = $request['headers']['Content-Type']; + esignExpect(str_starts_with($contentType, 'multipart/form-data; boundary='), 'multipart envelope'); + $boundary = substr($contentType, strlen('multipart/form-data; boundary=')); + $parts = []; + foreach (explode('--' . $boundary, $request['body']) as $part) { + if (!str_contains($part, "\r\n\r\n")) { + continue; + } + [$headers, $body] = explode("\r\n\r\n", ltrim($part, "\r\n"), 2); + preg_match('/name="([^"]+)"/', $headers, $matches); + $parts[$matches[1]] = ['headers' => $headers, 'body' => substr($body, 0, -2)]; + } + return $parts; +} + +$requests = []; +$responses = []; +$transport = static function (array $request) use (&$requests, &$responses): array { + $requests[] = $request; + if ($responses === []) { + throw new RuntimeException('No fake response'); + } + return array_shift($responses); +}; +$clock = static fn (): int => 1800000000000; +$client = new EsignClient(esignConfig(), $transport, $clock); +esignExpect($client->isEnabled() && $client->environment() === 'sandbox', 'configured environment'); +$client->assertConfigured(); + +foreach ([ + [['enabled' => 'false'], 'DISABLED'], + [['environment' => 'prod'], 'ENVIRONMENT_INVALID'], + [['app_secret' => ''], 'CREDENTIALS_MISSING'], + [['app_id' => "app\r\nInjected:yes"], 'CREDENTIALS_MISSING'], + [['timeout' => 0], 'TIMEOUT_INVALID'], + [['timeout' => 301], 'TIMEOUT_INVALID'], + [['sdk_url' => 'http://example.com/paas-sdk-service'], 'SDK_HTTP_REQUIRES_PRIVATE_HOST'], + [['sdk_url' => 'http://127.0.0.1:8091/paas-sdk-service?x=1'], 'SDK_URL_INVALID'], + [['sdk_url' => 'https://user:pass@example.com/paas-sdk-service'], 'SDK_URL_INVALID'], + [['sdk_url' => 'file:///tmp/paas-sdk-service'], 'SDK_URL_INVALID'], +] as [$config, $code]) { + esignThrows(fn () => (new EsignClient(esignConfig($config), $transport, $clock))->assertConfigured(), EsignProviderException::class, $code); +} +esignExpect($requests === [], 'configuration failures issue no request'); + +$responses[] = esignResponse(['errCode' => 0]); +$client->initialize(); +$init = json_decode($requests[0]['body'], true); +esignExpect($requests[0]['url'] === 'http://127.0.0.1:8091/paas-sdk-service/timevale/init', 'SDK init endpoint'); +esignExpect($init['projectConfig'] === [ + 'projectId' => 'test-app', 'projectSecret' => 'test-secret', + 'itsmApiUrl' => 'https://smlitsm.tsign.cn:8083/tgmonitor/rest/app!getAPIInfo2', +], 'sandbox initialization parameters'); +esignExpect($init['httpConfig'] === ['httpType' => 'HTTPS', 'retry' => 0], 'SDK internal retry disabled'); +esignExpect($init['signConfig']['algorithm'] === 'HMACSHA256', 'SDK algorithm'); + +$responses[] = esignResponse(['code' => 0, 'data' => ['flowId' => 'flow-7', 'shortLink' => 'https://smlt.esign.cn/identity7']]); +$identity = $client->startIdentity('张医生', 'rx-7', 'sdk-account-1'); +$request = $requests[count($requests) - 1]; +$body = json_decode($request['body'], true); +esignExpect($identity === ['flow_id' => 'flow-7', 'auth_url' => 'https://smlt.esign.cn/identity7'], 'identity result'); +esignExpect($request['url'] === 'https://smlopenapi.esign.cn/v2/identity/auth/web/indivAuthUrl', 'independent v2 identity API'); +esignExpect($body['indivInfo']['sdkAccountId'] === 'sdk-account-1' && !isset($body['sdkAccountId']), 'SDK account nested in indivInfo'); +esignExpect($body['configParams']['indivUneditableInfo'] === ['name', 'certType'], 'doctor name locked'); +// Fixed vectors independently calculated with Python hashlib/hmac; UTF-8 bytes must match exactly. +esignExpect($request['headers']['Content-MD5'] === 'M2hjK+7n9RSpPC8C09vWVQ==', 'POST content MD5 vector'); +esignExpect($request['headers']['X-Tsign-Open-Ca-Signature'] === 'i2dGU5UsRuMb6has/RBZN5BAsECYV4ziEDF17YHaL0g=', 'POST HMACSHA256 vector'); +esignExpect($request['headers']['X-Tsign-Open-Ca-Timestamp'] === '1800000000000', 'timestamp in milliseconds'); +esignExpect($request['headers']['X-Tsign-Open-Auth-Mode'] === 'Signature', 'signature auth mode'); + +$responses[] = esignResponse(['code' => 0, 'data' => ['flowId' => 'flow-7', 'status' => 'SUCCESS']]); +esignExpect($client->identityDetail('flow-7')['status'] === 'SUCCESS', 'identity official data returned'); +$request = $requests[count($requests) - 1]; +esignExpect($request['method'] === 'GET' && $request['body'] === '' && !isset($request['headers']['Content-MD5']), 'GET no body MD5'); +esignExpect($request['headers']['X-Tsign-Open-Ca-Signature'] === 'wPILAWFFD+SOKXrMxguRUqiG1Iwl+k/X9O9Fukf7hes=', 'GET HMACSHA256 vector'); + +$valid = ['errCode' => 0, 'status' => 1, 'remainingTimes' => 1, 'expireAt' => $clock() + 1000]; +$responses[] = esignResponse($valid); +$client->checkWillingness('flow-7'); +esignExpect(str_ends_with($requests[count($requests) - 1]['url'], '/timevale/auth/queryWillingnessValidity'), 'willingness endpoint'); +foreach ([['status' => 0], ['remainingTimes' => 0], ['expireAt' => $clock()], ['status' => '1'], ['expireAt' => 'not-a-date']] as $invalid) { + $responses[] = esignResponse(array_replace($valid, $invalid)); + esignThrows(fn () => $client->checkWillingness('flow-7'), EsignProviderException::class, 'WILLINGNESS_INVALID'); +} + +$responses[] = esignResponse(['errCode' => 0, 'accountId' => 'person-7']); +esignExpect($client->createPerson('张医生', 'TEST-IDENTITY', 'flow-7') === 'person-7', 'created SDK account'); +$request = $requests[count($requests) - 1]; +esignExpect(str_ends_with($request['url'], '/timevale/account/addPerson'), 'account SDK endpoint'); +esignExpect(json_decode($request['body'], true) === ['name' => '张医生', 'idNo' => 'TEST-IDENTITY', 'idNoType' => 'MAINLAND', 'identityAuthId' => 'flow-7'], 'identity bound to SDK account'); + +$responses[] = esignResponse(['errCode' => 0, 'sealData' => base64_encode('seal-image')]); +esignExpect($client->createSeal('person-7') === base64_encode('seal-image'), 'seal result'); +$sealBody = json_decode($requests[count($requests) - 1]['body'], true); +esignExpect($sealBody === ['accountId' => 'person-7', 'type' => 'BORDERLESS', 'color' => 'BLACK', 'stampRule' => 'SEAL_NONE'], 'seal from account identity'); + +$pdf = "%PDF-1.7\n\x00\x01binary-pdf\r\n%%EOF"; +$signedPdf = "%PDF-1.7\nsigned\x00binary\n%%EOF"; +$responses[] = esignResponse(['errCode' => 0, 'signServiceId' => 'service-7', 'stream' => base64_encode($signedPdf)]); +esignExpect($client->signPdf('person-7', 'flow-7', base64_encode('seal-image'), $pdf, 'rx-7.pdf') === ['sign_service_id' => 'service-7', 'pdf' => $signedPdf], 'decoded signed PDF bytes'); +$request = $requests[count($requests) - 1]; +esignExpect(str_ends_with($request['url'], '/timevale/user/sign/personSign'), 'SDK person sign endpoint'); +$parts = esignMultipartParts($request); +esignExpect(array_keys($parts) === ['personSignParam', 'streamFile'], 'multipart field names'); +esignExpect(str_contains($parts['personSignParam']['headers'], 'Content-Type: application/json; charset=UTF-8'), 'JSON part media type'); +esignExpect(str_contains($parts['streamFile']['headers'], 'Content-Type: application/octet-stream'), 'file part media type'); +esignExpect($parts['streamFile']['body'] === $pdf, 'multipart preserves arbitrary binary bytes'); +$parameters = json_decode($parts['personSignParam']['body'], true); +esignExpect($parameters['fileBean'] === ['fileName' => 'rx-7.pdf'] && !isset($parameters['fileBean']['dstPdfFile']), 'stream response requested'); +esignExpect($parameters['signType'] === 'Single' && $parameters['posBeans'] === [['posPage' => '1', 'posX' => 420, 'posY' => 70, 'width' => 100]], 'fixed prescription signature location'); +esignExpect($parameters['willingnessId'] === 'flow-7' && $parameters['accountId'] === 'person-7', 'signature identity binding'); + +$signatures = [['signature' => ['validate' => true], 'cert' => ['cn' => '张医生']], ['signature' => ['validate' => true]]]; +$responses[] = esignResponse(['errCode' => 0, 'signatures' => $signatures]); +esignExpect($client->verifyPdf($signedPdf) === ['signatures' => $signatures], 'all signatures verified'); +$parts = esignMultipartParts($requests[count($requests) - 1]); +esignExpect(isset($parts['verifyPdfParam']) && $parts['streamFile']['body'] === $signedPdf, 'verify multipart'); +foreach ([[], [['signature' => ['validate' => true]], ['signature' => ['validate' => false]]], [['signature' => ['validate' => 1]]], [['cert' => []]]] as $invalid) { + $responses[] = esignResponse(['errCode' => 0, 'signatures' => $invalid]); + esignThrows(fn () => $client->verifyPdf($signedPdf), EsignProviderException::class, $invalid === [] ? 'NO_SIGNATURES' : 'SIGNATURE_INVALID'); +} + +foreach ([ + [['status' => 200, 'body' => ''], 'EMPTY_RESPONSE'], + [['status' => 200, 'body' => 'secret identity data'], 'INVALID_JSON'], + [esignResponse(['msg' => 'private identity']), 'RESPONSE_INVALID'], + [esignResponse(['errCode' => 42, 'msg' => 'private name/id/secret']), 'PROVIDER_42'], + [['status' => 302, 'body' => 'Location: https://attacker.invalid'], 'HTTP_302'], + [['status' => 0, 'body' => '', 'errno' => 28], 'TIMEOUT'], +] as [$response, $code]) { + $responses[] = $response; + $before = count($requests); + $exception = esignThrows(fn () => $client->createSeal('person-7'), EsignProviderException::class, $code); + esignExpect(count($requests) === $before + 1, 'no retry ' . $code); + esignExpect(!str_contains($exception->getMessage(), 'private') && !str_contains($exception->getMessage(), 'secret') && !str_contains($exception->getMessage(), 'attacker'), 'sanitized error ' . $code); +} + +foreach ([ + [['status' => 0, 'body' => '', 'errno' => 28], 'TIMEOUT'], + [['status' => 200, 'body' => ''], 'EMPTY_RESPONSE'], + [['status' => 502, 'body' => 'private server exception'], 'HTTP_502'], + [esignResponse(['errCode' => 0, 'signServiceId' => 'already-signed']), 'SIGNED_FILE_UNAVAILABLE'], +] as [$response, $code]) { + $responses[] = $response; + $before = count($requests); + $exception = esignThrows(fn () => $client->signPdf('person-7', 'flow-7', base64_encode('seal'), $pdf, 'rx.pdf'), EsignOutcomeUnknownException::class, $code); + esignExpect(count($requests) === $before + 1, 'unknown signing outcome is never retried'); + if ($code === 'SIGNED_FILE_UNAVAILABLE') { + esignExpect($exception->signServiceId === 'already-signed', 'known sign reference retained'); + } +} +$responses[] = esignResponse(['errCode' => 55, 'msg' => 'secret rejected identity']); +esignThrows(fn () => $client->signPdf('person-7', 'flow-7', base64_encode('seal'), $pdf, 'rx.pdf'), EsignProviderException::class, 'PROVIDER_55'); +$throwing = new EsignClient(esignConfig(), static function (): array { throw new RuntimeException('https://secret:password/private'); }, $clock); +esignThrows(fn () => $throwing->createSeal('person-7'), EsignProviderException::class, 'TRANSPORT_ERROR'); +esignThrows(fn () => $throwing->signPdf('person-7', 'flow-7', base64_encode('seal'), $pdf, 'rx.pdf'), EsignOutcomeUnknownException::class, 'TRANSPORT_ERROR'); + +$responses[] = esignResponse(['code' => 0, 'data' => ['flowId' => '7', 'shortLink' => 'https://attacker.invalid/identity']]); +esignThrows(fn () => $client->startIdentity('医生', 'rx'), EsignProviderException::class, 'AUTH_URL_INVALID'); +$responses[] = esignResponse(['code' => 0, 'data' => ['flowId' => '7', 'shortLink' => 'https://t.esign.cn/identity']]); +esignThrows(fn () => $client->startIdentity('医生', 'rx'), EsignProviderException::class, 'AUTH_URL_INVALID'); +$responses[] = esignResponse(['code' => 0, 'data' => ['flowId' => '7', 'url' => 'https://smlfront.esign.cn:8890/identity/login']]); +esignExpect($client->startIdentity('医生', 'rx')['auth_url'] === 'https://smlfront.esign.cn:8890/identity/login', 'official sandbox long URL port'); +foreach (['https://smlfront.esign.cn:444/x', 'https://smlt.esign.cn:8890/x', 'https://smlt.esign.cn/a\\b'] as $invalidUrl) { + $responses[] = esignResponse(['code' => 0, 'data' => ['flowId' => '7', 'url' => $invalidUrl]]); + esignThrows(fn () => $client->startIdentity('医生', 'rx'), EsignProviderException::class, 'AUTH_URL_INVALID'); +} + +$production = new EsignClient(esignConfig(['environment' => 'production']), $transport, $clock); +$responses[] = esignResponse(['errCode' => 0]); +$production->initialize(); +$init = json_decode($requests[count($requests) - 1]['body'], true); +esignExpect($init['projectConfig']['itsmApiUrl'] === 'https://sdkapi.esign.cn/tgmonitor/rest/app!getAPIInfo2', 'production init endpoint'); +$responses[] = esignResponse(['code' => 0, 'data' => ['flowId' => '7', 'shortLink' => '', 'url' => 'https://idverify.esign.cn/identity']]); +$production->startIdentity('医生', 'rx'); +esignExpect(str_starts_with($requests[count($requests) - 1]['url'], 'https://openapi.esign.cn/v2/identity/'), 'production identity endpoint'); + +esignExpect($responses === [], 'all expected transport responses consumed'); +echo 'EsignClient: ' . $checks . " checks passed (offline)\n"; diff --git a/server/tests/PrescriptionEsignFlowTest.php b/server/tests/PrescriptionEsignFlowTest.php new file mode 100644 index 000000000..92bc24155 --- /dev/null +++ b/server/tests/PrescriptionEsignFlowTest.php @@ -0,0 +1,336 @@ + 'flow-' . self::$starts, 'auth_url' => 'https://smlt.esign.cn/test']; + } + public function identityDetail(string $id): array + { + return ['flowId' => self::$identityFlowId ?? $id, 'appId' => 'fixture', 'status' => self::$identityStatus, 'objectType' => 'INDIVIDUAL', + 'indivInfo' => ['name' => self::$identityName, 'certNo' => '110101199001011234', 'certType' => 'INDIVIDUAL_CH_IDCARD']]; + } + public function checkWillingness(string $id): void + { + if (self::$expiredWillingness) { throw new EsignProviderException('checkWillingness', 'WILLINGNESS_INVALID'); } + } + public function createPerson(string $name, string $idNo, string $flow): string { return 'account-test'; } + public function createSeal(string $id): string + { + if (self::$duringSeal) { (self::$duringSeal)(); } + return base64_encode('test-seal'); + } + public function signPdf(string $account, string $flow, string $seal, string $pdf, string $name): array + { + self::$signs++; + if (self::$duringSign) { (self::$duringSign)(); } + if (self::$signRejection !== null) { throw new EsignProviderException('signPdf', self::$signRejection); } + if (self::$signFailure) { throw new EsignOutcomeUnknownException('TIMEOUT', self::$unknownServiceId); } + return ['pdf' => $pdf . "\n% provider signed fixture\n", 'sign_service_id' => 'sign-' . self::$signs]; + } + public function verifyPdf(string $pdf): array + { + if (self::$verifyFailure) { throw new \RuntimeException('verify unavailable'); } + if (self::$verifyRejection !== null) { throw new EsignProviderException('verifyPdf', self::$verifyRejection); } + return ['signatures' => [['signature' => ['validate' => true], 'cert' => ['cn' => '测试医师'], 'sealData' => base64_encode('test-seal')]]]; + } + } +} +namespace { + require dirname(__DIR__) . '/vendor/autoload.php'; + require dirname(__DIR__) . '/vendor/topthink/framework/src/helper.php'; + use app\common\service\esign\PrescriptionEsignService as Service; + use app\common\service\esign\PrescriptionEsignPolicy as Policy; + use app\common\service\esign\PrescriptionPdf; + use app\common\service\esign\EsignClient as Fake; + use think\facade\Db; + use think\Container; + + $app = new think\App(); // Never initialize or load .env / real DB credentials. + $dir = sys_get_temp_dir() . '/zyt-esign-test-' . bin2hex(random_bytes(8)); + mkdir($dir, 0700); + $manager = new think\DbManager(); + $manager->setConfig(['default' => 'test', 'connections' => ['test' => [ + 'type' => 'sqlite', 'database' => $dir . '/fixture.sqlite', 'prefix' => 'zyt_', 'fields_strict' => true, + ]]]); + Container::getInstance()->instance('think\DbManager', $manager); + $config = new think\Config(); + $settings = ['enabled' => true, 'environment' => 'sandbox', 'app_id' => 'fixture', 'storage_path' => $dir . '/pdf']; + $config->set($settings, 'esign'); + Container::getInstance()->instance('config', $config); + $root = ['root' => 1, 'admin_id' => 1, 'name' => '测试医师']; + $checks = 0; + $assert = static function (bool $ok, string $message) use (&$checks): void { + if (!$ok) { throw new \RuntimeException($message); } + $checks++; + }; + $throws = static function (callable $fn, string $message) use ($assert): void { + try { $fn(); } catch (\DomainException $e) { $assert(true, $message); return; } + $assert(false, $message); + }; + try { + $fields = array_unique(array_merge(Policy::CONTENT_FIELDS, ['esign_required', 'esign_status', 'is_system_auto', 'void_status', 'delete_time', 'doctor_signature', 'update_time'])); + $columns = array_map(static fn ($field) => $field === 'id' ? 'id INTEGER PRIMARY KEY' : $field . ' TEXT', $fields); + Db::execute('CREATE TABLE zyt_tcm_prescription (' . implode(',', $columns) . ')'); + Db::execute('CREATE TABLE zyt_admin (id INTEGER PRIMARY KEY,name TEXT,delete_time INTEGER)'); + Db::name('admin')->insert(['id' => 1, 'name' => '测试医师']); + $sql = file_get_contents(dirname(__DIR__) . '/database/migrations/2026_11_17_prescription_esign.sql'); + preg_match_all('/CREATE TABLE IF NOT EXISTS `(zyt_\w+)` \((.*?)\) ENGINE/s', $sql, $matches, PREG_SET_ORDER); + foreach ($matches as $match) { + $defs = []; + foreach (explode("\n", $match[2]) as $line) { + if (preg_match('/^\s*`(\w+)`\s+(.+?)(?:,)?$/', $line, $m)) { + $type = preg_match('/\bint\b/', $m[2]) ? 'INTEGER' : 'TEXT'; + $def = '`' . $m[1] . '` ' . $type; + if ($m[1] === 'id' || ($match[1] === 'zyt_prescription_esign' && $m[1] === 'prescription_id')) { $def .= ' PRIMARY KEY'; } + if (preg_match("/DEFAULT ('[^']*'|\d+)/", $m[2], $d)) { $def .= ' DEFAULT ' . $d[1]; } + $defs[] = $def; + } + } + Db::execute('CREATE TABLE ' . $match[1] . ' (' . implode(',', $defs) . ')'); + } + Db::execute('CREATE UNIQUE INDEX uk_doctor ON zyt_doctor_esign_account(doctor_id,environment,app_id)'); + $new = static function (int $id): void { + Db::name('tcm_prescription')->insert([ + 'id' => $id, 'sn' => 'RX-TEST-' . $id, 'creator_id' => 1, 'doctor_name' => '测试医师', + 'patient_name' => '虚构测试患者', 'gender' => 1, 'age' => 30, 'phone' => '13800000000', + 'clinical_diagnosis' => '仅用于软件测试', 'herbs' => json_encode([['name' => '测试药材', 'dosage' => 10, 'unit' => 'g']], JSON_UNESCAPED_UNICODE), + 'prescription_date' => '2026-11-17', 'esign_required' => 1, 'esign_status' => 'pending', 'void_status' => 0, + ]); + }; + $new(1); + $throws(fn () => Service::start(1, 2, $root), 'non-creator cannot start even with root role'); + $throws(fn () => Service::assertSignedById(1), 'pending prescription cannot pass audit'); + $a = Service::start(1, 1, $root); + $assert($a['status'] === 'authenticating' && isset($a['auth_url']), 'start returns authentication URL'); + Service::start(1, 1, $root); + $assert(Fake::$starts === 1, 'repeat start must reuse flow'); + $throws(fn () => Policy::assertMutable(Db::name('tcm_prescription')->find(1)), 'auth freezes content'); + Fake::$identityStatus = 'ING'; + $assert(Service::complete(1, 1, $root)['status'] === 'authenticating' && Fake::$signs === 0, 'not authenticated cannot sign'); + Fake::$identityStatus = 'SUCCESS'; + Fake::$identityName = '其他医师'; + $assert(Service::complete(1, 1, $root)['status'] === 'failed' && Fake::$signs === 0, 'wrong identity cannot sign'); + Fake::$identityName = '测试医师'; + Service::start(1, 1, $root); // A rejected identity must be replaced, never silently reused. + Fake::$duringSign = static function () use ($assert, $root): void { + $assert(Service::complete(1, 1, $root)['status'] === 'signing', 'concurrent complete must not repeat sign'); + }; + $done = Service::complete(1, 1, $root); + Fake::$duringSign = null; + $assert($done['status'] === 'signed' && $done['can_download'], 'verified sign archived'); + Service::complete(1, 1, $root); + $assert(Fake::$signs === 1, 'signed replay returns same result'); + $download = Service::download(1, 1, $root); + $bytes = base64_decode($download['content_base64'], true); + $assert(hash('sha256', $bytes) === $download['sha256'] && str_contains($bytes, 'provider signed fixture'), 'download original bytes and digest'); + Service::assertSignedById(1); + $throws(fn () => Service::assertSignedById(1, true), 'sandbox cannot dispense'); + $throws(fn () => Policy::assertMutable(Db::name('tcm_prescription')->find(1)), 'signed content immutable'); + Db::name('tcm_prescription')->where('id', 1)->update(['clinical_diagnosis' => 'changed']); + $throws(fn () => Service::assertSignedById(1), 'out-of-band content mutation invalidates approval'); + $assert(Service::status(1, 1, $root)['status'] === 'uncertain', 'changed content is not displayed as signed'); + + $new(2); Service::start(2, 1, $root); + Fake::$verifyFailure = true; + $assert(Service::complete(2, 1, $root)['status'] === 'uncertain', 'verification outage preserves unknown state'); + $before = Fake::$signs; + Service::start(2, 1, $root); Service::complete(2, 1, $root); + $assert(Fake::$signs === $before, 'unknown outcome never automatically resigns'); + Fake::$verifyFailure = false; + Service::recover(2); + $assert(Service::status(2, 1, $root)['status'] === 'signed' && Fake::$signs === $before, 'recover re-verifies original without signing'); + $assert(Db::name('tcm_prescription')->where('id', 2)->value('doctor_signature') === 'data:image/png;base64,' . base64_encode('test-seal'), 'recovery restores supplier-verified display seal'); + + $new(3); Service::start(3, 1, $root); + Fake::$duringSign = static fn () => Db::name('tcm_prescription')->where('id', 3)->update(['void_status' => 1]); + $assert(Service::complete(3, 1, $root)['status'] === 'voided', 'late signature never restores voided prescription'); + Fake::$duringSign = null; + $throws(fn () => Service::assertSignedById(3), 'voided prescription cannot pass'); + + $new(4); Service::start(4, 1, $root); + Fake::$signFailure = true; + $assert(Service::complete(4, 1, $root)['status'] === 'uncertain', 'sign timeout remains uncertain'); + Fake::$signFailure = false; + $throws(fn () => Service::recover(4), 'missing signed file cannot be invented'); + + $new(6); Service::start(6, 1, $root); + Fake::$signFailure = true; Fake::$unknownServiceId = 'supplier-uncertain-6'; + $assert(Service::complete(6, 1, $root)['status'] === 'uncertain', 'typed timeout outcome remains uncertain'); + Fake::$signFailure = false; Fake::$unknownServiceId = null; + $evidence = Db::name('prescription_esign')->where('prescription_id', 6)->find(); + $assert($evidence['sign_service_id'] === 'supplier-uncertain-6' && $evidence['account_id'] === 'account-test', 'unknown exception supplier reference is retained'); + $before = Fake::$signs; + Service::start(6, 1, $root); Service::complete(6, 1, $root); + $assert(Fake::$signs === $before, 'typed unknown cannot automatically resign'); + + $new(7); Service::start(7, 1, $root); + Fake::$signRejection = 'PROVIDER_50001'; + $rejected = Service::complete(7, 1, $root); + Fake::$signRejection = null; + $assert($rejected['status'] === 'failed' && $rejected['can_sign'], 'explicit supplier rejection is retryable'); + $assert(str_contains($rejected['message'], 'PROVIDER_50001'), 'safe supplier code is retained'); + $assert(Db::name('prescription_esign')->where('prescription_id', 7)->value('flow_id') === '', 'explicit rejection requires fresh authentication'); + $before = Fake::$signs; + $throws(fn () => Service::complete(7, 1, $root), 'cannot reuse rejected sign authentication'); + Service::start(7, 1, $root); + $assert(Service::complete(7, 1, $root)['status'] === 'signed' && Fake::$signs === $before + 1, 'new auth can complete definite rejection retry'); + + $new(8); Fake::$startFailure = true; + $assert(Service::start(8, 1, $root)['status'] === 'failed', 'identity link outage records failed preparation'); + Fake::$startFailure = false; + $evidence = Db::name('prescription_esign')->where('prescription_id', 8)->find(); + $assert($evidence['flow_id'] === '' && $evidence['auth_url'] === '', 'failed preparation has no stale identity URL'); + $assert(Service::start(8, 1, $root)['status'] === 'authenticating', 'identity preparation can safely retry'); + + $new(9); Service::start(9, 1, $root); $before = Fake::$signs; + Fake::$expiredWillingness = true; + $assert(Service::complete(9, 1, $root)['status'] === 'failed' && Fake::$signs === $before, 'expired willingness never dispatches sign'); + Fake::$expiredWillingness = false; + $assert(Db::name('prescription_esign')->where('prescription_id', 9)->value('flow_id') === '', 'expired willingness requires new auth flow'); + + $new(10); Service::start(10, 1, $root); $before = Fake::$signs; + Fake::$identityFlowId = 'foreign-flow'; + $assert(Service::complete(10, 1, $root)['status'] === 'failed' && Fake::$signs === $before, 'identity response must echo bound flow'); + Fake::$identityFlowId = null; + + $new(11); Service::start(11, 1, $root); $before = Fake::$signs; + Db::name('doctor_esign_account')->where('doctor_id', 1)->update(['account_id' => 'replacement-account']); + $assert(Service::complete(11, 1, $root)['status'] === 'failed' && Fake::$signs === $before, 'account replacement cannot reuse auth for old account'); + Db::name('doctor_esign_account')->where('doctor_id', 1)->update(['account_id' => 'account-test']); + + Db::name('doctor_esign_account')->where('doctor_id', 1)->delete(); + $new(12); Service::start(12, 1, $root); $before = Fake::$signs; + Db::name('doctor_esign_account')->insert(['doctor_id' => 1, 'environment' => 'sandbox', 'app_id' => 'fixture', + 'account_id' => 'account-test', 'doctor_name' => '测试医师', 'create_time' => time()]); + $assert(Service::complete(12, 1, $root)['status'] === 'failed' && Fake::$signs === $before, 'concurrent first binding cannot turn unbound auth into bound auth'); + Service::start(12, 1, $root); + $assert(Service::complete(12, 1, $root)['status'] === 'signed', 'new auth binds the now existing account'); + + $new(13); Service::start(13, 1, $root); + Db::name('tcm_prescription')->where('id', 13)->update(['esign_status' => 'signing']); + Db::name('prescription_esign')->where('prescription_id', 13)->update(['started_at' => time() - 500]); + $before = Fake::$signs; + $stale = Service::status(13, 1, $root); + Service::start(13, 1, $root); Service::complete(13, 1, $root); + $assert($stale['status'] === 'uncertain' && !$stale['can_sign'] && Fake::$signs === $before, 'stale signing lease cannot trigger another sign'); + + $new(14); Service::start(14, 1, $root); $before = Fake::$signs; + Fake::$duringSeal = static fn () => Db::name('tcm_prescription')->where('id', 14)->update(['usage_notes' => 'out-of-band mutation']); + $assert(Service::complete(14, 1, $root)['status'] === 'uncertain' && Fake::$signs === $before, 'second fingerprint check prevents signing mutated prescription'); + Fake::$duringSeal = null; + + $new(15); Service::start(15, 1, $root); $before = Fake::$signs; + Fake::$duringSeal = static fn () => Db::name('tcm_prescription')->where('id', 15)->update(['void_status' => 1]); + $assert(Service::complete(15, 1, $root)['status'] === 'voided' && Fake::$signs === $before, 'void during provider preparation prevents dispatch'); + Fake::$duringSeal = null; + + $new(16); Service::start(16, 1, $root); Fake::$verifyFailure = true; + Service::complete(16, 1, $root); Fake::$verifyFailure = false; + Db::name('tcm_prescription')->where('id', 16)->update(['usage_notes' => 'modified after signing']); + $before = Fake::$signs; + $throws(fn () => Service::recover(16), 'recovery cannot approve a changed snapshot'); + $assert(Fake::$signs === $before && Service::status(16, 1, $root)['status'] === 'uncertain', 'changed recovery remains quarantined without signing'); + + $new(17); Service::start(17, 1, $root); + $evidence = Db::name('prescription_esign')->where('prescription_id', 17)->find(); + $blockedPath = $dir . '/pdf/' . dirname($evidence['source_path']) . '/signed.pdf'; + mkdir($blockedPath); + set_error_handler(static fn (): bool => true); // Expected rename failure, no sensitive error output. + try { $archiveFailure = Service::complete(17, 1, $root); } finally { restore_error_handler(); rmdir($blockedPath); } + $evidence = Db::name('prescription_esign')->where('prescription_id', 17)->find(); + $assert($archiveFailure['status'] === 'uncertain' && $evidence['sign_service_id'] !== '' && $evidence['signed_path'] === '', 'archive failure preserves successful supplier reference'); + $throws(fn () => Service::recover(17), 'archive failure requires manual retrieval, never resign'); + + $new(18); Service::start(18, 1, $root); $before = Fake::$signs; + $evidence = Db::name('prescription_esign')->where('prescription_id', 18)->find(); + file_put_contents($dir . '/pdf/' . $evidence['source_path'], '%PDF-1.7 tampered'); + $assert(Service::complete(18, 1, $root)['status'] === 'failed' && Fake::$signs === $before, 'changed source file cannot be sent to provider'); + + $new(19); Service::start(19, 1, $root); $before = Fake::$signs; + Db::name('admin')->where('id', 1)->update(['name' => '已改名医师']); + $throws(fn () => Service::complete(19, 1, $root), 'doctor account rename invalidates pending identity binding'); + Db::name('admin')->where('id', 1)->update(['name' => '测试医师']); + $assert(Fake::$signs === $before, 'renamed doctor does not send sign'); + + $new(20); Service::start(20, 1, $root); + Fake::$verifyRejection = 'PROVIDER_70002'; + $invalidSigned = Service::complete(20, 1, $root); + Fake::$verifyRejection = null; + $assert($invalidSigned['status'] === 'uncertain' && !$invalidSigned['can_sign'], 'definite verification failure after signature is never a retryable sign failure'); + + $proof = Db::name('prescription_esign')->where('prescription_id', 2)->find(); + $proof['doctor_id'] = 99; + $throws(fn () => Policy::assertSigned(Db::name('tcm_prescription')->find(2), $proof), 'proof author must match prescription creator'); + $assert(!str_contains(json_encode(Db::name('prescription_esign')->select()->toArray()), '110101199001011234') + && !str_contains(json_encode(Db::name('doctor_esign_account')->select()->toArray()), '110101199001011234'), 'identity document number never persisted'); + $assert(Fake::$initializes === 0, 'business operations and recovery never reinitialize shared SDK'); + + $new(5); Service::start(5, 1, $root); + $config->set(array_merge($settings, ['environment' => 'production']), 'esign'); + $throws(fn () => Service::complete(5, 1, $root), 'environment switch cannot reuse sandbox identity'); + $config->set(array_merge($settings, ['enabled' => false]), 'esign'); + $throws(fn () => Service::start(5, 1, $root), 'disabled config blocks signing'); + $throws(fn () => Service::assertSignedById(5), 'feature off must not bypass existing signature requirement'); + $legacy = Db::name('tcm_prescription')->find(5); $legacy['esign_required'] = 0; + Policy::assertSigned($legacy, null); + $assert(true, 'historical handwritten record remains compatible'); + + $sample = Db::name('tcm_prescription')->find(2); + $decimalRow = array_replace($sample, ['dosage_amount' => '10.0000', 'amount' => '20.00']); + $floatRow = array_replace($sample, ['dosage_amount' => 10.0, 'amount' => 20]); + $assert(Policy::hash($decimalRow) === Policy::hash($floatRow), 'raw DECIMAL and ORM float hashes agree'); + $assert(Policy::hash(Policy::snapshot($decimalRow)) === Policy::hash($decimalRow), 'snapshot hashing is idempotent'); + $pdf = PrescriptionPdf::render($sample, 'sandbox'); + $assert($pdf === PrescriptionPdf::render($sample, 'sandbox'), 'deterministic PDF'); + $manyHerbs = []; + for ($i = 1; $i <= 65; ++$i) { $manyHerbs[] = ['name' => '虚构药品' . $i, 'dosage' => $i, 'unit' => 'g']; } + $largePdf = PrescriptionPdf::render(array_replace($sample, ['herbs' => $manyHerbs, 'amount' => '18.50']), 'sandbox'); + $assert(preg_match('#/Type /Pages /Kids \[.*?\] /Count ([2-9]\d*)#', $largePdf) === 1, 'long prescription paginates'); + $assert(str_contains($largePdf, bin2hex(mb_convert_encoding('药品 65:', 'UTF-16BE', 'UTF-8'))), 'last drug is not truncated'); + $assert(str_contains($largePdf, bin2hex(mb_convert_encoding('金额(元):18.5', 'UTF-16BE', 'UTF-8'))), 'amount is present in signed document'); + file_put_contents(dirname(__DIR__, 2) . '/artifacts/esign-prescription-test.pdf', $pdf); + echo "Prescription eSign flow: $checks checks passed (isolated SQLite, fake provider)\n"; + } finally { + $manager->connect()->close(); + foreach (glob($dir . '/pdf/*/*.pdf') ?: [] as $file) { unlink($file); } + foreach (glob($dir . '/pdf/*', GLOB_ONLYDIR) ?: [] as $folder) { rmdir($folder); } + if (is_dir($dir . '/pdf')) { rmdir($dir . '/pdf'); } + if (is_file($dir . '/fixture.sqlite')) { unlink($dir . '/fixture.sqlite'); } + rmdir($dir); + } +} diff --git a/server/tests/PrescriptionEsignMysqlTest.php b/server/tests/PrescriptionEsignMysqlTest.php new file mode 100644 index 000000000..372b46c52 --- /dev/null +++ b/server/tests/PrescriptionEsignMysqlTest.php @@ -0,0 +1,126 @@ + PDO::ERRMODE_EXCEPTION]); +$pdo->exec("CREATE DATABASE `$database` CHARACTER SET utf8mb4"); +$pdo->exec("USE `$database`"); +$app = new think\App(); +$manager = new think\DbManager(); +$manager->setConfig(['default' => 'test', 'connections' => ['test' => [ + 'type' => 'mysql', 'hostname' => '127.0.0.1', 'hostport' => $port, 'database' => $database, + 'username' => 'root', 'password' => '', 'prefix' => 'zyt_', 'charset' => 'utf8mb4', 'fields_strict' => true, +]]]); +Container::getInstance()->instance('think\DbManager', $manager); +$config = new think\Config(); +$config->set(['enabled' => true, 'environment' => 'sandbox', 'app_id' => 'fixture'], 'esign'); +Container::getInstance()->instance('config', $config); +$root = ['root' => 1, 'admin_id' => 1, 'name' => '测试审核员']; +$checks = 0; +$pdfPath = null; +$expect = static function (bool $ok, string $message) use (&$checks): void { + if (!$ok) { throw new RuntimeException($message); } + $checks++; +}; +try { + $pdo->exec('CREATE TABLE zyt_tcm_prescription ( + id INT UNSIGNED PRIMARY KEY,creator_id INT,doctor_name VARCHAR(100),patient_name VARCHAR(100),phone VARCHAR(30),gender INT, + audit_status INT DEFAULT 0,void_status INT DEFAULT 0,delete_time INT NULL,update_time INT DEFAULT 0, + is_system_auto INT DEFAULT 0,herbs TEXT,clinical_diagnosis TEXT + ) ENGINE=InnoDB'); + $pdo->exec("INSERT INTO zyt_tcm_prescription (id,creator_id,doctor_name) VALUES (1,1,'测试医师')"); + $migration = file_get_contents(dirname(__DIR__) . '/database/migrations/2026_11_17_prescription_esign.sql'); + $pdo->exec($migration); + $pdo->exec($migration); + $row = Db::name('tcm_prescription')->find(1); + $expect((int) $row['esign_required'] === 0 && $row['esign_status'] === 'legacy', 'migration preserves historical rows and is repeatable'); + $pdo->exec("INSERT INTO zyt_tcm_prescription (id,creator_id,doctor_name,esign_required,esign_status) VALUES (2,1,'测试医师',1,'pending')"); + $pdo->exec(file_get_contents(dirname(__DIR__) . '/database/migrations/2026_04_07_create_tcm_prescription_order.sql')); + $pdo->exec('CREATE TABLE zyt_pharmacy_submission_claim (id INT PRIMARY KEY,prescription_order_id INT,source_revision INT,status VARCHAR(40))'); + Db::name('tcm_prescription_order')->insert(['id' => 1, 'order_no' => 'TEST-ESIGN', 'prescription_id' => 2, 'prescription_audit_status' => 0, 'fulfillment_status' => 0]); + $expect(PrescriptionLogic::audit(2, 'approve', '', 1, $root) === false, 'manual prescription audit rejects unsigned'); + $expect(str_contains(PrescriptionLogic::getError(), '电子签署'), 'manual audit explains signature requirement'); + $expect(PrescriptionOrderLogic::auditPrescription(1, 'approve', '', 1, $root) === false, 'order audit rejects unsigned before write'); + $expect((int) Db::name('tcm_prescription_order')->where('id', 1)->value('prescription_audit_status') === 0, 'order remains pending after rejection'); + $expect(PrescriptionOrderLogic::addLog(['id' => 1, 'summary' => '测试', 'prescription_audit_status' => 1], 1, $root) === false, 'manual order log cannot bypass signature requirement'); + Db::name('tcm_prescription')->where('id', 2)->update(['esign_status' => 'authenticating']); + $expect(PrescriptionLogic::patchPatientContact(2, '变更患者', '13800000000', 1, 1, $root) === false, 'patient correction cannot alter frozen original'); + $expect(PrescriptionLogic::delete(2) === false, 'frozen evidence cannot be deleted through normal delete'); + $config->set(['enabled' => false], 'esign'); + $expect(PrescriptionLogic::audit(2, 'approve', '', 1, $root) === false, 'switching feature off cannot bypass persisted requirement'); + PrescriptionEsignService::assertSignedById(1); + $expect(true, 'historical rows do not require new evidence'); + + // Real InnoDB contention: a second connection attempts to void the very + // prescription being approved, at the exact model before-write boundary. + Db::name('tcm_prescription')->where('id', 2)->update(['esign_status' => 'signed']); + $snapshot = PrescriptionEsignPolicy::hash(Db::name('tcm_prescription')->find(2)); + $storage = sys_get_temp_dir() . '/zyt-' . $database; + $relative = '2-' . $snapshot . '/signed.pdf'; + $pdfPath = $storage . '/' . $relative; + mkdir(dirname($pdfPath), 0700, true); + $pdf = "%PDF-1.7\nTEST ONLY\n%%EOF"; + file_put_contents($pdfPath, $pdf); + $config->set(['storage_path' => $storage], 'esign'); + Db::name('prescription_esign')->insert([ + 'prescription_id' => 2, 'doctor_id' => 1, 'environment' => 'sandbox', 'app_id' => 'fixture', + 'snapshot_hash' => $snapshot, 'source_hash' => hash('sha256', $pdf), 'source_path' => '', + 'signed_hash' => hash('sha256', $pdf), 'signed_path' => $relative, + 'account_id' => 'fixture-account', 'sign_service_id' => 'fixture-sign', + 'signed_at' => time(), 'create_time' => time(), 'update_time' => time(), + ]); + try { + PharmacySubmissionClaimService::acquire(1, 1, 'gancao', 1, '测试'); + $expect(false, 'sandbox must not acquire a dispensing claim'); + } catch (DomainException $e) { + $expect(str_contains($e->getMessage(), '沙箱'), 'claim boundary enforces production signatures'); + } + $pdo->exec('SET SESSION innodb_lock_wait_timeout=1'); + $events = new class($pdo, $expect) { + public int $attempts = 0; + public function __construct(private PDO $otherConnection, private Closure $expect) {} + public function trigger(string $event, mixed $model): array { + if (!str_ends_with($event, '.BeforeUpdate')) { return []; } + $this->attempts++; + try { + $this->otherConnection->exec('UPDATE zyt_tcm_prescription SET void_status=1 WHERE id=2'); + ($this->expect)(false, 'concurrent void must wait for signature check + audit write'); + } catch (PDOException $e) { + ($this->expect)((int) ($e->errorInfo[1] ?? 0) === 1205, 'prescription row lock held at audit write'); + } + throw new DomainException('TEST_LOCK_OBSERVED'); + } + }; + \think\Model::setEvent($events); + $expect(PrescriptionLogic::audit(2, 'approve', '', 1, $root) === false && PrescriptionLogic::getError() === 'TEST_LOCK_OBSERVED', 'manual audit reaches locked write'); + $expect(PrescriptionOrderLogic::auditPrescription(1, 'approve', '', 1, $root) === false && PrescriptionOrderLogic::getError() === 'TEST_LOCK_OBSERVED', 'order audit reaches locked write'); + $expect(PrescriptionOrderLogic::addLog(['id' => 1, 'summary' => '测试', 'prescription_audit_status' => 1], 1, $root) === false && PrescriptionOrderLogic::getError() === 'TEST_LOCK_OBSERVED', 'manual status change reaches locked write'); + $expect($events->attempts === 3 && (int) Db::name('tcm_prescription')->where('id', 2)->value('void_status') === 0, 'all concurrent void attempts blocked'); + echo "Prescription eSign MySQL migration and business gates: $checks checks passed\n"; +} finally { + \think\Model::setEvent(null); + if ($pdfPath !== null && is_file($pdfPath)) { + unlink($pdfPath); + rmdir(dirname($pdfPath)); + rmdir(dirname(dirname($pdfPath))); + } + $manager->connect()->close(); + if (!preg_match('/^esign_test_[a-f0-9]{12}$/D', $database)) { throw new RuntimeException('Unsafe test database'); } + $pdo->exec("DROP DATABASE `$database`"); +}