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 000000000..23303be6c Binary files /dev/null and b/artifacts/esign-backend-review.png differ 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 000000000..9127e2b44 Binary files /dev/null and b/artifacts/esign-prescription-test.png differ 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`"); +}