const assert = require('node:assert/strict') const fs = require('node:fs') const path = require('node:path') const test = require('node:test') const { createHash, webcrypto } = require('node:crypto') const ts = require('typescript') const vue = require('vue') const { parse, compileScript, compileTemplate } = require('@vue/compiler-sfc') globalThis.crypto ??= webcrypto function loadModule(filename, imports) { const code = ts.transpileModule(fs.readFileSync(path.join(__dirname, '../src', filename), 'utf8'), { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS } }).outputText const exports = {} new Function('require', 'exports', code)((id) => { assert.ok(Object.hasOwn(imports, id), `Unexpected import ${id}`) return imports[id] }, exports) return exports } const pdfBytes = Buffer.from('%PDF-1.7\nSigned test bytes\n%%EOF') const file = { filename: 'signed.pdf', content_base64: pdfBytes.toString('base64'), sha256: createHash('sha256').update(pdfBytes).digest('hex') } const status = (changes = {}) => ({ enabled: true, required: true, environment: 'sandbox', status: 'pending', status_label: '待签署', can_sign: true, can_download: false, message: '', ...changes }) test('signing mutations allow 180 seconds and explicitly disable transport replay', async () => { const calls = [] const api = loadModule('api/tcm.ts', { '@/utils/request': { default: { post: async (config, options) => { calls.push({ config, options }); return status() } } } }) await api.prescriptionEsignStart({ id: 17 }) await api.prescriptionEsignStart({ id: 17, restart_identity: true }) await api.prescriptionEsignComplete({ id: 17 }) assert.equal(calls.length, 3) assert.deepEqual(calls[1].config.params, { id: 17, restart_identity: true }) for (const { config, options } of calls) { assert.equal(config.timeout, 180000) assert.equal(options.isOpenRetry, false) assert.equal(options.retryCount, 0) } }) test('the detail and audit status requests use independent cancellation signals', async () => { const calls = [] const api = loadModule('api/tcm.ts', { '@/utils/request': { default: { get: async (config, options) => { calls.push({ config, options }); return status() } } } }) const detail = new AbortController() const audit = new AbortController() await Promise.all([api.prescriptionEsignStatus({ id: 17 }, detail.signal), api.prescriptionEsignStatus({ id: 17 }, audit.signal)]) assert.equal(calls[0].config.signal, detail.signal) assert.equal(calls[1].config.signal, audit.signal) assert.ok(calls.every((call) => call.options.ignoreCancelToken === true)) }) 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('prescription audit requires a signed archive or an explicit legacy state', () => { const { canApprovePrescriptionEsign } = loadModule('utils/prescription-esign.ts', { '@/api/tcm': {} }) for (const state of ['pending', 'authenticating', 'signing', 'uncertain', 'failed', 'voided', 'legacy']) { assert.equal(canApprovePrescriptionEsign(status({ status: state, can_download: true })), false) } assert.equal(canApprovePrescriptionEsign(null), false) assert.equal(canApprovePrescriptionEsign({ status: 'signed', can_download: true }), false) assert.equal(canApprovePrescriptionEsign(status({ status: 'signed' })), false) assert.equal(canApprovePrescriptionEsign(status({ status: 'signed', can_download: true })), true) assert.equal(canApprovePrescriptionEsign(status({ enabled: false, required: false, status: 'legacy', can_sign: false })), true) assert.equal(canApprovePrescriptionEsign(status({ required: false, status: 'legacy', can_sign: false })), true) }) test('signature time uses Beijing time and keeps the system verification time separate', () => { const { prescriptionEsignTiming } = loadModule('utils/prescription-esign.ts', { '@/api/tcm': {} }) const signatureTime = Date.parse('2026-11-17T16:03:04Z') / 1000 const verifiedTime = signatureTime + 30 const evidence = status({ status: 'signed', can_download: true, signed_at: verifiedTime }) assert.deepEqual(prescriptionEsignTiming({ ...evidence, issued_at: signatureTime - 2, signature_time: signatureTime, signature_time_source: 'tsa' }), { issuedTime: '2026/11/18 00:03:02', signatureTime: '2026/11/18 00:03:04', source: '可信时间戳', verifiedTime: '2026/11/18 00:03:34' }) assert.equal(prescriptionEsignTiming({ ...evidence, signature_time: signatureTime, signature_time_source: 'local' }).source, '签名记录时间') assert.deepEqual(prescriptionEsignTiming(evidence), { issuedTime: '', signatureTime: '', source: '', verifiedTime: '2026/11/18 00:03:34' }) for (const [time, source] of [[0, 'tsa'], [signatureTime, ''], [signatureTime * 1000, 'tsa']]) { assert.equal(prescriptionEsignTiming({ ...evidence, signature_time: time, signature_time_source: source }).signatureTime, '') } assert.equal(prescriptionEsignTiming({ ...evidence, status: 'voided' }).verifiedTime, '2026/11/18 00:03:34') assert.equal(prescriptionEsignTiming(status({ status: 'voided' })), null) assert.equal(prescriptionEsignTiming({ ...evidence, status: 'pending' }), null) assert.equal(prescriptionEsignTiming({ ...evidence, status: 'legacy' }), null) }) 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 lifecycle = {} const timers = new Map() let now = 0 let timerId = 0 const document = { visibilityState: 'visible', addEventListener() {}, removeEventListener() {} } const props = { prescriptionId: 17, initialState: initial } const utils = loadModule('utils/prescription-esign.ts', { '@/api/tcm': {} }) const globals = { ref: vue.ref, computed: vue.computed, toRaw: vue.toRaw, watch: (getter, callback) => watchers.push(callback), onMounted: (cb) => { lifecycle.mounted = cb }, onBeforeUnmount: (cb) => { lifecycle.unmount = cb }, onDeactivated: (cb) => { lifecycle.deactivate = cb }, setTimeout: (cb, delay) => { const id = ++timerId; timers.set(id, { cb, at: now + delay }); return id }, clearTimeout: (id) => timers.delete(id), Date: { now: () => now }, document, props, emit: (_, value) => events.push(value), useUserStore: () => ({ serverTimeOffsetMs: 0 }), safeEsignAuthUrl: utils.safeEsignAuthUrl, canApprovePrescriptionEsign: utils.canApprovePrescriptionEsign, canCheckEsignIdentity: utils.canCheckEsignIdentity, formatSigningTime: utils.formatSigningTime, prescriptionEsignTiming: utils.prescriptionEsignTiming, validateEsignStatus: utils.validateEsignStatus, validateEsignIdentityStatus: utils.validateEsignIdentityStatus, downloadOriginalEsignPdf: async (id, isCurrent) => { calls.push(['download', { id }]); return api.download?.(isCurrent) }, prescriptionEsignStatus: async (p) => { calls.push(['status', p]); return api.refresh ? api.refresh() : initial }, prescriptionSubmitForReview: async (p) => { calls.push(['upload', p]); return api.upload(p) }, prescriptionEsignDoctorStatus: async (signal) => { calls.push(['profile']); return api.profile(signal) }, prescriptionEsignStart: async (p) => { calls.push(['start', p]); return api.start ? api.start(p) : identity() }, prescriptionEsignIdentityStatus: async (p, signal) => { calls.push(['identity', p]); return api.identity ? api.identity(signal) : identity() }, prescriptionEsignVerifyWillingness: async (p) => { calls.push(['verify-sms', p]); return api.verifySms(p) }, prescriptionEsignComplete: async (p) => { calls.push(['complete', p]); return api.complete ? api.complete(p) : status({ status: 'signed', can_sign: false, can_download: true }) } } const value = new Function(...Object.keys(globals), `${compiledPanel}\nreturn { state, busy, work, confirmed, showControls, signingTime, signingLog, showSigningLog, error, authUrl, start, refresh, dialogVisible, readiness, action, message, activeStep, identityNumber, identityDetailsRequired, confirmSign, closeAuthentication, authenticationUnavailable, onVisibilityChange, smsCode, smsCodeEntry, smsSendCoolingDown, sendSms, verifySms, showSteps, reviewRequired, reviewSigning, updateReview, runAction, statusNotice }`)(...Object.values(globals)) value.confirmed.value = true // The existing-state tests begin after a successful initial query. async function advance(ms) { now += ms for (const [id, timer] of [...timers]) { if (timers.has(id) && timer.at <= now) { timers.delete(id); timer.cb() } } await flush() } return { ...value, props, calls, events, watchers, document, lifecycle, timers, advance } } function identity(changes = {}) { return status({ status: 'authenticating', auth_url: 'https://idverify.esign.cn/session', identity_status: 'ING', can_complete: false, ...changes }) } function accountBasedStatus(method, changes = {}) { return status({ verification_method: method, doctor_identity_required: false, ...changes }) } function accountBasedIdentity(method, changes = {}) { return accountBasedStatus(method, { status: 'authenticating', can_resume_identity: true, identity_status: 'SUCCESS', can_complete: true, ...(method === 'sms' ? { sms_sent: true } : {}), ...changes }) } test('a saved draft must upload before quick-sign preparation, with retry and explicit confirmation', async () => { const draft = status({ review_required: true, awaiting_upload: true, review_submitted_at: 0, can_submit_for_review: true, can_review_prescription: false, can_sign: false }) const submitted = accountBasedStatus('quick', { review_required: true, awaiting_upload: false, review_submitted_at: 1760000000, can_submit_for_review: false, can_review_prescription: false }) let attempts = 0 const p = panel(draft, { refresh: async () => attempts === 2 ? submitted : draft, upload: async () => { if (++attempts === 1) throw new Error('temporary network error') return { review_submitted_at: 1760000000, can_submit_for_review: false } }, start: async () => ({ ...submitted, status: 'authenticating', can_resume_identity: true }), identity: async () => accountBasedIdentity('quick', { ...submitted, status: 'authenticating', can_resume_identity: true }) }) p.watchers[0]() await flush() assert.equal(p.action.value.label, '上传处方') assert.equal(p.activeStep.value, 1) assert.deepEqual(p.calls.map(([name]) => name), ['status']) await p.runAction() assert.match(p.error.value, /重试/) assert.equal(p.action.value.label, '上传处方') await p.runAction() assert.deepEqual(p.calls.map(([name]) => name), ['status', 'upload', 'upload', 'status', 'start', 'identity']) assert.equal(p.action.value.label, '确认签名') assert.equal(p.activeStep.value, 2) await p.runAction() assert.equal(p.calls.at(-1)[0], 'complete') }) test('quick signing prepares once on open and waits for the prescriber to confirm', async () => { const prepared = accountBasedStatus('quick', { status: 'authenticating', can_resume_identity: true }) const p = panel(accountBasedStatus('quick'), { start: async () => prepared, identity: async () => accountBasedIdentity('quick') }) p.watchers[0]() await flush() assert.deepEqual(p.calls, [['status', { id: 17 }], ['start', { id: 17 }], ['identity', { id: 17 }]]) assert.equal(p.action.value.label, '确认签名') assert.match(p.message.value, /核对处方内容后确认签名/) assert.equal(p.dialogVisible.value, false) await p.advance(20000) assert.equal(p.calls.length, 3) await p.action.value.run() await p.confirmSign() assert.deepEqual(p.calls.at(-1), ['complete', { id: 17 }]) assert.equal(p.calls.length, 4) assert.equal(p.action.value.label, '下载已签 PDF') }) test('quick signing rechecks a retained flow and replaces a stale grant at most once', async () => { const prepared = accountBasedStatus('quick', { status: 'authenticating', can_resume_identity: true }) let expired = false const p = panel(prepared, { start: async () => prepared, identity: async () => accountBasedIdentity('quick', expired ? { identity_status: 'EXPIRED', can_complete: false } : {}) }) await p.refresh() assert.deepEqual(p.calls.map(([method]) => method), ['status', 'identity']) assert.equal(p.action.value.label, '确认签名') expired = true await p.refresh() assert.deepEqual(p.calls.slice(2), [ ['status', { id: 17 }], ['identity', { id: 17 }], ['start', { id: 17, restart_identity: true }], ['identity', { id: 17 }] ]) assert.equal(p.action.value.label, '查询签署状态') assert.equal(p.readiness.value, null) }) test('quick signing routes missing identity and unusable grants to account settings', async () => { const missingIdentity = accountBasedStatus('quick', { doctor_identity_required: true }) const blocked = panel(missingIdentity) await blocked.refresh() await blocked.confirmSign() assert.deepEqual(blocked.calls.map(([method]) => method), ['status']) assert.match(blocked.message.value, /身份认证.*签署身份与证书/) for (const [reason, copy] of [['missing', /待完成/], ['expired', /已到期/], ['exhausted', /次数已用完/], ['invalid', /已失效/]]) { let authorized = false const pending = accountBasedStatus('quick') const p = panel(pending, { start: async () => authorized ? accountBasedStatus('quick', { status: 'authenticating', can_resume_identity: true }) : accountBasedStatus('quick', { status: 'failed', signing_authorization_required: true, signing_authorization_reason: reason }), identity: async () => accountBasedIdentity('quick') }) await p.refresh() assert.deepEqual(p.calls.map(([method]) => method), ['status', 'start']) assert.equal(p.action.value.label, '查询签署状态') assert.match(p.message.value, copy) assert.match(p.message.value, /签署身份与证书/) authorized = true await p.action.value.run() assert.equal(p.action.value.label, '确认签名') assert.equal(p.calls.some(([method]) => method === 'complete'), false) } }) test('quick signing discards late readiness when the page is hidden and refresh can recover', async () => { let resolve let signal const prepared = accountBasedStatus('quick', { status: 'authenticating', can_resume_identity: true }) const p = panel(prepared, { identity: (controller) => { signal = controller return new Promise((done) => { resolve = done }) } }) const pending = p.refresh() await flush() p.document.visibilityState = 'hidden' p.onVisibilityChange() assert.equal(signal.aborted, true) resolve(accountBasedIdentity('quick')) await pending assert.equal(p.readiness.value, null) p.document.visibilityState = 'visible' await p.confirmSign() const refreshed = p.action.value.run() await flush() resolve(accountBasedIdentity('quick')) await refreshed assert.deepEqual(p.calls.map(([method]) => method), ['status', 'identity', 'status', 'identity']) assert.equal(p.action.value.label, '确认签名') }) test('current account-based identity cannot be inferred from an inconsistent response', async () => { const { validateEsignIdentityStatus } = loadModule('utils/prescription-esign.ts', { '@/api/tcm': {} }) for (const response of [ accountBasedIdentity('quick', { can_resume_identity: false }), accountBasedIdentity('quick', { signing_authorization_required: true }), accountBasedIdentity('quick', { doctor_identity_required: true }), accountBasedIdentity('quick', { identity_details_required: true, can_complete: false }), accountBasedIdentity('sms', { sms_sent: false }), accountBasedIdentity('sms', { sms_sent: 'true' }) ]) { assert.throws(() => validateEsignIdentityStatus(response), /状态|验证结果/) } const p = panel(accountBasedStatus('quick', { status: 'authenticating', can_resume_identity: true }), { identity: async () => accountBasedIdentity('sms') }) await p.refresh() assert.equal(p.confirmed.value, false) assert.equal(p.readiness.value, null) assert.equal(p.action.value.label, '查询签署状态') }) test('SMS is sent and verified separately from signing', async () => { const sent = accountBasedStatus('sms', { status: 'authenticating', sms_sent: true, can_resume_identity: true }) const p = panel(accountBasedStatus('sms'), { start: async () => sent, identity: async () => accountBasedIdentity('sms', { identity_status: 'ING', can_complete: false }), verifySms: async () => accountBasedIdentity('sms') }) await p.refresh() assert.deepEqual(p.calls.map(([method]) => method), ['status']) assert.equal(p.action.value.label, '发送验证码') await p.action.value.run() assert.equal(p.smsCodeEntry.value, true) assert.equal(p.action.value.label, '校验验证码') assert.equal(p.smsSendCoolingDown.value, true) await p.sendSms() await p.confirmSign() p.smsCode.value = '12345a' await p.action.value.run() assert.equal(p.smsCode.value, '') assert.match(p.error.value, /6位短信验证码/) assert.deepEqual(p.calls.map(([method]) => method), ['status', 'start', 'identity']) p.smsCode.value = '000123' await p.action.value.run() assert.deepEqual(p.calls.at(-1), ['verify-sms', { id: 17, auth_code: '000123' }]) assert.equal(p.smsCode.value, '') assert.equal(p.smsCodeEntry.value, false) assert.equal(p.action.value.label, '确认签名') assert.equal(JSON.stringify(p.events).includes('000123'), false) assert.equal(p.calls.some(([method]) => method === 'complete'), false) await p.action.value.run() assert.deepEqual(p.calls.at(-1), ['complete', { id: 17 }]) assert.equal(p.action.value.label, '下载已签 PDF') }) test('SMS wrong-code and expiry responses permit only the appropriate retry', async () => { const sent = accountBasedStatus('sms', { status: 'authenticating', sms_sent: true, can_resume_identity: true }) let expired = false const p = panel(accountBasedStatus('sms'), { start: async () => sent, identity: async () => accountBasedIdentity('sms', { identity_status: 'ING', can_complete: false }), verifySms: async () => accountBasedIdentity('sms', { identity_status: expired ? 'EXPIRED' : 'ING', can_complete: false }) }) await p.sendSms() p.smsCode.value = '000123' await p.verifySms() assert.match(p.error.value, /未通过/) assert.equal(p.smsCodeEntry.value, true) expired = true p.smsCode.value = '123456' await p.verifySms() assert.equal(p.smsCodeEntry.value, false) assert.match(p.message.value, /已失效/) await p.sendSms() await p.verifySms() assert.equal(p.calls.filter(([method]) => method === 'start').length, 1) await p.advance(60000) assert.equal(p.action.value.label, '重新发送验证码') await p.action.value.run() assert.deepEqual(p.calls.at(-2), ['start', { id: 17, restart_identity: true }]) assert.equal(p.smsCodeEntry.value, true) assert.equal(p.calls.some(([method]) => method === 'complete'), false) }) test('SMS checks the repaired account profile before allowing another manual send', async () => { const blocked = accountBasedStatus('sms', { status: 'failed', doctor_identity_required: true, message: '请完成实名手机号认证' }) const sent = accountBasedStatus('sms', { status: 'authenticating', sms_sent: true, can_resume_identity: true }) let profileStatus = 'needs_mobile' const p = panel(blocked, { profile: async () => ({ enabled: true, status: profileStatus }), start: async () => sent, identity: async () => accountBasedIdentity('sms', { identity_status: 'ING', can_complete: false }) }) await p.refresh() assert.match(p.message.value, /签署身份与证书/) await p.sendSms() assert.deepEqual(p.calls.map(([method]) => method), ['status', 'profile']) profileStatus = 'ready' await p.refresh() assert.match(p.message.value, /医生签署身份已就绪/) assert.equal(p.action.value.label, '发送验证码') assert.deepEqual(p.calls.map(([method]) => method), ['status', 'profile', 'status', 'profile']) await p.action.value.run() assert.equal(p.smsCodeEntry.value, true) }) test('SMS suspension discards late verification without sending again', async () => { let resolve const sent = accountBasedStatus('sms', { status: 'authenticating', sms_sent: true, can_resume_identity: true }) const p = panel(sent, { identity: async () => accountBasedIdentity('sms', { identity_status: 'ING', can_complete: false }), verifySms: () => new Promise((done) => { resolve = done }) }) await p.refresh() p.smsCode.value = '000123' const pending = p.verifySms() assert.equal(p.smsCode.value, '') p.document.visibilityState = 'hidden' p.onVisibilityChange() resolve(accountBasedIdentity('sms')) await pending assert.equal(p.readiness.value, null) assert.equal(p.smsCodeEntry.value, false) p.document.visibilityState = 'visible' await p.confirmSign() assert.deepEqual(p.calls.map(([method]) => method), ['status', 'identity', 'verify-sms']) }) test('SMS verification uses a masked six-digit input and a POST without retries', async () => { const { descriptor } = parse(fs.readFileSync(panelPath, 'utf8')) assert.match(descriptor.template.content, /v-model="smsCode"\s+type="password"\s+inputmode="numeric"\s+maxlength="6"\s+autocomplete="off"/) const calls = [] const api = loadModule('api/tcm.ts', { '@/utils/request': { default: { post: async (config, options) => { calls.push({ config, options }); return accountBasedIdentity('sms') } } } }) await api.prescriptionEsignVerifyWillingness({ id: 17, auth_code: '000123' }) assert.equal(calls[0].config.url, '/tcm.prescription/esignVerifyWillingness') assert.deepEqual(calls[0].config.params, { id: 17, auth_code: '000123' }) assert.equal(calls[0].options.isOpenRetry, false) assert.equal(calls[0].options.retryCount, 0) }) test('audit panel retains signing evidence when signing actions are hidden', async () => { const evidence = status({ status: 'signed', can_sign: false, can_download: true }) const p = panel(evidence, { refresh: async () => ({ ...evidence, signature_time: Date.parse('2026-11-17T16:03:04Z') / 1000, signature_time_source: 'tsa' }) }) p.props.audit = true assert.equal(p.signingTime.value.signatureTime, '') await p.refresh() assert.equal(p.showControls.value, false) assert.equal(p.signingTime.value.signatureTime, '2026/11/18 00:03:04') }) test('audit progress waits for a verified pharmacist signature and shows its trusted time', async () => { const doctor = status({ status: 'signed', can_sign: false, can_download: true, review_required: true }) const p = panel(doctor) p.props.audit = true await p.refresh() assert.equal(p.showControls.value, false) assert.equal(p.showSteps.value, true) assert.equal(p.activeStep.value, 3) assert.match(p.message.value, /等待药师审核签署/) const time = Date.parse('2026-11-17T16:03:04Z') / 1000 p.updateReview({ required: true, state: 'verifying', signature_time: time, signer_name: '测试药师' }) assert.equal(p.reviewSigning.value, null) assert.equal(p.activeStep.value, 3) p.updateReview({ required: true, state: 'signed', signature_time: 0, signer_name: '测试药师' }) assert.equal(p.activeStep.value, 3) p.updateReview({ required: true, state: 'signed', signature_time: time, signer_name: '测试药师' }) assert.equal(p.activeStep.value, 4) assert.deepEqual(p.reviewSigning.value, { time: '2026/11/18 00:03:04', name: '测试药师' }) }) test('single-signed records retain three steps and archived pharmacist timestamps show a completed fourth step', async () => { const signed = status({ status: 'signed', can_sign: false, can_download: true }) const single = panel(signed) assert.equal(single.showSteps.value, true) assert.equal(single.reviewRequired.value, false) assert.equal(single.activeStep.value, 3) const audit = panel(signed) audit.props.audit = true await audit.refresh() assert.equal(audit.showSteps.value, false) audit.updateReview({ required: true, state: 'pending' }) assert.equal(audit.showSteps.value, true) assert.equal(audit.activeStep.value, 3) const time = Date.parse('2026-11-17T16:03:04Z') / 1000 for (const status of ['signed', 'voided']) { const response = { ...signed, status, review_signature_time: time, review_signer_name: '测试药师' } const dual = panel(signed, { refresh: async () => response }) await dual.refresh() assert.equal(dual.showSteps.value, true) assert.equal(dual.reviewRequired.value, true) assert.equal(dual.activeStep.value, 4) assert.deepEqual(dual.reviewSigning.value, { time: '2026/11/18 00:03:04', name: '测试药师' }) } }) test('audit signing panel directs unsigned work to the prescriber', async () => { let response = status() const p = panel(status(), { refresh: async () => response }) p.props.audit = true await p.refresh() assert.equal(p.action.value.label, '验证医生身份') assert.match(p.message.value, /完成核身及电子签署后/) response = status({ can_sign: false }) await p.refresh() assert.equal(p.action.value.label, '查询签署状态') assert.match(p.message.value, /开方医生完成电子签署后/) response = status({ can_sign: false, message: '请先补全处方,再进行电子签署' }) await p.refresh() assert.match(p.message.value, /补全处方/) assert.equal(p.calls.every(([method]) => method === 'status'), true) }) async function flush() { for (let i = 0; i < 10; i++) await Promise.resolve() } test('embedded verification unlocks confirmation without signing after read-only server SUCCESS', async () => { const p = panel(status(), { identity: async () => identity({ identity_status: 'SUCCESS', can_complete: true }) }) await p.start() assert.equal(p.state.value.status, 'authenticating') assert.equal(p.state.value.can_download, false) assert.equal(p.activeStep.value, 1) assert.ok(p.authUrl.value) assert.deepEqual(p.calls, [['start', { id: 17 }]]) await p.advance(4999) assert.equal(p.calls.length, 1) await p.advance(1) assert.equal(p.dialogVisible.value, false) assert.equal(p.activeStep.value, 2) assert.equal(p.action.value.label, '确认签名') await p.advance(10000) assert.deepEqual(p.calls.map(([name]) => name), ['start', 'identity']) await p.action.value.run() assert.equal(p.state.value.status, 'signed') assert.equal(p.events.at(-1).can_download, true) assert.equal(p.dialogVisible.value, false) assert.equal(p.activeStep.value, 3) assert.equal(p.action.value.label, '下载已签 PDF') await p.start() assert.equal(p.calls.length, 3, 'server can_sign=false prevents a new signing request') await p.advance(600000) assert.equal(p.calls.filter(([name]) => name === 'complete').length, 1) }) test('failed or cancelled authentication stays pending and remains recoverable', async () => { const p = panel(status({ status: 'authenticating' })) await p.start() await p.advance(5000) assert.equal(p.state.value.status, 'authenticating') assert.equal(p.state.value.can_download, false) assert.equal(p.calls.some(([name]) => name === 'complete'), 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, /查询签署状态/) 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() 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) }) test('read-only readiness API uses GET, cancellation and no retries', async () => { const calls = [] const api = loadModule('api/tcm.ts', { '@/utils/request': { default: { get: async (config, options) => { calls.push({ config, options }); return identity() } } } }) const controller = new AbortController() await api.prescriptionEsignIdentityStatus({ id: 17 }, controller.signal) assert.equal(calls[0].config.url, '/tcm.prescription/esignIdentityStatus') assert.equal(calls[0].config.signal, controller.signal) assert.equal(calls[0].options.isOpenRetry, false) assert.equal(calls[0].options.retryCount, 0) }) test('iframe cannot navigate the outer page or open a popup, and events are never proof', () => { const source = fs.readFileSync(panelPath, 'utf8') const { descriptor } = parse(source) assert.match(descriptor.template.content, /sandbox="allow-forms allow-scripts allow-same-origin"/) assert.match(descriptor.template.content, /referrerpolicy="no-referrer"/) assert.doesNotMatch(source, /target="_blank"|window\.open|window\.location|allow-popups|allow-top-navigation|postMessage|contentWindow|@load/) assert.doesNotMatch(descriptor.template.content, /:href="authUrl"/) assert.match(descriptor.template.content, /处方草稿已保存[\s\S]+验证医生身份[\s\S]+签名并完成/) assert.match(descriptor.template.content, / { let resolve const p = panel(status(), { identity: () => new Promise((done) => { resolve = done }) }) await p.start() await p.advance(5000) await p.advance(30000) assert.equal(p.calls.filter(([name]) => name === 'identity').length, 1) resolve(identity()) await flush() await p.advance(4999) assert.equal(p.calls.filter(([name]) => name === 'identity').length, 1) await p.advance(1) assert.equal(p.calls.filter(([name]) => name === 'identity').length, 2) p.closeAuthentication() resolve(identity({ identity_status: 'SUCCESS', can_complete: true })) await flush() assert.equal(p.calls.some(([name]) => name === 'complete'), false) }) for (const result of [ identity({ identity_status: 'SUCCESS', can_complete: false }), identity({ identity_status: 'ING', can_complete: false }), identity({ identity_status: 'INIT', can_complete: false }) ]) { test(`readiness ${result.identity_status} / can_complete=false does not submit`, async () => { const p = panel(status(), { identity: async () => result }) await p.start() await p.advance(5000) assert.equal(p.calls.some(([name]) => name === 'complete'), false) p.closeAuthentication() }) } for (const kind of ['close', 'unmount', 'deactivate', 'hidden', 'prescription', 'source-state', 'unavailable']) { test(`${kind} stops polling and discards late identity SUCCESS`, async () => { let resolve let signal const p = panel(status(), { identity: (abortSignal) => { signal = abortSignal; return new Promise((done) => { resolve = done }) } }) await p.start() await p.advance(5000) if (kind === 'close') p.closeAuthentication() if (kind === 'unmount') p.lifecycle.unmount() if (kind === 'deactivate') p.lifecycle.deactivate() if (kind === 'hidden') { p.document.visibilityState = 'hidden'; p.onVisibilityChange() } if (kind === 'prescription') { p.props.prescriptionId = 18; p.watchers[0]() } if (kind === 'source-state') { p.props.initialState = identity({ auth_url: 'https://idverify.esign.cn/another' }); p.watchers[1](p.props.initialState) } if (kind === 'unavailable') p.authenticationUnavailable() assert.equal(signal.aborted, true) resolve(identity({ identity_status: 'SUCCESS', can_complete: true })) await flush() await p.advance(10000) assert.equal(p.calls.some(([name]) => name === 'complete'), false) assert.equal(p.calls.filter(([name]) => name === 'identity').length, 1) assert.equal(p.dialogVisible.value, false) assert.equal(p.readiness.value, null) }) } test('ten-minute deadline aborts pending readiness and cannot turn a late SUCCESS into signing', async () => { let resolve const p = panel(status(), { identity: () => new Promise((done) => { resolve = done }) }) await p.start() await p.advance(5000) await p.advance(595000) assert.match(p.error.value, /超时/) assert.equal(p.dialogVisible.value, false) assert.equal(p.readiness.value, null) resolve(identity({ identity_status: 'SUCCESS', can_complete: true })) await flush() assert.equal(p.calls.some(([name]) => name === 'complete'), false) assert.equal(p.timers.size, 0) }) for (const result of [ identity({ identity_status: 'FAIL' }), identity({ identity_status: 'UNAVAILABLE' }), identity({ status: 'failed' }), identity({ status: 'uncertain' }), identity({ status: 'signed', can_download: true, can_sign: false }), identity({ identity_status: 'ING', can_complete: true }), { status: 'authenticating', identity_status: 'SUCCESS', can_complete: true } ]) { test(`failed, terminal or invalid readiness stops: ${JSON.stringify(result)}`, async () => { const p = panel(status(), { identity: async () => result }) await p.start() await p.advance(5000) await p.advance(10000) assert.equal(p.calls.filter(([name]) => name === 'identity').length, 1) assert.equal(p.calls.some(([name]) => name === 'complete'), false) assert.equal(p.dialogVisible.value, false) assert.equal(p.readiness.value, null) assert.equal(p.timers.size, 0) }) } for (const outcome of ['error', 'pending', 'uncertain']) { test(`completion ${outcome} never retries and refresh is read-only`, async () => { const p = panel(status(), { identity: async () => identity({ identity_status: 'SUCCESS', can_complete: true }), complete: async () => { if (outcome === 'error') throw new Error('timeout'); return identity({ status: outcome }) } }) await p.start() await p.advance(5000) await p.confirmSign() await p.advance(600000) await p.refresh() assert.equal(p.calls.filter(([name]) => name === 'complete').length, 1) assert.equal(p.calls.filter(([name]) => name === 'identity').length, 1) assert.equal(p.dialogVisible.value, false) assert.equal(p.readiness.value, null) }) } test('invalid authentication URL never mounts a frame or polls', async () => { const p = panel(status(), { start: async () => identity({ auth_url: 'https://evil.example/session' }) }) await p.start() await p.advance(10000) assert.equal(p.authUrl.value, '') assert.equal(p.dialogVisible.value, false) assert.equal(p.calls.length, 1) assert.match(p.error.value, /链接无效/) }) test('restoring a saved authentication flow or refreshing alone never starts polling or signs', async () => { const p = panel(identity()) await p.refresh() await p.advance(600000) assert.deepEqual(p.calls, [['status', { id: 17 }]]) assert.equal(p.dialogVisible.value, false) }) test('a pre-sign failure rechecks the retained flow and waits for a new confirmation', async () => { const failed = status({ status: 'failed', can_resume_identity: true, message: '可重新检查身份验证' }) let attempts = 0 const p = panel(status(), { identity: async () => attempts === 0 ? identity({ identity_status: 'SUCCESS', can_complete: true }) : { ...failed, identity_status: 'SUCCESS', can_complete: true }, complete: async () => ++attempts === 1 ? failed : status({ status: 'signed', can_sign: false, can_download: true }) }) await p.action.value.run() await p.advance(5000) await p.action.value.run() assert.equal(p.action.value.label, '检查身份验证') await p.action.value.run() assert.equal(p.dialogVisible.value, false) assert.equal(p.action.value.label, '确认签名') assert.deepEqual(p.calls.map(([name]) => name), ['start', 'identity', 'complete', 'identity']) await p.action.value.run() assert.equal(p.action.value.label, '下载已签 PDF') }) for (const expiredOrFailed of ['EXPIRED', 'FAIL']) { test(`${expiredOrFailed} requires a separate restart action`, async () => { const p = panel(identity(), { identity: async () => identity({ identity_status: expiredOrFailed, auth_url: undefined, can_resume_identity: true }) }) await p.action.value.run() assert.equal(p.action.value.label, '重新验证医生身份') assert.deepEqual(p.calls, [['identity', { id: 17 }]]) await p.action.value.run() assert.deepEqual(p.calls.at(-1), ['start', { id: 17, restart_identity: true }]) assert.equal(p.dialogVisible.value, true) }) } test('transport ambiguity requires a fresh status check; unknown signatures never resubmit', async () => { const p = panel(status(), { identity: async () => identity({ identity_status: 'SUCCESS', can_complete: true }), complete: async () => { throw new Error('timeout') }, refresh: async () => status({ status: 'uncertain', can_sign: false }) }) await p.action.value.run() await p.advance(5000) await p.action.value.run() assert.equal(p.action.value.label, '查询签署状态') await p.confirmSign() await p.action.value.run() assert.equal(p.action.value.label, '查询签署状态') await p.advance(600000) assert.deepEqual(p.calls.map(([name]) => name), ['start', 'identity', 'complete', 'status']) }) test('archive recovery only verifies, and download retries directly from the signed state', async () => { const signed = status({ status: 'signed', can_sign: false, can_download: true }) let downloads = 0 const p = panel(status({ status: 'uncertain', can_sign: false, can_retry_verify: true }), { complete: async () => signed, refresh: async () => signed, download: async () => { if (++downloads === 1) throw new Error('offline') } }) assert.equal(p.action.value.label, '重试校验已签文件') await p.action.value.run() assert.deepEqual(p.calls, [['complete', { id: 17, verify_only: true }]]) assert.equal(p.action.value.label, '下载已签 PDF') await p.action.value.run() assert.match(p.error.value, /下载已签 PDF 失败/) assert.equal(p.confirmed.value, true) assert.equal(p.action.value.label, '下载已签 PDF') await p.action.value.run() assert.equal(p.error.value, '') assert.deepEqual(p.calls.map(([name]) => name), ['complete', 'status', 'download', 'status', 'download']) }) test('readiness errors stop without retry or any completion request', async () => { const p = panel(status(), { identity: async () => { throw new Error('offline') } }) await p.start() await p.advance(5000) await p.advance(600000) assert.deepEqual(p.calls.map(([name]) => name), ['start', 'identity']) assert.equal(p.confirmed.value, false) assert.equal(p.dialogVisible.value, false) assert.match(p.error.value, /查询签署状态/) }) test('a pending completion consumes the intent and cannot be replayed by click, timer or refresh', async () => { let resolve const p = panel(status(), { identity: async () => identity({ identity_status: 'SUCCESS', can_complete: true }), complete: () => new Promise((done) => { resolve = done }) }) await p.start() await p.advance(5000) const sign = p.confirmSign() assert.equal(p.busy.value, true) assert.equal(p.work.value, 'sign') await p.confirmSign() await p.start() await p.refresh() await p.advance(600000) assert.deepEqual(p.calls.map(([name]) => name), ['start', 'identity', 'complete']) p.document.visibilityState = 'hidden' p.onVisibilityChange() resolve(status({ status: 'signed', can_sign: false, can_download: true })) await sign await flush() assert.notEqual(p.state.value.status, 'signed', 'closed flow discards late mutation reply; a fresh read is required') assert.equal(p.busy.value, false) }) test('parent echo of the emitted DTO preserves the active verification intent', async () => { const p = panel() await p.start() p.props.initialState = vue.reactive(p.events.at(-1)) p.watchers[1](p.props.initialState) assert.equal(p.dialogVisible.value, true) await p.advance(5000) assert.deepEqual(p.calls.map(([name]) => name), ['start', 'identity']) p.closeAuthentication() }) const syntheticIdentityNumber = '110101199001010015' const bindingRequired = () => identity({ identity_status: 'SUCCESS', identity_details_required: true }) test('completion includes supplementary identity only when supplied and never retries', async () => { const calls = [] const api = loadModule('api/tcm.ts', { '@/utils/request': { default: { post: async (config, options) => { calls.push({ config, options }); return status() } } } }) await api.prescriptionEsignComplete({ id: 17, identity_number: undefined }) await api.prescriptionEsignComplete({ id: 17, identity_number: syntheticIdentityNumber }) await api.prescriptionEsignComplete({ id: 17, verify_only: true }) assert.deepEqual(calls[0].config.params, { id: 17 }) assert.deepEqual(calls[1].config.params, { id: 17, identity_number: syntheticIdentityNumber }) assert.deepEqual(calls[2].config.params, { id: 17, verify_only: true }) assert.equal(calls[1].config.url, '/tcm.prescription/esignComplete') assert.equal(calls[1].options.isOpenRetry, false) assert.equal(calls[1].options.retryCount, 0) }) test('identity readiness defaults omitted supplementary flag to false and rejects conflicting capability', () => { const { validateEsignIdentityStatus } = loadModule('utils/prescription-esign.ts', { '@/api/tcm': {} }) assert.equal(validateEsignIdentityStatus(identity()).identity_details_required, false) assert.equal(validateEsignIdentityStatus(bindingRequired()).identity_details_required, true) assert.equal(validateEsignIdentityStatus(identity({ identity_status: 'EXPIRED' })).identity_status, 'EXPIRED') const resumed = bindingRequired() resumed.status = 'failed' resumed.can_resume_identity = true assert.equal(validateEsignIdentityStatus(resumed).identity_details_required, true) for (const change of [ { identity_details_required: 'true' }, { identity_details_required: 1 }, { identity_details_required: null }, { identity_details_required: true, can_complete: true }, { identity_details_required: true, identity_status: 'ING' }, { identity_details_required: true, status: 'signed' }, { status: 'failed' }, { can_resume_identity: 'true' }, { can_retry_verify: null }, { identity_details_required: true, can_sign: false } ]) { assert.throws(() => validateEsignIdentityStatus({ ...bindingRequired(), ...change }), /状态|验证结果/) } }) test('certificate binding waits without further polling or signing until one explicit submit', async () => { let resolve const p = panel(status(), { identity: async () => bindingRequired(), complete: () => new Promise((done) => { resolve = done }) }) await p.start() await p.advance(5000) assert.equal(p.identityDetailsRequired.value, true) assert.equal(p.busy.value, false) assert.equal(p.dialogVisible.value, false) await p.advance(30000) assert.deepEqual(p.calls.map(([name]) => name), ['start', 'identity']) assert.equal(p.timers.size, 1, 'only the original authentication deadline remains') p.identityNumber.value = syntheticIdentityNumber const first = p.confirmSign() assert.equal(p.identityNumber.value, '', 'masked input clears before the pending request') assert.equal(p.work.value, 'sign') await p.confirmSign() await p.start() await p.refresh() await p.advance(600000) assert.equal(p.calls.filter(([name]) => name === 'complete').length, 1) assert.deepEqual(p.calls.at(-1), ['complete', { id: 17, identity_number: syntheticIdentityNumber }]) assert.equal(JSON.stringify(p.events).includes(syntheticIdentityNumber), false) assert.equal(JSON.stringify(p.state.value).includes(syntheticIdentityNumber), false) resolve(status({ status: 'signed', can_sign: false, can_download: true })) await first assert.equal(p.dialogVisible.value, false) assert.equal(p.identityDetailsRequired.value, false) }) test('supplementary binding rejects malformed input locally and clears it on submit', async () => { const p = panel(status(), { identity: async () => bindingRequired() }) await p.start() await p.advance(5000) for (const value of ['', '123', '11010119900101001?', '000000000000000000']) { p.identityNumber.value = value await p.confirmSign() assert.equal(p.identityNumber.value, '') assert.match(p.error.value, /18位大陆居民身份证号/) assert.equal(p.calls.some(([name]) => name === 'complete'), false) assert.equal(p.busy.value, false) } p.closeAuthentication() }) test('identity details cannot authorize completion before a trusted readiness result', async () => { const p = panel() await p.start() p.identityNumber.value = syntheticIdentityNumber await p.confirmSign() assert.equal(p.identityNumber.value, '') assert.equal(p.calls.some(([name]) => name === 'complete'), false) p.closeAuthentication() }) for (const kind of ['close', 'unmount', 'deactivate', 'hidden', 'prescription', 'source-state', 'refresh', 'timeout']) { test(`${kind} clears certificate identity input and revokes supplemental submission`, async () => { const p = panel(status(), { identity: async () => bindingRequired() }) await p.start() await p.advance(5000) p.identityNumber.value = syntheticIdentityNumber if (kind === 'close') p.closeAuthentication() if (kind === 'unmount') p.lifecycle.unmount() if (kind === 'deactivate') p.lifecycle.deactivate() if (kind === 'hidden') { p.document.visibilityState = 'hidden'; p.onVisibilityChange() } if (kind === 'prescription') { p.props.prescriptionId = 18; p.watchers[0]() } if (kind === 'source-state') { p.props.initialState = status(); p.watchers[1](p.props.initialState) } if (kind === 'refresh') await p.refresh() if (kind === 'timeout') await p.advance(595000) assert.equal(p.identityNumber.value, '') assert.equal(p.identityDetailsRequired.value, false) assert.equal(p.readiness.value, null) await p.confirmSign() await p.advance(10000) assert.equal(p.calls.some(([name]) => name === 'complete'), false) assert.equal(p.calls.filter(([name]) => name === 'identity').length, 1) assert.equal(p.timers.size, 0) }) } test('a late supplemental readiness reply cannot restore a closed dialog or submission', async () => { let resolve const p = panel(status(), { identity: () => new Promise((done) => { resolve = done }) }) await p.start() await p.advance(5000) p.closeAuthentication() resolve(bindingRequired()) await flush() assert.equal(p.identityDetailsRequired.value, false) assert.equal(p.dialogVisible.value, false) assert.equal(p.calls.some(([name]) => name === 'complete'), false) }) for (const outcome of ['error', 'uncertain']) { test(`supplementary completion ${outcome} clears input, redacts errors and never retries`, async () => { const p = panel(status(), { identity: async () => bindingRequired(), complete: async () => { if (outcome === 'error') throw new Error(`provider rejected ${syntheticIdentityNumber}`) return status({ status: 'uncertain', can_sign: false }) } }) await p.start() await p.advance(5000) p.identityNumber.value = syntheticIdentityNumber await p.confirmSign() await p.confirmSign() await p.advance(600000) assert.equal(p.identityNumber.value, '') assert.equal(p.error.value.includes(syntheticIdentityNumber), false) assert.equal(p.calls.filter(([name]) => name === 'complete').length, 1) assert.equal(p.readiness.value, null) }) } test('supplementary identity is a masked input with explicit action and no persistence or external navigation', () => { const source = fs.readFileSync(panelPath, 'utf8') const { descriptor } = parse(source) assert.match(descriptor.template.content, /v-model="identityNumber"\s+type="password"/) assert.match(descriptor.template.content, /autocomplete="off"/) assert.match(descriptor.template.content, /@click="runAction"/) assert.match(source, /const run = action\.value\.run\s+const current = operation\s+await run\(\)/) assert.match(source, /label: '确认签名', run: confirmSign/) assert.match(descriptor.template.content, /v-if="authUrl && dialogVisible/) assert.doesNotMatch(source, /show-password|localStorage|sessionStorage|console\.|window\.open|window\.location/) }) test('status checks and exiting authentication retain a visible notice without submitting a signature', async () => { const p = panel(status()) p.confirmed.value = false await p.runAction() assert.match(p.statusNotice.value, /签署状态已更新/) p.dialogVisible.value = true p.identityNumber.value = 'private-input' p.closeAuthentication() assert.equal(p.dialogVisible.value, false) assert.equal(p.identityNumber.value, '') assert.match(p.statusNotice.value, /已退出本次签署/) assert.equal(p.action.value.label, '查询签署状态') assert.deepEqual(p.calls.map(([method]) => method), ['status']) }) 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('audit preview loads only its current prescription and refreshes after a signing change', async () => { const filename = 'PrescriptionAuditLayout.vue' const source = fs.readFileSync(path.join(__dirname, '../src/components', filename), 'utf8') const { descriptor } = parse(source, { filename }) const script = compileScript(descriptor, { id: 'audit-preview-test' }).content const js = ts.transpileModule(script, { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS } }).outputText const calls = [] const imports = { vue, '@/api/tcm': { prescriptionDetail: ({ id }, signal) => new Promise((resolve) => calls.push({ id, signal, resolve })) }, '@/components/prescription-slip/index.vue': { default: {} } } const exports = {} new Function('require', 'exports', js)((id) => imports[id], exports) const props = vue.reactive({ prescriptionId: null }) const scope = vue.effectScope() const preview = scope.run(() => exports.default.setup(props, { expose() {} })) try { assert.equal(calls.length, 0) props.prescriptionId = 51 await vue.nextTick() props.prescriptionId = 52 await vue.nextTick() assert.equal(calls[0].signal.aborted, true) assert.deepEqual(calls.map((call) => call.id), [51, 52]) calls[0].resolve({ id: 51 }) calls[1].resolve({ id: 51 }) await Promise.resolve() assert.equal(preview.detail.value, null) assert.match(preview.error.value, /重试/) preview.retry.value++ await vue.nextTick() calls[2].resolve({ id: 52, esign: { signature_time: 10 } }) await Promise.resolve() assert.equal(preview.detail.value.id, 52) assert.equal(preview.error.value, '') props.doctorSignedAt = 10 await vue.nextTick() assert.equal(calls.length, 3) props.pharmacistSignedAt = 15 await vue.nextTick() assert.equal(calls[3].id, 52) calls[3].resolve({ id: 52, esign: { signature_time: 10, review_signature_time: 15 } }) await Promise.resolve() assert.equal(preview.detail.value.esign.review_signature_time, 15) } finally { scope.stop() } }) test('signing log orders actual events and preserves the time source and empty states', () => { const time = Date.parse('2026-11-17T16:03:04Z') / 1000 const entries = [ { event: 'archived', label: '系统归档完成', time: time + 3, source: 'system' }, { event: 'signed', label: '医师签署', time, source: 'tsa', actor_name: '测试医师', message: '签署完成' }, { event: 'draft', label: '草稿已保存', time: time - 2, source: 'local' }, { event: 'invalid', label: '无效时间', time: 0, source: 'tsa' }, { event: 'unknown', label: '未知来源', time, source: 'unknown' } ] const withEvents = panel(status({ signing_log: entries })) assert.deepEqual(withEvents.signingLog.value.map((entry) => [entry.event, entry.sourceLabel]), [ ['draft', '签名记录时间'], ['signed', '可信时间戳'], ['archived', '系统记录'] ]) assert.equal(withEvents.signingLog.value[1].actor_name, '测试医师') assert.equal(withEvents.signingLog.value[1].message, '签署完成') assert.equal(withEvents.signingLog.value[1].timeText, '2026/11/18 00:03:04') assert.equal(entries[0].event, 'archived') assert.equal(withEvents.showSigningLog.value, true) const pending = panel(status()) assert.deepEqual(pending.signingLog.value, []) assert.equal(pending.showSigningLog.value, true) const audit = panel(status()) audit.props.audit = true assert.equal(audit.showSigningLog.value, false) assert.equal(panel(status({ required: false, status: 'legacy' })).showSigningLog.value, false) }) test('both slips use verified physician and pharmacist PNGs and fall back to the signer names', () => { const png = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jN9sAAAAASUVORK5CYII=' const props = vue.reactive({ variant: 'internal', data: { doctor_name: '开方人', doctor_signature: png, esign: status({ status: 'signed', doctor_signer_name: ' 测试医生 ', review_signature_time: 1794931384, review_signer_name: ' 测试药师 ', review_signature: png }) } }) const component = 'components/prescription-slip/index.vue' const { doctorName, doctorSignature, failedDoctorSignature, reviewerName, reviewerSignature, failedReviewerSignature } = pageDeclarations(component, ['verifiedDoctor', 'doctorName', 'failedDoctorSignature', 'doctorSignature', 'reviewerName', 'failedReviewerSignature', 'reviewerSignature', 'isVerifiedSignaturePng'], { computed: vue.computed, ref: vue.ref, props }) for (const variant of ['internal', 'user']) { props.variant = variant assert.equal(doctorName.value, '测试医生') assert.equal(doctorSignature.value, png) assert.equal(reviewerName.value, '测试药师') assert.equal(reviewerSignature.value, png) failedDoctorSignature.value = png failedReviewerSignature.value = png assert.equal(doctorSignature.value, '') assert.equal(reviewerSignature.value, '') assert.equal(doctorName.value, '测试医生') assert.equal(reviewerName.value, '测试药师') failedDoctorSignature.value = '' failedReviewerSignature.value = '' } props.data.esign.status = 'pending' assert.equal(doctorSignature.value, '') assert.equal(doctorName.value, '开方人') assert.equal(reviewerName.value, '') assert.equal(reviewerSignature.value, '') props.data.esign.status = 'signed' props.data.esign.review_signature = 'data:image/svg+xml;base64,PHN2Zz4=' assert.equal(reviewerSignature.value, '') assert.equal(reviewerName.value, '测试药师') }) test('the slip reloads a newly verified physician seal once from prescription detail', async () => { const requests = [] const { updatePrescriptionSlipEsign } = loadModule('utils/prescription-esign.ts', { '@/api/tcm': { prescriptionDetail: async ({ id }) => { requests.push(id) return { id, doctor_signature: 'verified seal' } } } }) const signed = status({ status: 'signed', can_sign: false, can_download: true }) const slip = { id: 17, esign: status(), doctor_signature: 'old signature' } const refreshed = updatePrescriptionSlipEsign(slip, signed) assert.equal(slip.esign, signed) assert.equal(slip.doctor_signature, '') await refreshed assert.equal(slip.doctor_signature, 'verified seal') await updatePrescriptionSlipEsign(slip, signed) assert.deepEqual(requests, [17]) }) 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), reissueContext: vue.ref(null), 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], /处方草稿已保存/) }) test('list upload can retry and opens signing without exposing audit to the pharmacist', async () => { const requests = [] const messages = [] const opened = [] const row = { id: 17, audit_status: 0, review_submitted_at: 0, can_submit_for_review: true, can_review_prescription: false, esign: status({ awaiting_upload: true, can_sign: false }) } const drawer = { ...row } const { pendingPrescriptionReviewLabel } = loadModule('utils/prescription-esign.ts', { '@/api/tcm': {} }) const globals = { pager: { lists: [row] }, slipView: vue.ref(drawer), uploadingPrescriptionId: vue.ref(0), getLists: async () => {}, handleView: async (rx) => { opened.push(rx.id) }, prescriptionSubmitForReview: async (params) => { requests.push(params) if (requests.length === 1) throw new Error('temporary network error') return { review_submitted_at: 1760000000, can_submit_for_review: false } }, feedback: { msgSuccess: (message) => messages.push(message) } } const { submitPrescriptionForReview, canOpenPrescriptionAudit } = pageDeclarations( 'views/consumer/prescription/index.vue', ['isPendingPrescriptionAudit', 'canOpenPrescriptionAudit', 'submitPrescriptionForReview'], globals ) assert.equal(canOpenPrescriptionAudit(row), false) assert.equal(pendingPrescriptionReviewLabel(row), '待上传') await submitPrescriptionForReview({ ...row, can_submit_for_review: false }) assert.equal(requests.length, 0) await submitPrescriptionForReview(row) assert.equal(canOpenPrescriptionAudit(row), false) assert.equal(globals.uploadingPrescriptionId.value, 0) await submitPrescriptionForReview(row) assert.deepEqual(requests, [{ id: 17 }, { id: 17 }]) assert.equal(canOpenPrescriptionAudit(row), false) assert.equal(canOpenPrescriptionAudit(globals.slipView.value), false) assert.equal(pendingPrescriptionReviewLabel(row), '待医师签署') const verified = { ...row, can_review_prescription: true, esign: { ...row.esign, status: 'signed', can_review_prescription: true } } assert.equal(canOpenPrescriptionAudit(verified), true) assert.equal(pendingPrescriptionReviewLabel(verified), '待审核') assert.equal(canOpenPrescriptionAudit({ ...verified, void_status: 1 }), false) assert.equal(row.can_submit_for_review, false) assert.equal(globals.slipView.value.esign.review_submitted_at, 1760000000) assert.deepEqual(opened, [17]) assert.match(messages[0], /请完成医师签署/) }) test('issued prescriptions can be voided in any review state when the server allows it', async () => { const calls = [] const messages = [] let cancel = true let refreshes = 0 const row = { id: 17, audit_status: '0', can_void: true, can_submit_for_review: true } const globals = { voidingPrescriptionId: vue.ref(0), prescriptionVoid: async (params) => { calls.push(params) if (calls.length === 1) throw new Error('temporary failure') }, getLists: async () => { refreshes++ }, feedback: { confirm: async () => { if (cancel) throw new Error('cancel') }, msgSuccess: (message) => messages.push(message) } } const { canVoidPrescription, voidPendingPrescription } = pageDeclarations( 'views/consumer/prescription/index.vue', ['canVoidPrescription', 'voidPendingPrescription'], globals ) assert.equal(canVoidPrescription(row), true) // 审核通过(药师已签署)后仍可作废;以服务端 can_void 为准。 assert.equal(canVoidPrescription({ ...row, audit_status: 1 }), true) for (const other of [{ void_status: 1 }, { can_void: false }]) { await voidPendingPrescription({ ...row, ...other }) } await voidPendingPrescription(row) assert.deepEqual(calls, []) cancel = false await voidPendingPrescription(row) assert.equal(canVoidPrescription(row), true) await Promise.all([voidPendingPrescription(row), voidPendingPrescription(row)]) assert.deepEqual(calls, [{ id: 17 }, { id: 17 }]) assert.equal(row.void_status, 1) assert.equal(row.can_submit_for_review, false) assert.equal(canVoidPrescription(row), false) assert.equal(refreshes, 1) assert.deepEqual(messages, ['处方已作废']) }) test('issued prescriptions reopen a voided record as a new prescription with fresh signature and review', async () => { const source = { id: 17, sn: 'RX0017', visit_no: 'RX0017', void_status: '1', creator_id: '8', prescription_date: '2025-01-01', prescription_type: '饮片', dosage_amount: '120', diagnosis_id: 18, appointment_id: 19, patient_id: 20, phone: 'test', patient_name: '虚构测试', clinical_diagnosis: '虚构诊断', herbs: [{ name: '测试药材', dosage: 1, formula_type: '辅方' }], dietary_taboo: ['测试项目'], prescription_name: '测试处方', case_record: { archive: true }, audit_status: 2, doctor_signature: 'data:image/png;base64,old', esign: status({ status: 'voided' }), prescription_order_id: 21, is_shared: 1, visible_role_ids: [22] } const newEsign = status({ status: 'pending', awaiting_upload: true }) const view = [] const saves = [] const reads = [] const warnings = [] const form = { aux_usage: {} } let permitted = true let detail = { ...source, void_status: 0 } const globals = { userStore: { userInfo: { id: 8, name: '虚构医师' } }, hasPermission: () => permitted, showEdit: vue.ref(false), editMode: vue.ref('view'), slipView: vue.ref(null), editForm: form, reissueContext: vue.ref(null), reissuingPrescriptionId: vue.ref(0), isLoadingData: vue.ref(false), editingWasVoid: vue.ref(true), editingWasRejected: vue.ref(true), nextTick: vue.nextTick, formRef: vue.ref({ clearValidate() {}, validate: async () => true }), loadEsignConfig: async () => true, scheduleEditSignatureInit() {}, clearRxLinkedOrderHint() {}, dayRangeStrings: () => ({ start: '2026-11-23 00:00:00' }), defaultAuxUsage: () => ({}), normalizeAuxUsageForm: () => ({}), normalizeSlipHerbs: (herbs) => herbs.map((herb) => ({ ...herb })), submitLoading: vue.ref(false), esignReady: vue.ref(true), esignEnabled: vue.ref(true), herbValidationLabel: () => '药材', prescriptionDetail: async (params) => { reads.push(params); return detail }, prescriptionAdd: async (params) => { saves.push(params); return { id: 23, esign: newEsign } }, prescriptionEdit: async () => assert.fail('reissue edited original prescription'), handleView: async (row) => view.push(row), getLists() {}, feedback: { msgSuccess() {}, msgWarning: (message) => warnings.push(message), msgError: assert.fail } } const { canReissuePrescription, handleReissue, handleSubmit, handleAdd } = pageDeclarations( 'views/consumer/prescription/index.vue', ['resetForm', 'fillPrescriptionContents', 'openNewPrescription', 'handleAdd', 'canReissuePrescription', 'handleReissue', 'handleSubmit'], globals ) assert.equal(canReissuePrescription(source), true) // 他人所开、已作废的处方也可由有开方权限的账号重新开方。 assert.equal(canReissuePrescription({ ...source, creator_id: 9 }), true) await handleReissue({ ...source, void_status: 0 }) permitted = false await handleReissue(source) assert.deepEqual(reads, []) permitted = true await handleReissue(source) assert.equal(globals.showEdit.value, false) assert.equal(warnings.length, 1) detail = source await Promise.all([handleReissue(source), handleReissue(source)]) assert.deepEqual(reads, [{ id: 17 }, { id: 17 }]) assert.equal(globals.showEdit.value, true) assert.equal(globals.editMode.value, 'add') assert.equal(form.id, 0) assert.equal(form.doctor_signature, '') assert.equal(form.prescription_date, '2026-11-23') assert.equal(form.dosage_amount, 120) assert.deepEqual(form.herbs, source.herbs) form.dietary_taboo.push('本次新增') assert.deepEqual(source.dietary_taboo, ['测试项目']) await handleSubmit() const [saved] = saves assert.equal(saved.audit_status, 0) assert.equal(saved.diagnosis_id, 18) assert.equal(saved.appointment_id, 19) assert.equal(saved.patient_id, 20) assert.equal(saved.phone, 'test') assert.equal(saved.prescription_name, '测试处方') assert.equal(saved.case_record, undefined) assert.equal(saved.doctor_signature, '') assert.deepEqual(saved.visible_role_ids, []) for (const field of ['sn', 'visit_no', 'void_status', 'esign', 'prescription_order_id']) { assert.equal(Object.hasOwn(saved, field), false) } assert.equal(view[0].id, 23) assert.deepEqual(view[0].esign, newEsign) handleAdd() assert.equal(globals.reissueContext.value, null) }) test('opening a submitted consumer audit clears previous evidence and still needs pharmacist signature for approval', async () => { const requests = [] const { canApprovePrescriptionEsign } = loadModule('utils/prescription-esign.ts', { '@/api/tcm': {} }) const signed = status({ status: 'signed', can_download: true, can_sign: false }) const globals = { computed: vue.computed, canApprovePrescriptionEsign, auditEsign: vue.ref(signed), auditReview: vue.ref({ can_approve: true }), auditTargetId: vue.ref(16), auditRemark: vue.ref(''), auditLoading: vue.ref(false), auditDialogVisible: vue.ref(false), prescriptionAudit: async (params) => { requests.push(params) }, showEdit: vue.ref(false), slipView: vue.ref(null), getLists: () => {}, feedback: { msgSuccess: () => {}, msgError: () => {}, msgWarning: () => {} } } const { openAuditDialog, onAuditEsignStatusChange, submitAudit } = pageDeclarations( 'views/consumer/prescription/index.vue', ['canApproveAudit', 'isPendingPrescriptionAudit', 'canOpenPrescriptionAudit', 'openAuditDialog', 'onAuditEsignStatusChange', 'submitAudit'], globals ) openAuditDialog({ id: 17, audit_status: 0, review_submitted_at: 0 }) assert.equal(globals.auditDialogVisible.value, false) openAuditDialog({ id: 17, audit_status: 0, review_submitted_at: 1760000000, can_review_prescription: false }) assert.equal(globals.auditDialogVisible.value, false) openAuditDialog({ id: 17, audit_status: 0, review_submitted_at: 1760000000, can_review_prescription: true }) assert.equal(globals.auditEsign.value, null) assert.equal(globals.auditReview.value, null) await submitAudit('approve') onAuditEsignStatusChange(status()) await submitAudit('approve') assert.deepEqual(requests, []) globals.auditRemark.value = '处方需修正' await submitAudit('reject') openAuditDialog({ id: 18, audit_status: 0, review_submitted_at: 1760000000, can_review_prescription: true }) onAuditEsignStatusChange(signed) await submitAudit('approve') assert.equal(requests.length, 1, 'a single verified doctor signature cannot approve') globals.auditReview.value = { can_approve: true } await submitAudit('approve') assert.deepEqual(requests, [ { id: 17, action: 'reject', remark: '处方需修正' }, { id: 18, action: 'approve', remark: '' } ]) }) for (const filename of [ 'views/consumer/prescription/order_list.vue', 'views/consumer/prescription/order_list_h5.vue', 'views/first_visit/my_patients/components/OrderActionHost.vue' ]) { test(`${filename}: gates prescription approval separately from payment approval`, async () => { const requests = [] const approvePrescription = async (params) => requests.push(['prescription', params]) const approvePayment = async (params) => requests.push(['payment', params]) const { canApprovePrescriptionEsign } = loadModule('utils/prescription-esign.ts', { '@/api/tcm': {} }) const signed = status({ status: 'signed', can_download: true, can_sign: false }) const globals = { computed: vue.computed, canApprovePrescriptionEsign, auditEsign: vue.ref(signed), auditReview: vue.ref({ can_approve: true }), auditTargetId: vue.ref(16), auditRemark: vue.ref(''), auditKind: vue.ref('prescription'), auditSubmitting: vue.ref(false), auditVisible: vue.ref(false), auditRowData: vue.ref(null), detailVisible: vue.ref(false), detailDrawerRef: vue.ref(null), prescriptionOrderAuditPrescription: approvePrescription, prescriptionOrderAuditPayment: approvePayment, myPatientOrderAuditPrescription: approvePrescription, myPatientOrderAuditPayment: approvePayment, actionRow: vue.ref({}), submitting: vue.ref(false), changed: async () => {}, getLists: () => {}, feedback: { msgSuccess: () => {} } } const isFirstVisit = filename.includes('OrderActionHost') const open = isFirstVisit ? 'openAction' : 'openAudit' const helpers = isFirstVisit ? [] : ['canRxAudit'] const handlers = pageDeclarations(filename, ['canApproveAudit', ...helpers, open, 'submitAudit'], globals) const row = { id: 17, prescription_id: 51, prescription_audit_status: 0, fulfillment_status: 1 } const prescriptionAction = isFirstVisit ? 'audit_prescription' : 'prescription' handlers[open]({ ...row, can_review_prescription: false }, prescriptionAction) assert.equal(globals.auditVisible.value, false) handlers[open]({ ...row, can_review_prescription: true }, prescriptionAction) await handlers.submitAudit('approve') assert.deepEqual(requests, []) globals.auditEsign.value = signed await handlers.submitAudit('approve') assert.deepEqual(requests, []) globals.auditReview.value = { can_approve: true } await handlers.submitAudit('approve') handlers[open]({ id: 17, prescription_id: 51 }, isFirstVisit ? 'audit_payment' : 'payment') assert.equal(globals.auditEsign.value, null) await handlers.submitAudit('approve') assert.deepEqual(requests, [ ['prescription', { id: 17, action: 'approve', remark: '' }], ['payment', { id: 17, action: 'approve', remark: '' }] ]) }) } for (const filename of [ 'components/EsignPrescriptionPanel.vue', 'components/EsignReviewPanel.vue', 'components/prescription-slip/index.vue', 'components/tcm-prescription/index.vue', 'views/consumer/prescription/index.vue', 'views/consumer/prescription/order_list.vue', 'views/consumer/prescription/order_list_h5.vue', 'views/first_visit/my_patients/components/OrderActionHost.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, []) }) }