340 lines
17 KiB
JavaScript
340 lines
17 KiB
JavaScript
import test from 'node:test'
|
||
import assert from 'node:assert/strict'
|
||
import fs from 'node:fs'
|
||
import ts from 'typescript'
|
||
import { computed, effectScope, nextTick, reactive, ref, watch } from 'vue'
|
||
import { createRequestScope } from '../src/utils/requestScope.ts'
|
||
import { submitReturnWithConfirmation, getReturnCompletionText } from '../src/utils/returnConfirmation.ts'
|
||
import { canSubmitBorrowScan } from '../src/views/borrow/borrowScanState.ts'
|
||
import { canSubmitReturnScan } from '../src/views/borrow/returnScanState.ts'
|
||
|
||
const deferred = () => {
|
||
let resolve
|
||
let reject
|
||
const promise = new Promise((done, fail) => { resolve = done; reject = fail })
|
||
return { promise, resolve, reject }
|
||
}
|
||
const turn = () => new Promise((resolve) => setImmediate(resolve))
|
||
const quiet = () => {}
|
||
|
||
function component(t, filename, names, bindings = {}) {
|
||
const source = fs.readFileSync(new URL('../src/views/' + filename, import.meta.url), 'utf8')
|
||
const script = source.match(/<script setup lang="ts">([\s\S]*?)<\/script>/)[1]
|
||
const parsed = ts.createSourceFile(filename + '.ts', script, ts.ScriptTarget.ES2020, true)
|
||
const body = parsed.statements.filter((node) => !ts.isImportDeclaration(node)).map((node) => node.getText()).join('\n')
|
||
const code = ts.transpileModule(body, { compilerOptions: { target: ts.ScriptTarget.ES2020 } }).outputText
|
||
const route = reactive({ query: {}, params: { token: 'fixture-task' } })
|
||
const disposalCallbacks = []
|
||
const scope = effectScope()
|
||
const context = {
|
||
computed, ref, watch, reactive, nextTick, createRequestScope, canSubmitBorrowScan, canSubmitReturnScan,
|
||
submitReturnWithConfirmation, getReturnCompletionText,
|
||
onMounted: quiet, onUnmounted: (callback) => disposalCallbacks.push(callback),
|
||
useRoute: () => route, useAuthStore: () => ({}),
|
||
isPublicInventorySessionChanged: (error) => error?.status === 409 && error.message === '盘点会话已切换,请重新确认本页身份',
|
||
window: { matchMedia: () => ({ matches: true }), setTimeout, clearTimeout, confirm: () => true },
|
||
playBeepSound: quiet, playErrorSound: quiet,
|
||
buildManualBorrowPersonDisplay: (person) => person.nickname,
|
||
isManualBorrowSelectedPersonKeyword: (person, keyword) => person.nickname === keyword,
|
||
buildManualReturnRecordDisplay: (record) => record.person_nickname,
|
||
isManualReturnSelectedRecordKeyword: (record, keyword) => record.person_nickname === keyword,
|
||
...bindings
|
||
}
|
||
t.after(() => { disposalCallbacks.forEach((dispose) => dispose()); scope.stop() })
|
||
return scope.run(() => new Function(...Object.keys(context), code + '\nreturn { route, ' + names.join(', ') + ' };')(...Object.values(context)))
|
||
}
|
||
|
||
const borrower = { id: 7, nickname: '使用者甲', real_name: '甲' }
|
||
const equipment = (code, id) => ({ id, equipment_code: code, equipment_name: '资产 ' + code, status: '可用' })
|
||
const record = (code, id, recordId) => ({
|
||
id: recordId, equipment_id: id, person_id: borrower.id, person_nickname: borrower.nickname,
|
||
equipment_code: code
|
||
})
|
||
const returnData = (code, id, recordId) => ({ data: { equipment_code: code, equipment_name: '资产 ' + code, borrow_records: [record(code, id, recordId)] } })
|
||
|
||
test('borrow scans leave the newer asset and its accessories in place when an older child lookup finishes', async (t) => {
|
||
const olderChildren = deferred()
|
||
const view = component(t, 'borrow/BorrowScan.vue', [
|
||
'handleScan', 'handleCameraDetected', 'selectManualSearchResult', 'equipmentInfo', 'mountedChildren', 'lookupLoading', 'canSubmit'
|
||
], {
|
||
scanEquipment: async (code) => ({ data: equipment(code, code === 'A' ? 1 : 2) }),
|
||
getChildren: async (id) => id === 1 ? olderChildren.promise : { data: { children: [{ id: 22 }], total_children_value: 10 } }
|
||
})
|
||
const old = view.selectManualSearchResult(equipment('A', 1))
|
||
await turn()
|
||
assert.equal(view.lookupLoading.value, true)
|
||
assert.equal(view.equipmentInfo.value, null)
|
||
assert.equal(view.canSubmit.value, false)
|
||
await view.handleCameraDetected('B')
|
||
olderChildren.resolve({ data: { children: [{ id: 11 }], total_children_value: 20 } })
|
||
await old
|
||
assert.equal(view.equipmentInfo.value.equipment_code, 'B')
|
||
assert.deepEqual(view.mountedChildren.value.map((child) => child.id), [22])
|
||
assert.equal(view.lookupLoading.value, false)
|
||
})
|
||
|
||
test('a late borrow lookup failure cannot replace a newer successful prefilled result', async (t) => {
|
||
const old = deferred()
|
||
const view = component(t, 'borrow/BorrowScan.vue', ['handleCameraDetected', 'equipmentInfo', 'scanError'], {
|
||
scanEquipment: (code) => code === 'A' ? old.promise : Promise.resolve({ data: equipment(code, 2) }),
|
||
getChildren: async () => ({ data: { children: [], total_children_value: 0 } })
|
||
})
|
||
const pending = view.handleCameraDetected('A')
|
||
view.route.query = { equipment_code: 'B' }
|
||
await turn()
|
||
old.reject(new Error('A lookup failed'))
|
||
await pending
|
||
assert.equal(view.equipmentInfo.value.equipment_code, 'B')
|
||
assert.equal(view.scanError.value, '')
|
||
})
|
||
|
||
test('borrow submit clears the old draft during new lookup and freezes the confirmed asset and person during the write', async (t) => {
|
||
const newAsset = deferred()
|
||
const pendingWrite = deferred()
|
||
const submissions = []
|
||
const lookups = []
|
||
const view = component(t, 'borrow/BorrowScan.vue', [
|
||
'handleScan', 'handleSubmit', 'selectPerson', 'persons', 'selectedPersonId', 'borrowForm', 'successInfo', 'loading'
|
||
], {
|
||
scanEquipment: async (code) => { lookups.push(code); return code === 'B' ? newAsset.promise : { data: equipment(code, 1) } },
|
||
getChildren: async () => ({ data: { children: [], total_children_value: 0 } }),
|
||
scanBorrow: (payload) => { submissions.push(payload); return pendingWrite.promise }
|
||
})
|
||
view.persons.value = [borrower]
|
||
await view.handleScan('A')
|
||
view.selectPerson(borrower)
|
||
const lookup = view.handleScan('B')
|
||
await view.handleSubmit()
|
||
assert.equal(submissions.length, 0)
|
||
newAsset.resolve({ data: equipment('B', 2) })
|
||
await lookup
|
||
view.selectPerson(borrower)
|
||
view.borrowForm.value.notes = '已确认备注'
|
||
const write = view.handleSubmit()
|
||
assert.equal(view.loading.value, true)
|
||
await view.handleSubmit()
|
||
await view.handleScan('C')
|
||
view.selectPerson({ id: 8, nickname: '使用者乙' })
|
||
assert.equal(view.selectedPersonId.value, 7)
|
||
assert.deepEqual(lookups, ['A', 'B'])
|
||
assert.deepEqual(submissions.map((row) => [row.equipment_code, row.person_id, row.notes]), [['B', 7, '已确认备注']])
|
||
pendingWrite.resolve({ data: { borrow_time: '2026-11-10T00:00:00Z' } })
|
||
await write
|
||
assert.equal(view.successInfo.value.equipment_code, 'B')
|
||
assert.match(view.successInfo.value.person_display, /使用者甲/)
|
||
})
|
||
|
||
test('return scan keeps the new asset and borrow record after the older anomaly fallback finishes', async (t) => {
|
||
const fallback = deferred()
|
||
const view = component(t, 'borrow/ReturnScan.vue', [
|
||
'handleCameraDetected', 'borrowRecordInfo', 'selectedBorrowRecordId', 'pageNotice', 'showBorrowAnomalyHandler'
|
||
], {
|
||
getBorrowRecordByCode: async (code) => {
|
||
if (code === 'A') throw Object.assign(new Error('A record missing'), { status: 409 })
|
||
return returnData(code, 2, 202)
|
||
},
|
||
getChildren: async () => ({ data: { children: [] } }),
|
||
searchReturnAssets: () => fallback.promise,
|
||
findPreferredManualReturnAssetCandidate: (rows) => rows[0],
|
||
filterManualReturnAssetCandidates: (rows) => rows
|
||
})
|
||
const pending = view.handleCameraDetected('A')
|
||
await turn()
|
||
view.route.query = { equipmentCode: 'B', borrowRecordId: '202' }
|
||
await turn()
|
||
fallback.resolve({ data: [{ equipment_id: 1, equipment_code: 'A', search_state: 'borrow_record_missing', can_handle_borrow_anomaly: true }] })
|
||
await pending
|
||
assert.equal(view.borrowRecordInfo.value.equipment_code, 'B')
|
||
assert.equal(view.selectedBorrowRecordId.value, 202)
|
||
assert.equal(view.showBorrowAnomalyHandler.value, false)
|
||
assert.match(view.pageNotice.value.message, /资产 B/)
|
||
})
|
||
|
||
test('return reads disable stale submission, reject a missing prefilled record, and lock the confirmed transaction', async (t) => {
|
||
const newerRecord = deferred()
|
||
const pendingWrite = deferred()
|
||
const lookups = []
|
||
const submissions = []
|
||
const view = component(t, 'borrow/ReturnScan.vue', [
|
||
'handleScan', 'handleSubmit', 'selectBorrowRecord', 'selectedBorrowRecordId', 'canSubmit', 'returnInfo', 'pageNotice'
|
||
], {
|
||
getBorrowRecordByCode: async (code) => { lookups.push(code); return code === 'B' ? newerRecord.promise : returnData(code, 1, 101) },
|
||
getChildren: async () => ({ data: { children: [] } }),
|
||
scanReturn: (payload) => { submissions.push(payload); return pendingWrite.promise }
|
||
})
|
||
await view.handleScan('A')
|
||
assert.equal(view.canSubmit.value, true)
|
||
const lookup = view.handleScan('B', 999)
|
||
await view.handleSubmit()
|
||
assert.equal(submissions.length, 0)
|
||
newerRecord.resolve(returnData('B', 2, 202))
|
||
await lookup
|
||
assert.equal(view.canSubmit.value, false)
|
||
assert.equal(view.selectedBorrowRecordId.value, null)
|
||
assert.match(view.pageNotice.value.message, /指定借用记录/)
|
||
view.selectBorrowRecord(record('B', 2, 202))
|
||
view.returnInfo.value.return_condition = '损坏'
|
||
const write = view.handleSubmit()
|
||
await view.handleSubmit()
|
||
await view.handleScan('C')
|
||
view.selectBorrowRecord(record('C', 3, 303))
|
||
assert.equal(view.selectedBorrowRecordId.value, 202)
|
||
assert.deepEqual(lookups, ['A', 'B'])
|
||
assert.deepEqual(submissions.map((row) => [row.equipment_code, row.borrow_record_id, row.return_condition]), [['B', 202, '损坏']])
|
||
pendingWrite.resolve({ data: { need_confirm: false } })
|
||
await write
|
||
assert.match(view.pageNotice.value.message, /资产 B.*损坏/)
|
||
})
|
||
|
||
test('leaving a prefilled return route for a blank scan invalidates the old lookup', async (t) => {
|
||
const previous = deferred()
|
||
const lookups = []
|
||
const view = component(t, 'borrow/ReturnScan.vue', [
|
||
'borrowRecordInfo', 'lookupLoading', 'selectedBorrowRecordId', 'canSubmit', 'pageNotice'
|
||
], {
|
||
getBorrowRecordByCode: (code) => { lookups.push(code); return previous.promise },
|
||
getChildren: async () => ({ data: { children: [] } })
|
||
})
|
||
view.route.query = { equipmentCode: 'A', borrowRecordId: '101' }
|
||
await nextTick()
|
||
assert.deepEqual(lookups, ['A'])
|
||
assert.equal(view.lookupLoading.value, true)
|
||
view.route.query = {}
|
||
await nextTick()
|
||
previous.resolve(returnData('A', 1, 101))
|
||
await turn()
|
||
assert.equal(view.lookupLoading.value, false)
|
||
assert.equal(view.borrowRecordInfo.value, null)
|
||
assert.equal(view.selectedBorrowRecordId.value, null)
|
||
assert.equal(view.canSubmit.value, false)
|
||
assert.equal(view.pageNotice.value, null)
|
||
})
|
||
|
||
test('inventory locks exception and scan actions until their writes and refresh settle', async (t) => {
|
||
const pendingException = deferred()
|
||
const pendingScan = deferred()
|
||
const writes = []
|
||
const codes = []
|
||
const reads = []
|
||
const task = { id: 1, status: 'active' }
|
||
const actor = { task, participant: { id: 7 } }
|
||
const assetA = { id: 11, equipment_code: 'A', equipment_name: '资产 A', check_status: 'pending' }
|
||
const assetB = { id: 22, equipment_code: 'B', equipment_name: '资产 B', check_status: 'pending' }
|
||
let failRefresh = false
|
||
const view = component(t, 'inventory/PublicInventoryTask.vue', [
|
||
'task', 'session', 'openExceptionModal', 'closeExceptionModal', 'submitException', 'exceptionTarget',
|
||
'handleSubmitScan', 'handleCameraDetected', 'scanCode', 'feedback', 'actionLocked', 'lastHandledItem'
|
||
], {
|
||
submitPublicInventoryException: (id, payload, identity) => { writes.push({ id, payload, identity }); return pendingException.promise },
|
||
submitPublicInventoryScan: (code, identity) => { codes.push({ code, identity }); return pendingScan.promise },
|
||
getPublicInventoryTask: async () => {
|
||
if (failRefresh) throw new Error('refresh unavailable')
|
||
return { data: task }
|
||
},
|
||
getPublicInventoryMe: async (...args) => { reads.push(args); return { data: actor } },
|
||
getPublicInventoryItems: async (...args) => { reads.push(args); return { data: { items: [assetA, assetB], summary: {} } } }
|
||
})
|
||
view.task.value = task
|
||
view.session.value = actor
|
||
view.openExceptionModal(assetA)
|
||
const write = view.submitException()
|
||
assert.equal(view.actionLocked.value, true)
|
||
view.closeExceptionModal()
|
||
view.openExceptionModal(assetB)
|
||
await view.submitException()
|
||
await view.handleCameraDetected('B')
|
||
assert.equal(view.exceptionTarget.value.id, 11)
|
||
const identity = { task_token: 'fixture-task', participant_id: 7 }
|
||
assert.deepEqual(writes.map(({ id, identity }) => ({ id, identity })), [{ id: 11, identity }])
|
||
assert.deepEqual(codes, [])
|
||
pendingException.resolve({})
|
||
await write
|
||
assert.equal(view.exceptionTarget.value, null)
|
||
assert.equal(view.lastHandledItem.value.id, 11)
|
||
assert.match(view.feedback.value.text, /资产 A/)
|
||
assert.deepEqual(reads, [['fixture-task', 7], ['fixture-task', 7]])
|
||
view.scanCode.value = 'B'
|
||
const scan = view.handleSubmitScan()
|
||
await view.handleSubmitScan()
|
||
await view.handleCameraDetected('C')
|
||
view.openExceptionModal(assetA)
|
||
assert.equal(view.exceptionTarget.value, null)
|
||
assert.deepEqual(codes, [{ code: 'B', identity }])
|
||
failRefresh = true
|
||
pendingScan.resolve({ data: assetB })
|
||
await scan
|
||
assert.equal(view.feedback.value.type, 'info')
|
||
assert.match(view.feedback.value.text, /已确认 资产 B.*未能刷新/)
|
||
assert.equal(view.actionLocked.value, false)
|
||
})
|
||
|
||
const sessionConflict = () => Object.assign(new Error('盘点会话已切换,请重新确认本页身份'), { status: 409 })
|
||
|
||
test('a write with another tab’s session clears only the local inventory and allows reconfirming this task', async (t) => {
|
||
const task = { id: 1, status: 'active' }
|
||
const actor = { task, participant: { id: 7 } }
|
||
const asset = { id: 11, equipment_code: 'A', equipment_name: '资产 A' }
|
||
const calls = []
|
||
const view = component(t, 'inventory/PublicInventoryTask.vue', [
|
||
'task', 'session', 'items', 'handleCameraDetected', 'identityNeedsConfirmation', 'feedback', 'selectedParticipantId', 'confirmIdentity'
|
||
], {
|
||
submitPublicInventoryScan: async (code, identity) => { calls.push(['scan', code, identity]); throw sessionConflict() },
|
||
searchPublicInventoryParticipants: async (token) => { calls.push(['participants', token]); return { data: [actor.participant] } },
|
||
confirmPublicInventoryParticipant: async (token, participantId) => {
|
||
calls.push(['confirm', token, participantId])
|
||
return { data: { participant_id: participantId } }
|
||
},
|
||
getPublicInventoryMe: async (...args) => { calls.push(['me', ...args]); return { data: actor } },
|
||
getPublicInventoryItems: async (...args) => { calls.push(['items', ...args]); return { data: { items: [asset], summary: {} } } }
|
||
})
|
||
view.task.value = task
|
||
view.session.value = actor
|
||
view.items.value = [asset]
|
||
await view.handleCameraDetected('A')
|
||
await view.handleCameraDetected('A')
|
||
assert.deepEqual(calls, [['scan', 'A', { task_token: 'fixture-task', participant_id: 7 }], ['participants', 'fixture-task']])
|
||
assert.equal(view.session.value, null)
|
||
assert.deepEqual(view.items.value, [])
|
||
assert.equal(view.identityNeedsConfirmation.value, true)
|
||
assert.match(view.feedback.value.text, /身份已变化.*重新确认/)
|
||
view.selectedParticipantId.value = 7
|
||
await view.confirmIdentity()
|
||
assert.deepEqual(calls.slice(2), [['confirm', 'fixture-task', 7], ['me', 'fixture-task', 7], ['items', 'fixture-task', 7]])
|
||
assert.equal(view.identityNeedsConfirmation.value, false)
|
||
assert.equal(view.session.value.participant.id, 7)
|
||
assert.equal(view.items.value[0].id, 11)
|
||
})
|
||
|
||
test('initial inventory recovery binds the items request to the participant found by me', async (t) => {
|
||
const task = { id: 1, status: 'active', identity_mode: 'dingtalk' }
|
||
const actor = { task, participant: { id: 7 } }
|
||
const calls = []
|
||
const view = component(t, 'inventory/PublicInventoryTask.vue', [
|
||
'bootstrap', 'confirmBoundIdentity', 'session', 'items', 'identityNeedsConfirmation', 'feedback'
|
||
], {
|
||
useAuthStore: () => ({ isAuthenticated: true, user: { person_id: 5 } }),
|
||
getPublicInventoryTask: async () => ({ data: task }),
|
||
getPublicInventoryMe: async (...args) => { calls.push(['me', ...args]); return { data: actor } },
|
||
getPublicInventoryItems: async (...args) => {
|
||
calls.push(['items', ...args])
|
||
if (calls.length === 2) throw sessionConflict()
|
||
return { data: { items: [{ id: 11 }], summary: {} } }
|
||
},
|
||
confirmCurrentInventoryParticipant: async (token) => {
|
||
calls.push(['confirm', token])
|
||
return { data: { participant_id: 7 } }
|
||
}
|
||
})
|
||
await view.bootstrap()
|
||
assert.deepEqual(calls, [['me', 'fixture-task', undefined], ['items', 'fixture-task', 7]])
|
||
assert.equal(view.session.value, null)
|
||
assert.deepEqual(view.items.value, [])
|
||
assert.equal(view.identityNeedsConfirmation.value, true)
|
||
assert.match(view.feedback.value.text, /身份已变化/)
|
||
await view.confirmBoundIdentity()
|
||
assert.deepEqual(calls.slice(2), [['confirm', 'fixture-task'], ['me', 'fixture-task', 7], ['items', 'fixture-task', 7]])
|
||
assert.equal(view.session.value.participant.id, 7)
|
||
assert.deepEqual(view.items.value, [{ id: 11 }])
|
||
assert.equal(view.identityNeedsConfirmation.value, false)
|
||
})
|