This commit is contained in:
Your Name
2026-11-14 15:19:59 +08:00
parent 08892f4270
commit a5588f89b1
476 changed files with 5768 additions and 491 deletions
@@ -0,0 +1,227 @@
const assert = require('node:assert/strict')
const fs = require('node:fs')
const path = require('node:path')
const test = require('node:test')
const ts = require('typescript')
const vue = require('vue')
const { renderToString } = require('@vue/server-renderer')
const { parse, compileScript, compileTemplate } = require('@vue/compiler-sfc')
const root = path.resolve(__dirname, '../src')
const signature = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIHWP4z8DwHwAFgAI/ScLbtAAAAABJRU5ErkJggg=='
const oldSignature = 'data:image/png;base64,old-order-signature'
const signedOrder = () => ({
id: 42, prescription_id: 8, fulfillment_status: 1, prescription_audit_status: 1,
prescription_audit_signature: signature, prescription_audit_signed_name: '本单药师',
prescription_audit_signed_by: 7, prescription_audit_signed_at: 1794553200
})
const basePrescription = () => ({ id: 8, doctor_name: '开方医师', patient_name: '张某', herbs: [], prescription_type: '饮片' })
const deferred = () => {
let resolve
const promise = new Promise(yes => { resolve = yes })
return { promise, resolve }
}
function loadModule(source, imports) {
const output = ts.transpileModule(source, { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS, esModuleInterop: true } }).outputText
const module = { exports: {} }
new Function('require', 'module', 'exports', output)(imports, module, module.exports)
return module.exports
}
const utils = loadModule(fs.readFileSync(path.join(root, 'components/prescription-slip/utils.ts'), 'utf8'), () => { throw new Error('unexpected dependency') })
const slipFile = path.join(root, 'components/prescription-slip/index.vue')
const slipDescriptor = parse(fs.readFileSync(slipFile, 'utf8'), { filename: slipFile }).descriptor
const slipScript = compileScript(slipDescriptor, { id: 'signature-slip-render', inlineTemplate: true })
const Slip = loadModule(slipScript.content, name => {
if (name === 'vue') return vue
if (name === './utils') return utils
throw new Error(`unexpected dependency: ${name}`)
}).default
async function renderedSlip(data, variant) {
// 真正执行 PrescriptionSlip.vue 的编译 render;两个联次均使用该 DOM 导出图片/PDF。
return renderToString(vue.createSSRApp({ render: () => vue.h(Slip, { data, variant }) }))
}
function preview(page, options = {}) {
const calls = [], errors = []
let order = options.order ?? signedOrder()
let prescription = options.prescription ?? basePrescription()
const request = {
async get({ url, params }) {
calls.push({ url, params })
if (url === '/tcm.prescription/detail') return typeof prescription === 'function' ? prescription(params) : { data: prescription }
if (url === '/tcm.prescriptionOrder/detail') return typeof order === 'function' ? order(params) : { data: order }
throw new Error(`Unexpected URL ${url}`)
},
async post({ url, params }) {
calls.push({ url, params })
if (url === '/tcm.prescriptionOrder/auditPrescription') {
order = { ...signedOrder(), prescription_audit_status: params.action === 'approve' ? 1 : 2, prescription_audit_signature: params.signature }
return {}
}
if (url === '/tcm.prescriptionOrder/revokeRxAudit') {
order = { ...signedOrder(), prescription_audit_status: 0, prescription_audit_signature: '', prescription_audit_signed_name: '' }
return {}
}
throw new Error(`Unexpected URL ${url}`)
}
}
// 使用真实 API functions 和真实共享 loader,只有最底层网络 transport 被替换。
const api = loadModule(fs.readFileSync(path.join(root, 'api/tcm.ts'), 'utf8'), name => {
assert.equal(name, '@/utils/request')
return request
})
const loader = loadModule(fs.readFileSync(path.join(root, 'views/consumer/prescription/components/order-prescription-slip.ts'), 'utf8'), name => {
assert.equal(name, '@/api/tcm')
return api
})
const filename = path.join(root, 'views/consumer/prescription', page)
const { descriptor, errors: parseErrors } = parse(fs.readFileSync(filename, 'utf8'), { filename })
assert.deepEqual(parseErrors, [])
const script = compileScript(descriptor, { id: page })
const template = compileTemplate({ source: descriptor.template.content, filename, id: page, compilerOptions: { bindingMetadata: script.bindings } })
assert.deepEqual(template.errors, [])
const ast = ts.createSourceFile(filename + '.ts', descriptor.scriptSetup.content, 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 declaration of node.declarationList.declarations) declarations.set(declaration.name.getText(ast), `${node.declarationList.flags & ts.NodeFlags.Const ? 'const' : 'let'} ${declaration.getText(ast)}`)
}
}
const names = [
'prescriptionViewVisible', 'prescriptionViewLoading', 'prescriptionViewData', 'prescriptionViewOrderId', 'prescriptionViewRequestId',
'prescriptionTabType', 'openPrescriptionView', 'resetPrescriptionView', 'refreshOpenPrescriptionView',
'auditVisible', 'auditKind', 'auditTargetId', 'auditRowData', 'auditRemark', 'auditSignature', 'auditSession', 'auditSubmitting',
'openAudit', 'resetAuditInput', 'submitAudit', 'confirmRevokeRxAudit'
]
const globals = {
ref: vue.ref, ...loader,
prescriptionOrderAuditPrescription: api.prescriptionOrderAuditPrescription,
prescriptionOrderAuditPayment: api.prescriptionOrderAuditPayment,
prescriptionOrderRevokeRxAudit: api.prescriptionOrderRevokeRxAudit,
prescriptionOrderDetail: api.prescriptionOrderDetail,
detailDrawerRef: vue.ref({ refreshIfCurrent: async () => {} }),
// 父详情/列表故意保持旧快照,验证预览不从它恢复签名。
detailData: vue.ref({ id: 42, prescription_id: 8, prescription_audit_status: 0 }), detailVisible: vue.ref(false),
slipAuxLibraryName: vue.ref(''), resolveSlipAuxLibraryName: async () => '',
ElMessageBox: { confirm: async () => {} }, getLists() {}, fetchLogs: async () => {},
feedback: { msgWarning: message => errors.push(message), msgError: message => errors.push(message), msgSuccess() {} }
}
for (const name of names) assert.ok(declarations.has(name), `${page}: missing ${name}`)
const output = ts.transpileModule(names.map(name => declarations.get(name)).join('\n'), { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS } }).outputText
const state = new Function(...Object.keys(globals), `${output}\nreturn { ${names.join(', ')} }`)(...Object.values(globals))
return { state, calls, errors, setOrder: value => { order = value }, setPrescription: value => { prescription = value } }
}
for (const page of ['order_list.vue', 'order_list_h5.vue']) {
test(`${page}: real API -> preview -> both rendered slips show order signature when prescription response has no audit fields`, async () => {
const { state, calls } = preview(page)
await state.openPrescriptionView({ id: 42, prescription_id: 8, prescription_audit_status: 0 })
assert.deepEqual(calls, [
{ url: '/tcm.prescription/detail', params: { id: 8, prescription_order_id: 42 } },
{ url: '/tcm.prescriptionOrder/detail', params: { id: 42 } }
])
for (const variant of ['internal', 'user']) {
const html = await renderedSlip(state.prescriptionViewData.value, variant)
assert.match(html, /<img[^>]*alt="药师签名"/)
assert.ok(html.includes(`src="${signature}"`))
assert.equal(html.includes('本单药师'), false)
assert.ok(html.indexOf('开方医师') < html.indexOf('药师签名'))
}
})
test(`${page}: fresh order replaces missing or wrong signature fields from prescription and list snapshots`, async () => {
const stale = { ...basePrescription(), prescription_audit_status: 1, prescription_audit_signature: oldSignature, prescription_audit_signed_name: '别单旧药师', prescription_audit_signed_by: 99 }
const { state } = preview(page, { prescription: stale })
await state.openPrescriptionView({ ...stale, id: 42, prescription_id: 8 })
assert.equal(state.prescriptionViewData.value.prescription_audit_signature, signature)
assert.equal(state.prescriptionViewData.value.prescription_audit_signed_by, 7)
const html = await renderedSlip(state.prescriptionViewData.value, 'internal')
assert.equal(html.includes('本单药师'), false)
assert.equal(html.includes('别单旧药师'), false)
assert.equal(html.includes(oldSignature), false)
})
test(`${page}: pending, rejected, cancelled and refunded fresh orders remove stale pharmacist images from both slips`, async () => {
const stale = { ...basePrescription(), ...signedOrder(), id: 8 }
for (const order of [
{ ...signedOrder(), prescription_audit_status: 0 },
{ ...signedOrder(), prescription_audit_status: 2 },
{ ...signedOrder(), fulfillment_status: 4 },
{ ...signedOrder(), fulfillment_status: 10 },
{ ...signedOrder(), prescription_audit_signature: '' }
]) {
const { state } = preview(page, { order, prescription: stale })
await state.openPrescriptionView({ ...signedOrder(), prescription_id: 8 })
assert.equal(state.prescriptionViewData.value.prescription_audit_signature, '')
for (const variant of ['internal', 'user']) {
const html = await renderedSlip(state.prescriptionViewData.value, variant)
assert.equal(html.includes('alt="药师签名"'), false)
assert.equal(html.includes('本单药师'), false)
}
}
})
test(`${page}: completing an audit and revoking it refresh an already-open prescription preview`, async () => {
const { state, setPrescription } = preview(page, { order: { ...signedOrder(), prescription_audit_status: 0, prescription_audit_signature: '' } })
await state.openPrescriptionView({ id: 42, prescription_id: 8 })
assert.equal(state.prescriptionViewData.value.prescription_audit_signature, '')
state.prescriptionTabType.value = 'user'
state.openAudit({ id: 42 }, 'prescription')
state.auditSignature.value = signature
await state.submitAudit('approve')
assert.equal(state.prescriptionViewData.value.prescription_audit_signature, signature)
assert.equal(state.prescriptionTabType.value, 'user')
assert.match(await renderedSlip(state.prescriptionViewData.value, 'user'), /<img[^>]*alt="药师签名"/)
setPrescription({ ...basePrescription(), ...signedOrder(), id: 8 })
await state.confirmRevokeRxAudit({ id: 42 })
assert.equal(state.prescriptionViewData.value.prescription_audit_signature, '')
assert.equal((await renderedSlip(state.prescriptionViewData.value, 'user')).includes('alt="药师签名"'), false)
})
test(`${page}: another order's detail and failed detail loads cannot borrow a cached signature`, async () => {
for (const order of [{ ...signedOrder(), id: 99 }, async () => { throw new Error('订单加载失败') }]) {
const { state, errors } = preview(page, { order, prescription: { ...basePrescription(), ...signedOrder(), id: 8 } })
state.prescriptionViewData.value = { ...basePrescription(), ...signedOrder(), id: 8 }
await state.openPrescriptionView({ id: 42, prescription_id: 8 })
assert.equal(state.prescriptionViewData.value, null)
assert.equal(state.prescriptionViewVisible.value, false)
assert.equal(errors.length, 1)
}
})
test(`${page}: a slower previous order response cannot overwrite the newly opened or closed preview`, async () => {
const slow = deferred()
const { state } = preview(page, {
prescription: params => params.id === 8 ? slow.promise : { ...basePrescription(), id: params.id },
order: params => ({ ...signedOrder(), id: params.id, prescription_id: params.id === 42 ? 8 : 9, prescription_audit_signed_name: `药师${params.id}` })
})
const first = state.openPrescriptionView({ id: 42, prescription_id: 8 })
await state.openPrescriptionView({ id: 43, prescription_id: 9 })
slow.resolve(basePrescription())
await first
assert.equal(state.prescriptionViewData.value.prescription_order_id, 43)
assert.equal(state.prescriptionViewData.value.prescription_audit_signed_name, '药师43')
const pending = state.openPrescriptionView({ id: 43, prescription_id: 9 })
state.resetPrescriptionView()
await pending
assert.equal(state.prescriptionViewData.value, null)
})
test(`${page}: changed prescription association reloads the actual current prescription`, async () => {
const { state, calls } = preview(page, {
order: { ...signedOrder(), prescription_id: 9 },
prescription: params => {
if (params.id === 8) throw new Error('处方与订单关联不匹配')
return { ...basePrescription(), id: params.id }
}
})
await state.openPrescriptionView({ id: 42, prescription_id: 8 })
assert.equal(state.prescriptionViewData.value.id, 9)
assert.equal(state.prescriptionViewData.value.prescription_audit_signature, signature)
assert.deepEqual(calls.filter(call => call.url === '/tcm.prescription/detail').map(call => call.params.id), [8, 9])
})
}
@@ -0,0 +1,311 @@
const assert = require('node:assert/strict')
const fs = require('node:fs')
const path = require('node:path')
const test = require('node:test')
const ts = require('typescript')
const vue = require('vue')
const { parse, compileScript, compileTemplate } = require('@vue/compiler-sfc')
const root = path.resolve(__dirname, '..')
const signature = 'data:image/png;base64,c2lnbmF0dXJl'
const deferred = () => {
let resolve, reject
const promise = new Promise((yes, no) => { resolve = yes; reject = no })
return { promise, resolve, reject }
}
function component(relative) {
const filename = path.join(root, 'src', relative)
const { descriptor, errors } = parse(fs.readFileSync(filename, 'utf8'), { filename })
assert.deepEqual(errors, [])
const script = compileScript(descriptor, { id: relative })
const template = compileTemplate({ source: descriptor.template.content, filename, id: relative, compilerOptions: { bindingMetadata: script.bindings } })
assert.deepEqual(template.errors, [])
return { filename, descriptor, script }
}
function handlers(relative, names, globals, watches = '') {
const { filename, descriptor } = component(relative)
const ast = ts.createSourceFile(filename + '.ts', descriptor.scriptSetup.content, 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 declaration of node.declarationList.declarations) declarations.set(declaration.name.getText(ast), `${node.declarationList.flags & ts.NodeFlags.Const ? 'const' : 'let'} ${declaration.getText(ast)}`)
}
}
for (const name of names) assert.ok(declarations.has(name), `${relative}: missing ${name}`)
const expressions = watches ? ast.statements.filter(node => ts.isExpressionStatement(node) && node.getText(ast).startsWith('watch(') && node.getText(ast).includes(watches)).map(node => node.getText(ast)) : []
const compiled = ts.transpileModule([...names.map(name => declarations.get(name)), ...expressions].join('\n'), { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS } }).outputText
return new Function(...Object.keys(globals), `${compiled}\nreturn { ${names.join(', ')} }`)(...Object.values(globals))
}
for (const page of ['views/consumer/prescription/order_list.vue', 'views/consumer/prescription/order_list_h5.vue', 'views/first_visit/my_patients/components/OrderActionHost.vue']) {
const host = page.includes('OrderActionHost')
function setup(save = async () => {}) {
const calls = [], errors = [], refreshed = []
const names = ['auditVisible', 'auditKind', 'auditRemark', 'auditSignature', 'auditSession', 'resetAuditInput', 'submitAudit']
names.push(...(host ? ['actionRow', 'submitting', 'openAction', 'changed'] : ['auditTargetId', 'auditRowData', 'auditSubmitting', 'openAudit']))
const rx = async payload => { calls.push(['rx', payload]); await save(payload) }
const pay = async payload => { calls.push(['pay', payload]); await save(payload) }
const state = handlers(page, names, {
ref: vue.ref,
feedback: { msgError: message => errors.push(message), msgSuccess() {} },
prescriptionOrderAuditPrescription: rx, prescriptionOrderAuditPayment: pay,
myPatientOrderAuditPrescription: rx, myPatientOrderAuditPayment: pay,
detailDrawerRef: vue.ref({ refreshIfCurrent: async id => refreshed.push(id) }),
detailVisible: vue.ref(false), detailData: vue.ref(null), getLists() {}, emit() {}, refreshOpenPrescriptionView: async () => {}
})
const open = (id = 42, kind = 'prescription') => host ? state.openAction({ id }, `audit_${kind}`) : state.openAudit({ id }, kind)
return { state, calls, errors, refreshed, open }
}
test(`${page}: blank signature blocks approve and reject even via direct handler`, async () => {
const { state, calls, open } = setup()
open()
state.auditRemark.value = '原因'
for (const blank of ['', ' ']) {
state.auditSignature.value = blank
await state.submitAudit('approve')
await state.submitAudit('reject')
}
assert.deepEqual(calls, [])
assert.equal(state.auditVisible.value, true)
})
test(`${page}: both audit results carry a fresh signature; reject still needs a reason`, async () => {
const { state, calls, refreshed, open } = setup()
open()
state.auditSignature.value = signature
await state.submitAudit('reject')
assert.deepEqual(calls, [])
state.auditRemark.value = ' 需重新核对 '
await state.submitAudit('reject')
assert.deepEqual(calls[0], ['rx', { id: 42, action: 'reject', remark: '需重新核对', signature }])
assert.equal(state.auditSignature.value, '')
open(43)
assert.equal(state.auditSignature.value, '')
state.auditSignature.value = signature
await state.submitAudit('approve')
assert.deepEqual(calls[1], ['rx', { id: 43, action: 'approve', remark: '', signature }])
if (!page.includes('h5')) assert.deepEqual(refreshed, [42, 43])
})
test(`${page}: payment auditing neither requires nor sends a signature`, async () => {
const { state, calls, open } = setup()
open(4, 'payment')
state.auditSignature.value = signature
await state.submitAudit('approve')
open(5, 'payment')
state.auditRemark.value = '支付信息不符'
await state.submitAudit('reject')
assert.deepEqual(calls, [
['pay', { id: 4, action: 'approve', remark: '' }],
['pay', { id: 5, action: 'reject', remark: '支付信息不符' }]
])
})
test(`${page}: closing, reopening and switching orders discard the prior signature`, () => {
const { state, open } = setup()
open()
state.auditSignature.value = signature
const firstSession = state.auditSession.value
open(43)
assert.equal(state.auditSignature.value, '')
assert.ok(state.auditSession.value > firstSession)
state.auditSignature.value = signature
state.auditVisible.value = false
state.resetAuditInput()
assert.equal(state.auditSignature.value, '')
open(42)
assert.equal(state.auditSignature.value, '')
})
test(`${page}: a pending audit cannot duplicate or change target; failure retains the signature`, async () => {
const saving = deferred()
const { state, calls, open } = setup(() => saving.promise)
open()
state.auditSignature.value = signature
const submission = state.submitAudit('approve')
await state.submitAudit('approve')
open(99, 'payment')
state.resetAuditInput()
assert.equal(calls.length, 1)
assert.equal(state.auditKind.value, 'prescription')
assert.equal(host ? state.actionRow.value.id : state.auditTargetId.value, 42)
saving.reject(new Error('network'))
await submission
assert.equal(state.auditSignature.value, signature)
assert.equal(state.auditVisible.value, true)
assert.equal(host ? state.submitting.value : state.auditSubmitting.value, false)
})
}
function logSetup(save = async () => {}) {
const calls = [], errors = []
const state = handlers('views/consumer/prescription/components/PrescriptionOrderDetailDrawer.vue', [
'addLogVisible', 'addLogSaving', 'addLogFormRef', 'addLogSignature', 'addLogSession', 'addLogForm',
'requiresAddLogSignature', 'resetAddLogForm', 'openAddLogDialog', 'submitAddLog'
], {
ref: vue.ref, reactive: vue.reactive, computed: vue.computed, watch: vue.watch,
detailData: vue.ref({ id: 42, prescription_audit_status: 1, prescription_audit_signature: signature }),
canSetRxAuditOnAddLog: vue.ref(true), canSetPayAuditOnAddLog: vue.ref(true),
feedback: { msgError: message => errors.push(message), msgSuccess() {} },
prescriptionOrderAddLog: async payload => { calls.push(payload); await save() },
refresh: async () => {}, emit() {}
}, 'addLogForm.prescription_audit_status')
state.addLogFormRef.value = { validate: async () => true, clearValidate() {} }
state.openAddLogDialog()
state.addLogForm.summary = '补充说明'
return { state, calls, errors }
}
test('manual log explicitly setting either terminal status requires a new signature, including unchanged approval', async () => {
for (const status of [1, 2]) {
const { state, calls } = logSetup()
state.addLogForm.prescription_audit_status = status
await vue.nextTick()
await state.submitAddLog()
assert.deepEqual(calls, [])
state.addLogSignature.value = signature
await state.submitAddLog()
assert.equal(calls[0].signature, signature)
assert.equal(calls[0].prescription_audit_status, status)
}
})
test('plain logs, payment-only changes and reset to pending do not require or send signatures', async () => {
for (const status of ['', 0]) {
const { state, calls } = logSetup()
state.addLogForm.prescription_audit_status = status
state.addLogForm.payment_slip_audit_status = 1
await state.submitAddLog()
assert.equal(calls.length, 1)
assert.equal('signature' in calls[0], false)
}
})
test('manual log cannot reuse a signature after status change or reopen; failed saves retain it', async () => {
const { state, calls } = logSetup(async () => { throw new Error('network') })
state.addLogForm.prescription_audit_status = 1
await vue.nextTick()
state.addLogSignature.value = signature
state.addLogForm.prescription_audit_status = 2
await vue.nextTick()
assert.equal(state.addLogSignature.value, '')
state.addLogSignature.value = signature
await state.submitAddLog()
assert.equal(calls.length, 1)
assert.equal(state.addLogSignature.value, signature)
assert.equal(state.addLogVisible.value, true)
state.openAddLogDialog()
assert.equal(state.addLogSignature.value, '')
})
test('manual log locks submission before async form validation, preventing duplicates', async () => {
const validation = deferred()
const { state, calls } = logSetup()
state.addLogFormRef.value.validate = () => validation.promise
const submit = state.submitAddLog()
await state.submitAddLog()
state.openAddLogDialog()
assert.equal(state.addLogSaving.value, true)
validation.resolve(true)
await submit
assert.equal(calls.length, 1)
})
function loadModule(source, imports, globals = {}) {
const compiled = ts.transpileModule(source, { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS, esModuleInterop: true } }).outputText
const module = { exports: {} }
new Function('require', 'module', 'exports', ...Object.keys(globals), compiled)(imports, module, module.exports, ...Object.values(globals))
return module.exports
}
function padSetup() {
const { script } = component('components/signature-pad/index.vue')
const mounted = [], output = [], paths = []
let observer
const props = vue.reactive({ modelValue: '', disabled: false })
const componentModule = loadModule(script.content, name => {
assert.equal(name, 'vue')
return { ...vue, onMounted: fn => mounted.push(fn), onBeforeUnmount() {} }
}, { window: { devicePixelRatio: 2 }, ResizeObserver: class { constructor(fn) { observer = fn } observe() {} disconnect() {} } })
const state = componentModule.default.setup(props, { expose() {}, emit(_event, value) { props.modelValue = value; output.push(value) } })
let width = 400
const captures = new Set()
const context = { beginPath() {}, moveTo(x, y) { paths.push(['move', x, y]) }, lineTo(x, y) { paths.push(['line', x, y]) }, stroke() {}, setTransform(...values) { paths.push(['transform', ...values]) }, fillRect() {} }
const canvas = {
getBoundingClientRect: () => ({ left: 10, top: 20, width, height: 168 }),
getContext: () => context, toDataURL: () => signature,
setPointerCapture: id => captures.add(id), hasPointerCapture: id => captures.has(id), releasePointerCapture: id => captures.delete(id)
}
state.canvasRef.value = canvas
mounted.forEach(fn => fn())
const point = (x, y, extra = {}) => ({ pointerId: 1, pointerType: 'touch', button: 0, clientX: x + 10, clientY: y + 20, ...extra })
const draw = () => { state.onPointerDown(point(20, 30)); state.onPointerMove(point(80, 60)); state.onPointerUp(point(100, 70)) }
return { state, props, output, paths, canvas, point, draw, resize: newWidth => { width = newWidth; observer() } }
}
test('signature pad rejects blank clicks and tiny motion, then emits only completed ink', async () => {
const { state, props, point, draw } = padSetup()
state.onPointerDown(point(20, 20))
state.onPointerUp(point(20, 20))
assert.equal(props.modelValue, '')
state.onPointerDown(point(20, 20))
state.onPointerMove(point(21, 21))
state.onPointerUp(point(21, 21))
assert.equal(props.modelValue, '')
draw()
await vue.nextTick()
assert.equal(props.modelValue, signature)
state.clearSignature()
await vue.nextTick()
assert.equal(props.modelValue, '')
state.onPointerDown(point(20, 20))
state.onPointerUp(point(20, 20))
assert.equal(props.modelValue, '')
})
test('signature pad ignores secondary pointers, cancels interrupted ink and respects disabled state', () => {
const { state, props, point, draw } = padSetup()
state.onPointerDown(point(20, 20))
state.onPointerMove(point(100, 100, { pointerId: 2 }))
state.onPointerUp(point(100, 100, { pointerId: 2 }))
state.onPointerCancel(point(20, 20))
assert.equal(props.modelValue, '')
draw()
props.disabled = true
state.clearSignature()
state.onPointerDown(point(20, 20))
assert.equal(props.modelValue, signature)
assert.equal(state.drawing.value, false)
})
test('signature pad maps CSS coordinates once at high DPR and preserves strokes on resize', () => {
const { canvas, paths, draw, resize, props } = padSetup()
draw()
assert.equal(canvas.width, 800)
assert.equal(canvas.height, 336)
assert.ok(paths.some(parts => parts[0] === 'line' && parts[1] === 80 && parts[2] === 60))
resize(200)
assert.equal(canvas.width, 400)
assert.ok(paths.some(parts => parts[0] === 'line' && parts[1] === 40 && parts[2] === 60))
assert.equal(props.modelValue, signature)
})
test('prescription slip only displays the pharmacist signature for the current signed approval', () => {
const source = fs.readFileSync(path.join(root, 'src/components/prescription-slip/utils.ts'), 'utf8')
const { rxPharmacistSignature } = loadModule(source, () => { throw new Error('unexpected import') })
const signed = { prescription_audit_status: 1, prescription_audit_signature: signature, prescription_audit_signed_name: ' 李药师 ', doctor_name: '王医生' }
assert.equal(rxPharmacistSignature(signed), signature)
assert.equal(rxPharmacistSignature({ ...signed, prescription_audit_status: '1' }), signature)
for (const status of [0, 2, null, undefined]) assert.equal(rxPharmacistSignature({ ...signed, prescription_audit_status: status }), '')
assert.equal(rxPharmacistSignature({ ...signed, prescription_audit_signature: '' }), '')
assert.equal(rxPharmacistSignature({ ...signed, prescription_audit_signed_name: '' }), signature)
assert.equal(rxPharmacistSignature({ doctor_name: '王医生' }), '')
component('components/prescription-slip/index.vue')
component('views/consumer/prescription/components/AuditSignatureRecord.vue')
})
// 处方预览的 API -> handler -> 实际 Vue 图片渲染回归见 prescription-audit-signature-display.test.cjs。