fix: complete October 22 workflow feedback and request failure recovery

This commit is contained in:
2026-10-22 23:06:02 +08:00
parent 22baa5b5c0
commit 3ffa706b89
7 changed files with 123 additions and 381 deletions
@@ -128,41 +128,25 @@ test('cancelled detail summary has no pending overseas synchronization entries',
assert.deepEqual(summary, [])
})
test('edit freezes detail version rather than cached list version and replays same key/body after uncertain result', async t => {
const h = harness(t)
const original = await h.store.loadDraftDetail('one')
const session = h.store.beginDraftEdit(original)
h.store.orders = [{ ...original, version: 0 }]
h.behavior.failWrite = true
await assert.rejects(h.store.saveDraft(h.draft, '测试企业', 'one', session), /响应丢失/)
const first = h.calls.find(call => call.method === 'PUT')
assert.equal(first.data.expectedVersion, 9)
assert.equal(first.data.draft.customerRemark, '原草稿')
assert.ok(first.headers['Idempotency-Key'])
assert.deepEqual(h.calls.map(call => call.method), ['GET', 'PUT'], 'no pre-save version refresh')
h.behavior.failWrite = false; h.behavior.version = 10
const result = await h.store.saveDraft(h.draft, '测试企业', 'one', session)
test('edit preserves the detail version but generates a fresh command after failure', async t => {
const h = harness(t), session = h.store.beginDraftEdit(await h.store.loadDraftDetail('one'))
h.store.orders = [{ id: 'one', version: 0 }]; h.behavior.failWrite = true
await assert.rejects(h.store.saveDraft(h.draft, '客户', 'one', session), /响应丢失/)
h.behavior.failWrite = false; h.draft.customerRemark = '已修改'
await h.store.saveDraft(h.draft, '客户', 'one', session)
const writes = h.calls.filter(call => call.method === 'PUT')
assert.deepEqual(writes[1], first)
assert.deepEqual(h.calls.map(call => call.method), ['GET', 'PUT', 'GET', 'PUT', 'GET'])
assert.equal(result.version, 10)
assert.equal(writes[0].data.expectedVersion, 9); assert.equal(writes[1].data.draft.customerRemark, '已修改')
assert.notEqual(writes[0].headers['Idempotency-Key'], writes[1].headers['Idempotency-Key'])
})
test('changed retry payload or missing edit session fails closed without issuing a new write', async t => {
const h = harness(t)
await assert.rejects(h.store.saveDraft(h.draft, '客户', 'one'), /重新打开/)
assert.equal(h.calls.length, 0)
const session = h.store.beginDraftEdit(await h.store.loadDraftDetail('one'))
h.behavior.failWrite = true
test('missing edit session is invalid while changed inputs after failure are accepted', async t => {
const h = harness(t); await assert.rejects(h.store.saveDraft(h.draft, '客户', 'one'), /重新打开/)
const session = h.store.beginDraftEdit(await h.store.loadDraftDetail('one')); h.behavior.failWrite = true
await assert.rejects(h.store.saveDraft(h.draft, '客户', 'one', session))
h.draft.customerRemark = '不同内容'
await assert.rejects(h.store.saveDraft(h.draft, '客户', 'one', session), /重试原内容/)
assert.equal(h.calls.filter(call => call.method === 'PUT').length, 1)
assert.equal(session.expectedVersion, 9)
assert.ok(Object.isFrozen(session))
h.draft.customerRemark = '不同内容'; h.behavior.failWrite = false
await h.store.saveDraft(h.draft, '客户', 'one', session)
assert.equal(h.calls.filter(call => call.method === 'PUT').length, 2)
})
test('read failure after successful edit preserves the same command for retry', async t => {
test('read failure after edit does not retain a frozen request', async t => {
const h = harness(t)
const session = h.store.beginDraftEdit(await h.store.loadDraftDetail('one'))
h.behavior.failRead = true
@@ -170,28 +154,17 @@ test('read failure after successful edit preserves the same command for retry',
h.behavior.failRead = false
await h.store.saveDraft(h.draft, '客户', 'one', session)
const writes = h.calls.filter(call => call.method === 'PUT')
assert.deepEqual(writes[0], writes[1])
assert.notEqual(writes[0].headers['Idempotency-Key'], writes[1].headers['Idempotency-Key'])
})
test('cancel forwards version and reason without rejecting submitted orders locally; retry keeps key and body', async t => {
const h = harness(t)
h.behavior.status = 'SUBMITTED'
h.store.orders = [{ id: 'one', status: 'PENDING_REVIEW', version: 0 }]
h.behavior.failWrite = true
test('cancel submits the current version and reason after a previous failure', async t => {
const h = harness(t); h.behavior.status = 'SUBMITTED'; h.behavior.failWrite = true
await assert.rejects(h.store.cancelOrder('one', 12, '客户要求取消'), /响应丢失/)
const first = h.calls[0]
assert.equal(first.method, 'POST')
assert.equal(first.url, '/merchant/v1/orders/first-leg/one/cancel')
assert.deepEqual(first.data, { expectedVersion: 12, reason: '客户要求取消' })
await assert.rejects(h.store.cancelOrder('one', 13, '其他原因'), /原版本和原因/)
assert.equal(h.calls.length, 1)
h.behavior.failWrite = false
await h.store.cancelOrder('one', 12, '客户要求取消')
assert.deepEqual(h.calls[2], first)
assert.equal(h.calls[1].method, 'GET')
assert.equal(h.store.orders.length, 0)
h.behavior.failWrite = false; await h.store.cancelOrder('one', 13, '其他原因')
const writes = h.calls.filter(call => call.method === 'POST')
assert.equal(writes.length, 2); assert.deepEqual(writes[1].data, { expectedVersion: 13, reason: '其他原因' })
assert.notEqual(writes[0].headers['Idempotency-Key'], writes[1].headers['Idempotency-Key'])
})
test('cancel requires a detail version and a nonempty reason', async t => {
const h = harness(t)
await assert.rejects(h.store.cancelOrder('one', undefined, '理由'))
@@ -252,24 +225,13 @@ test('cancel UI uses mandatory-reason centered prompt and refreshes after succes
assert.deepEqual(h.calls[1], ['cancel', 'one', 12, '客户申请取消'])
})
test('cancel UI keeps an uncertain command for explicit retry, but conflict requires a fresh decision', async () => {
const h = cancellationViewHarness()
const order = { id: 'one', status: 'DRAFT' }
h.behavior.error = new Error('网络无响应')
await h.handler(order)
assert.equal(h.pendingCancellation.value.expectedVersion, 12)
h.behavior.error = null
await h.handler(order)
assert.equal(h.prompts.length, 1)
assert.equal(h.calls.filter(call => call[0] === 'prepare').length, 1)
assert.equal(h.calls.filter(call => call[0] === 'confirm').length, 1)
assert.deepEqual(h.calls.filter(call => call[0] === 'cancel')[0], h.calls.filter(call => call[0] === 'cancel')[1])
h.behavior.error = new h.ApiError()
await h.handler(order)
assert.equal(h.pendingCancellation.value, undefined)
assert.match(h.messages.at(-1), /刷新订单后重新确认/)
test('cancel UI releases failure and asks for a current cancellation decision on the next click', async () => {
const h = cancellationViewHarness(), order = { id: 'one', status: 'DRAFT' }
h.behavior.error = new Error('网络无响应'); await h.handler(order)
h.behavior.error = null; await h.handler(order)
assert.equal(h.prompts.length, 2); assert.equal(h.calls.filter(call => call[0] === 'prepare').length, 2)
assert.equal(h.calls.filter(call => call[0] === 'cancel').length, 2)
})
test('cancel UI blocks unavailable permission and irreversible visible stages before reads or writes', async () => {
const h = cancellationViewHarness()
h.canCancelOrder.value = false
@@ -286,23 +248,14 @@ test('both editor entry points capture detail sessions and both save paths pass
assert.equal((view.match(/store\.saveDraft(?:ForSubmission)?\(cloneDraft\(form\), tenantStore\.company\.companyName, editingId\.value, editingSession\.value\)/g) ?? []).length, 2)
})
test('submit reads raw detail version rather than list zero and replays original key and version after timeout', async t => {
const h = harness(t)
h.store.orders = [{ id: 'one', status: 'DRAFT', version: 0 }]
h.behavior.failSubmit = true
test('submit uses the current raw version and a fresh key after timeout', async t => {
const h = harness(t); h.store.orders = [{id:'one',status:'DRAFT',version:0}]; h.behavior.failSubmit = true
await assert.rejects(h.store.submitSaved('one', 'ACTIVE'), /响应丢失/)
const first = h.calls[1]
assert.equal(first.url, '/merchant/v1/orders/first-leg/one/submit')
assert.deepEqual(first.data, { expectedVersion: 9 })
assert.ok(first.headers['Idempotency-Key'])
h.behavior.version = 10; h.behavior.status = 'SUBMITTED'; h.behavior.failSubmit = false
await h.store.submitSaved('one', 'ACTIVE')
assert.deepEqual(h.calls[3], first)
assert.deepEqual(h.calls.map(call => call.method), ['GET', 'POST', 'GET', 'POST', 'GET'])
assert.equal(h.store.hasPendingSubmission('one'), false)
h.behavior.version = 10; h.behavior.failSubmit = false; await h.store.submitSaved('one', 'ACTIVE')
const writes = h.calls.filter(call => call.url.endsWith('/submit'))
assert.deepEqual(writes.map(call => call.data.expectedVersion), [9,10]); assert.notEqual(writes[0].headers['Idempotency-Key'],writes[1].headers['Idempotency-Key'])
})
test('submit refuses missing version or non-draft first decision and preserves command after failed readback', async t => {
test('submit validates current status and releases failure after readback', async t => {
const h = harness(t)
for (const version of [undefined, -1, 1.5]) {
h.behavior.version = version
@@ -313,49 +266,25 @@ test('submit refuses missing version or non-draft first decision and preserves c
assert.ok(h.calls.every(call => call.method === 'GET'))
h.behavior.status = 'DRAFT'; h.behavior.failSubmitRead = true
await assert.rejects(h.store.submitSaved('one'), /读取失败/)
assert.equal(h.store.hasPendingSubmission('one'), true)
h.behavior.failRead = false; h.behavior.failSubmitRead = false
await h.store.submitSaved('one')
const posts = h.calls.filter(call => call.method === 'POST')
assert.deepEqual(posts[0], posts[1])
assert.notEqual(posts[0].headers['Idempotency-Key'], posts[1].headers['Idempotency-Key'])
assert.deepEqual(posts[0].data, { expectedVersion: 0 }, 'raw detail zero is valid')
})
test('save then submit retries without another save and changed form requires an explicit new decision', async t => {
const h = harness(t)
const session = h.store.beginDraftEdit(await h.store.loadDraftDetail('one'))
await h.store.saveDraftForSubmission(h.draft, '客户', 'one', session)
h.behavior.failSubmit = true
await assert.rejects(h.store.submitSaved('one'))
const first = h.calls.find(call => call.url.endsWith('/submit'))
await h.store.saveDraftForSubmission(h.draft, '客户', 'one', session)
assert.equal(h.calls.filter(call => call.method === 'PUT').length, 1)
h.draft.customerRemark = '新决定'
await assert.rejects(h.store.saveDraftForSubmission(h.draft, '客户', 'one', session), /重新编辑/)
h.behavior.status = 'SUBMITTED'
await assert.rejects(h.store.beginNewSubmissionEdit('one'), /不能重新编辑/)
assert.equal(h.store.hasPendingSubmission('one'), true)
h.behavior.status = 'DRAFT'; h.behavior.version = 12
const newSession = await h.store.beginNewSubmissionEdit('one')
assert.equal(newSession.expectedVersion, 12)
await h.store.saveDraftForSubmission(h.draft, '客户', 'one', newSession)
h.behavior.version = 13; h.behavior.failSubmit = false
await h.store.submitSaved('one')
const posts = h.calls.filter(call => call.url.endsWith('/submit'))
assert.notEqual(posts[1].headers['Idempotency-Key'], first.headers['Idempotency-Key'])
assert.deepEqual(posts[1].data, { expectedVersion: 13 })
test('failed submit leaves the draft editable for a fresh save and submission', async t => {
const h = harness(t), session = h.store.beginDraftEdit(await h.store.loadDraftDetail('one'))
await h.store.saveDraft(h.draft, '客户', 'one', session); h.behavior.failSubmit = true
await assert.rejects(h.store.submitSaved('one')); h.draft.customerRemark = '新内容'
await h.store.saveDraft(h.draft, '客户', 'one', session); h.behavior.failSubmit = false
await h.store.submitSaved('one'); assert.equal(h.calls.filter(call => call.method === 'PUT').length, 2)
})
test('failed initial submit read does not resave the prepared draft on retry', async t => {
const h = harness(t)
const session = h.store.beginDraftEdit(await h.store.loadDraftDetail('one'))
await h.store.saveDraftForSubmission(h.draft, '客户', 'one', session)
h.behavior.failRead = true
await assert.rejects(h.store.submitSaved('one'))
await h.store.saveDraftForSubmission(h.draft, '客户', 'one', session)
assert.equal(h.calls.filter(call => call.method === 'PUT').length, 1)
test('failed initial submit read releases the submission guard for the next click', async t => {
const h = harness(t); h.behavior.failRead = true; await assert.rejects(h.store.submitSaved('one'))
h.behavior.failRead = false; await h.store.submitSaved('one')
assert.equal(h.calls.filter(call => call.url.endsWith('/submit')).length, 1)
})
async function submissionViewHarness(t) {
const h = harness(t)
const source = readFileSync(new URL('../views/FirstLegOrdersView.vue', import.meta.url), 'utf8').match(/<script setup lang="ts">([\s\S]*?)<\/script>/)[1]
@@ -377,56 +306,29 @@ async function submissionViewHarness(t) {
return { ...h, ...handlers, globals, messages, confirmations }
}
test('real editor submit handler retries original submission without PUT and requires confirmation for changed form', async t => {
const h = await submissionViewHarness(t)
h.behavior.failSubmit = true
await h.submitOrder()
await h.submitOrder()
assert.equal(h.calls.filter(call => call.method === 'PUT').length, 1)
const posts = h.calls.filter(call => call.url.endsWith('/submit'))
assert.deepEqual(posts[0], posts[1])
h.draft.customerRemark = '修改后的决定'
h.behavior.cancelConfirm = true
await h.submitOrder()
assert.equal(h.confirmations.length, 1)
assert.equal(h.calls.filter(call => call.method === 'PUT').length, 1)
h.behavior.cancelConfirm = false; h.behavior.failSubmit = false; h.behavior.version = 12
await h.submitOrder()
assert.equal(h.confirmations.length, 2)
assert.equal(h.calls.filter(call => call.method === 'PUT').length, 2)
const last = h.calls.filter(call => call.url.endsWith('/submit')).at(-1)
assert.deepEqual(last.data, { expectedVersion: 12 })
assert.notEqual(last.headers['Idempotency-Key'], posts[0].headers['Idempotency-Key'])
assert.equal(h.globals.saving.value, false)
test('real editor releases failure and saves current edited input on another click', async t => {
const h = await submissionViewHarness(t); h.behavior.failSubmit = true
await h.submitOrder(); assert.equal(h.globals.saving.value, false)
h.draft.customerRemark = '修改后的决定'; h.behavior.failSubmit = false; await h.submitOrder()
const writes = h.calls.filter(call => call.method === 'PUT'), posts = h.calls.filter(call => call.url.endsWith('/submit'))
assert.equal(writes.length, 2); assert.equal(writes[1].data.draft.customerRemark, '修改后的决定')
assert.notEqual(posts[0].headers['Idempotency-Key'], posts[1].headers['Idempotency-Key']); assert.equal(h.globals.saving.value, false)
})
test('real batch handler retains uncertain IDs across list refresh and retries original commands even if now submitted', async t => {
const h = await submissionViewHarness(t)
h.behavior.failSubmit = true
await h.submitSelectedDraftOrders()
assert.deepEqual(h.globals.pendingBatchSubmissionIds.value, ['one'])
assert.deepEqual(h.globals.selectedDraftOrders.value, [])
h.behavior.failSubmit = false; h.behavior.status = 'SUBMITTED'; h.behavior.version = 10
await h.submitSelectedDraftOrders()
test('real batch handler uses only current selection after a failed batch', async t => {
const h = await submissionViewHarness(t); h.behavior.failSubmit = true
await h.submitSelectedDraftOrders(); assert.equal(h.globals.batchSubmitting.value, false)
h.behavior.failSubmit = false; await h.submitSelectedDraftOrders()
assert.equal(h.calls.filter(call => call.url.endsWith('/submit')).length, 1)
h.globals.selectedDraftOrders.value = [{id:'one',version:9}]; await h.submitSelectedDraftOrders()
const posts = h.calls.filter(call => call.url.endsWith('/submit'))
assert.equal(posts.length, 2)
assert.deepEqual(posts[1], posts[0])
assert.deepEqual(posts[0].data, { expectedVersion: 9 })
assert.deepEqual(h.globals.pendingBatchSubmissionIds.value, [])
assert.equal(h.globals.batchSubmitting.value, false)
assert.equal(posts.length, 2); assert.notEqual(posts[0].headers['Idempotency-Key'], posts[1].headers['Idempotency-Key'])
})
test('real new-order handler creates once and retries the saved order submission with the original version', async t => {
const h = await submissionViewHarness(t)
h.globals.editingId.value = undefined; h.globals.editingSession.value = undefined
h.behavior.version = 0; h.behavior.failSubmit = true
await h.submitOrder()
assert.equal(h.globals.editingId.value, 'one')
h.behavior.version = 1; h.behavior.status = 'SUBMITTED'; h.behavior.failSubmit = false
test('real new-order handler retains the created order and saves current edits after submit failure', async t => {
const h = await submissionViewHarness(t); h.globals.editingId.value = undefined; h.globals.editingSession.value = undefined
h.behavior.version = 0; h.behavior.failSubmit = true; await h.submitOrder()
assert.equal(h.globals.editingId.value, 'one'); h.behavior.failSubmit = false; h.draft.customerRemark = '修改'
await h.submitOrder()
assert.equal(h.calls.filter(call => call.method === 'POST' && call.url === '/merchant/v1/orders/first-leg').length, 1)
assert.equal(h.calls.filter(call => call.method === 'PUT').length, 0)
const posts = h.calls.filter(call => call.url.endsWith('/submit'))
assert.deepEqual(posts[0], posts[1])
assert.deepEqual(posts[0].data, { expectedVersion: 0 })
})
assert.equal(h.calls.filter(call => call.method === 'PUT').length, 1)
assert.equal(h.calls.filter(call => call.url.endsWith('/submit')).length, 2)
})
@@ -220,7 +220,7 @@ test('only blocks submission when a known company audit status is not active', (
})
test('uses the versioned merchant cancellation contract', () => {
assert.match(storeSource, /cancelMerchantFirstLegOrder\(id, pending\.payload, pending\.key\)/)
assert.match(storeSource, /cancelMerchantFirstLegOrder\(id, payload, createIdempotencyKey\(/)
assert.match(apiSource, /cancelMerchantFirstLegOrder\(id: number \| string, payload: \{ expectedVersion: number; reason: string \}, idempotencyKey: string\)/)
})
@@ -231,8 +231,8 @@ test('sends an idempotency key for create and submit writes', () => {
assert.match(apiSource, /createMerchantFirstLegOrderBatch\(items: MerchantBatchDraftItem\[\], idempotencyKey: string\)/)
assert.match(apiSource, /headers: \{ 'Idempotency-Key': idempotencyKey \}/)
assert.match(storeSource, /createMerchantFirstLegOrderBatch\(items, idempotencyKey\)/)
assert.match(storeSource, /pendingSubmissions\.get\(id\)/)
assert.match(storeSource, /submitMerchantFirstLegOrder\(id, pending\.payload, pending\.key\)/)
assert.doesNotMatch(storeSource, /pendingSubmissions|pendingEdits|pendingCancellation/)
assert.match(storeSource, /submitMerchantFirstLegOrder\(id, \{ expectedVersion: order\.version \}, createIdempotencyKey\(/)
})
test('does not expose the contradictory backend rejected state in the client model', () => {
+7 -66
View File
@@ -404,11 +404,7 @@ export const useFirstLegOrdersStore = defineStore('client-first-leg-orders', ()
const orderProgress = ref<Record<string, MerchantOrderProgress>>({})
const queryChannelNames = ref<string[]>([])
let listRequest = 0
const pendingSubmissions = new Map<string, { key: string; payload: { expectedVersion: number } }>()
const submissionForms = new Map<string, { snapshot: string; order: FirstLegOrder }>()
const submittingIds = new Set<string>()
const pendingEdits = new WeakMap<DraftEditSession, { key: string; payload: { expectedVersion: number; draft: FirstLegOrderSaveRequest } }>()
const pendingCancellations = new Map<string, { key: string; payload: { expectedVersion: number; reason: string } }>()
function beginDraftEdit(detail: FirstLegOrder): DraftEditSession {
if (!canClientEditFirstLegOrder(detail.status) || !Number.isSafeInteger(detail.version) || detail.version < 0) throw new Error('请重新打开草稿详情后编辑')
@@ -534,22 +530,12 @@ export const useFirstLegOrdersStore = defineStore('client-first-leg-orders', ()
}
async function saveDraft(draft: FirstLegOrderDraft, customerName: string, id?: string, editSession?: DraftEditSession) {
if (hasPendingSubmission(id)) throw new Error('上次提交结果未确认,请重试原提交,或确认重新编辑后再保存')
const warehouse = prepareDraftForSave(draft, warehouses.value)
if (id) {
if (!editSession || editSession.orderId !== id) throw new Error('请重新打开草稿详情后编辑')
const payload = { expectedVersion: editSession.expectedVersion, draft: savePayload(draft, warehouse, customerName) }
let pending = pendingEdits.get(editSession)
if (pending && JSON.stringify(pending.payload) !== JSON.stringify(payload)) throw new Error('上次保存结果未确认,请重试原内容,或重新打开详情后编辑')
// Observe an uncertain previous outcome without replacing its frozen version.
if (pending) await getMerchantFirstLegOrder(id)
if (!pending) {
pending = { key: createIdempotencyKey(`first-leg-edit-${id}`), payload: JSON.parse(JSON.stringify(payload)) }
pendingEdits.set(editSession, pending)
}
await updateMerchantFirstLegOrder(id, pending.payload, pending.key)
await updateMerchantFirstLegOrder(id, payload, createIdempotencyKey(`first-leg-edit-${id}`))
const saved = await loadOrderAggregate(id)
pendingEdits.delete(editSession)
return saved
}
const createdId = await createMerchantFirstLegOrder(savePayload(draft, warehouse, customerName))
@@ -559,15 +545,7 @@ export const useFirstLegOrdersStore = defineStore('client-first-leg-orders', ()
async function cancelOrder(id: string, expectedVersion: number, reason: string) {
if (!Number.isSafeInteger(expectedVersion) || expectedVersion < 0 || !reason.trim() || reason.trim().length > 500) throw new Error('取消订单需要详情版本及 1–500 字取消原因')
const payload = { expectedVersion, reason: reason.trim() }
let pending = pendingCancellations.get(id)
if (pending && JSON.stringify(pending.payload) !== JSON.stringify(payload)) throw new Error('上次取消结果未确认,请使用原版本和原因重试')
if (pending) await getMerchantFirstLegOrder(id)
if (!pending) {
pending = { key: createIdempotencyKey(`first-leg-cancel-${id}`), payload }
pendingCancellations.set(id, pending)
}
await cancelMerchantFirstLegOrder(id, pending.payload, pending.key)
pendingCancellations.delete(id)
await cancelMerchantFirstLegOrder(id, payload, createIdempotencyKey(`first-leg-cancel-${id}`))
orders.value = orders.value.filter(order => order.id !== id)
}
@@ -576,7 +554,6 @@ export const useFirstLegOrdersStore = defineStore('client-first-leg-orders', ()
const labels: Record<string, string> = { DRAFT: '草稿', SUBMITTED: '审核中', APPROVED: '已审核', ACCEPTED: '已接单', REJECTED: '已退回' }
if (!Object.hasOwn(labels, order.status)) throw new Error('当前订单状态不允许取消,请刷新订单查看最新进度')
if (!Number.isSafeInteger(order.version) || order.version < 0) throw new Error('订单版本缺失,请重新加载详情')
pendingCancellations.delete(id)
return { id, expectedVersion: order.version, businessNo: order.orderNo || order.inboundCode || '—', statusLabel: labels[order.status] }
}
@@ -597,55 +574,19 @@ export const useFirstLegOrdersStore = defineStore('client-first-leg-orders', ()
if (submittingIds.has(id)) throw new Error('订单正在提交,请稍候')
submittingIds.add(id)
try {
let pending = pendingSubmissions.get(id)
// Always observe the raw detail; a retry must retain the original command.
const { order } = await getMerchantFirstLegOrder(id)
if (!pending) {
if (order.status !== 'DRAFT') throw new Error('当前订单不是草稿,请刷新订单查看最新状态')
if (!Number.isSafeInteger(order.version) || order.version < 0) throw new Error('订单版本缺失,请重新加载详情')
pending = { key: createIdempotencyKey(`first-leg-submit-${id}`), payload: { expectedVersion: order.version } }
pendingSubmissions.set(id, pending)
}
await submitMerchantFirstLegOrder(id, pending.payload, pending.key)
const submitted = await loadOrderAggregate(id)
pendingSubmissions.delete(id)
submissionForms.delete(id)
return submitted
if (order.status !== 'DRAFT') throw new Error('当前订单不是草稿,请刷新订单查看最新状态')
if (!Number.isSafeInteger(order.version) || order.version < 0) throw new Error('订单版本缺失,请重新加载详情')
await submitMerchantFirstLegOrder(id, { expectedVersion: order.version }, createIdempotencyKey(`first-leg-submit-${id}`))
return await loadOrderAggregate(id)
} finally {
submittingIds.delete(id)
}
}
function hasPendingSubmission(id?: string) { return !!id && (pendingSubmissions.has(id) || submissionForms.has(id)) }
function isSubmissionRetry(id: string | undefined, draft: FirstLegOrderDraft) {
return !!id && hasPendingSubmission(id) && submissionForms.get(id)?.snapshot === JSON.stringify(draft)
}
async function beginNewSubmissionEdit(id: string) {
if (submittingIds.has(id)) throw new Error('订单正在提交,请稍候')
const detail = await getMerchantFirstLegOrder(id)
if (detail.order.status !== 'DRAFT') throw new Error('订单已不在草稿状态,不能重新编辑,请刷新订单查看最新状态')
if (!Number.isSafeInteger(detail.order.version) || detail.order.version < 0) throw new Error('订单版本缺失,请重新加载详情')
const order = mapOrder(detail.order, warehouses.value, detail)
const session = beginDraftEdit(order)
pendingSubmissions.delete(id)
submissionForms.delete(id)
upsertOrder(order)
return session
}
async function saveDraftForSubmission(draft: FirstLegOrderDraft, customerName: string, id?: string, editSession?: DraftEditSession) {
if (id && isSubmissionRetry(id, draft)) return submissionForms.get(id)!.order
const snapshot = JSON.stringify(draft)
const order = await saveDraft(JSON.parse(snapshot), customerName, id, editSession)
submissionForms.set(order.id, { snapshot, order })
return order
}
async function loadDraftDetail(id: string) {
return loadOrderAggregate(id)
}
return { orders, orderDetails, total, queueCounts, orderProgress, queryChannelNames, warehouses, loading, loadedFromApi, loadError, warehouseLoadError, getById, load, loadDetail, loadDraftDetail, loadWarehouseDetail, loadWarehouseType, beginDraftEdit, saveDraft, prepareCancellation, cancelOrder, saveDraftBatch, submitSaved, hasPendingSubmission, isSubmissionRetry, beginNewSubmissionEdit, saveDraftForSubmission }
return { orders, orderDetails, total, queueCounts, orderProgress, queryChannelNames, warehouses, loading, loadedFromApi, loadError, warehouseLoadError, getById, load, loadDetail, loadDraftDetail, loadWarehouseDetail, loadWarehouseType, beginDraftEdit, saveDraft, prepareCancellation, cancelOrder, saveDraftBatch, submitSaved }
})
@@ -85,7 +85,6 @@ const canCreateOrder = computed(() => auth.hasPermission('order:first-leg:create
const canEditOrder = computed(() => auth.hasPermission('order:first-leg:edit'))
const canCancelOrder = computed(() => auth.hasPermission('order:first-leg:cancel'))
const cancellingOrderId = ref('')
const pendingCancellation = shallowRef<{ id: string; expectedVersion: number; reason: string; businessNo: string; statusLabel: string }>()
function canOfferCancellation(order: FirstLegOrder) {
return canCancelOrder.value && ['DRAFT', 'PENDING_REVIEW', 'WAIT_MEASURE'].includes(order.status)
@@ -95,40 +94,20 @@ async function cancelOrder(order: FirstLegOrder) {
if (!canOfferCancellation(order) || cancellingOrderId.value) return
cancellingOrderId.value = order.id
try {
let command = pendingCancellation.value
if (command && command.id !== order.id) {
ElMessage.warning(`请先处理订单 ${command.businessNo} 未确认的取消结果`)
return
}
if (!command) {
const target = await store.prepareCancellation(order.id)
const { value } = await ElMessageBox.prompt(`订单:${target.businessNo};当前状态:${target.statusLabel}。请填写取消原因。`, '取消订单', {
const target = await store.prepareCancellation(order.id)
const { value } = await ElMessageBox.prompt(
`订单:${target.businessNo};当前状态:${target.statusLabel}。请填写取消原因。`, '取消订单', {
type: 'warning', inputType: 'textarea', confirmButtonText: '确认取消订单', cancelButtonText: '返回',
inputValidator: value => Boolean(value?.trim()) && value.trim().length <= 500 || '请填写 1–500 字取消原因',
})
command = { ...target, reason: value.trim() }
pendingCancellation.value = command
} else {
await ElMessageBox.confirm(`订单:${command.businessNo};原状态:${command.statusLabel};原因:${command.reason}。将查询当前状态并重试原取消请求。`, '重试取消订单', {
type: 'warning', confirmButtonText: '重试原请求', cancelButtonText: '返回',
})
}
await store.cancelOrder(command.id, command.expectedVersion, command.reason)
pendingCancellation.value = undefined
ElMessage.success('订单已取消')
await loadOrderPage()
await store.cancelOrder(target.id, target.expectedVersion, value.trim())
ElMessage.success('订单已取消'); await loadOrderPage()
if (isDetailPage.value) await router.push({ name: 'first-leg-orders' })
} catch (error) {
if (error === 'cancel' || error === 'close') return
if (error instanceof ApiError && (error.code === 'A0409' || error.status === 409)) {
pendingCancellation.value = undefined
ElMessage.error(`${error.message}。请刷新订单后重新确认取消。`)
} else {
ElMessage.error(error instanceof Error ? error.message : '取消失败,请重试原请求')
}
} finally {
cancellingOrderId.value = ''
}
ElMessage.error(error instanceof Error ? error.message : '取消失败,请重新操作')
void loadOrderPage()
} finally { cancellingOrderId.value = '' }
}
const canSubmitOrder = computed(() => auth.hasPermission('order:first-leg:submit'))
const canConfirmInboundFee = computed(() => auth.hasPermission('order:first-leg:edit'))
@@ -242,7 +221,6 @@ const tablePageSize = ref(10)
const downloadingMarks = ref(false)
const exportingOrders = ref(false)
const batchSubmitting = ref(false)
const pendingBatchSubmissionIds = ref<string[]>([])
const selectedOrders = ref<FirstLegOrder[]>([])
const selectedOrderCount = computed(() => selectedOrders.value.length)
const selectedDraftOrders = computed(() => selectedOrders.value.filter((order) => order.status === 'DRAFT'))
@@ -1368,7 +1346,7 @@ function getOrderRowActions(row: object): TableAction[] {
actions.push({ key: 'edit', label: '编辑', loading: openingEditor.value, run: () => openEdit(order) })
}
if (canOfferCancellation(order)) {
actions.push({ key: 'cancel', label: pendingCancellation.value?.id === order.id ? '重试取消' : '取消订单', loading: cancellingOrderId.value === order.id, disabled: Boolean(cancellingOrderId.value), run: () => cancelOrder(order) })
actions.push({ key: 'cancel', label: '取消订单', loading: cancellingOrderId.value === order.id, disabled: Boolean(cancellingOrderId.value), run: () => cancelOrder(order) })
}
if (eligibleCustomsDetail(order)) {
actions.push({ key: 'customs', label: '报关资料', run: () => openCustomsDocuments(order) })
@@ -1751,14 +1729,14 @@ function handleOrderSelectionChange(rows: FirstLegOrder[]) {
}
async function submitSelectedDraftOrders() {
const ids = [...new Set([...pendingBatchSubmissionIds.value, ...selectedDraftOrders.value.map(order => order.id)])]
const ids = [...new Set(selectedDraftOrders.value.map(order => order.id))]
if (batchSubmitting.value || !ids.length) return
if (companySubmissionBlocked.value) {
ElMessage.warning('企业资料审核通过后才能提交订单')
return
}
try {
await ElMessageBox.confirm(`确认提交 ${ids.length} 条草稿订单吗?${pendingBatchSubmissionIds.value.length ? '上次结果未确认的订单将使用原提交命令重试。' : ''}`, '批量提交订单', {
await ElMessageBox.confirm(`确认提交 ${ids.length} 条草稿订单吗?`, '批量提交订单', {
type: 'warning',
confirmButtonText: '确认提交',
cancelButtonText: '取消',
@@ -1771,7 +1749,6 @@ async function submitSelectedDraftOrders() {
batchSubmitting.value = true
try {
const results = await Promise.allSettled(ids.map(id => store.submitSaved(id, companyAuditLoaded.value ? tenantStore.company.auditStatus : undefined)))
pendingBatchSubmissionIds.value = ids.filter((id, index) => results[index]?.status === 'rejected' && store.hasPendingSubmission(id))
const successCount = results.filter((result) => result.status === 'fulfilled').length
const failures = results.filter((result): result is PromiseRejectedResult => result.status === 'rejected')
await searchOrders(appliedFilters.value)
@@ -2024,7 +2001,6 @@ async function saveDraft() {
if (!await validateEditorForm()) return
saving.value = true
try {
if (!await confirmSubmissionEdit()) return
const order = await store.saveDraft(cloneDraft(form), tenantStore.company.companyName, editingId.value, editingSession.value)
editingId.value = order.id
editingSession.value = store.beginDraftEdit(order)
@@ -2039,20 +2015,6 @@ async function saveDraft() {
}
}
async function confirmSubmissionEdit() {
if (!editingId.value || !store.hasPendingSubmission(editingId.value)) return true
try {
await ElMessageBox.confirm('上次提交结果尚未确认。确认重新读取订单并按当前表单重新编辑吗?只有服务端仍为草稿时才能开始新的提交决定。', '重新编辑订单', {
type: 'warning', center: true, confirmButtonText: '确认重新编辑', cancelButtonText: '返回',
})
} catch (error) {
if (error === 'cancel' || error === 'close') return false
throw error
}
editingSession.value = await store.beginNewSubmissionEdit(editingId.value)
return true
}
async function submitOrder() {
if (saving.value) return
if (companySubmissionBlocked.value) {
@@ -2071,14 +2033,12 @@ async function submitOrder() {
}
return
}
const retry = store.isSubmissionRetry(editingId.value, cloneDraft(form))
if (!retry && !await validateEditorForm()) return
if (!await validateEditorForm()) return
try {
saving.value = true
if (!retry && !await confirmSubmissionEdit()) return
const knownCompanyAuditStatus = companyAuditLoaded.value ? tenantStore.company.auditStatus : undefined
const savedOrder = await store.saveDraftForSubmission(cloneDraft(form), tenantStore.company.companyName, editingId.value, editingSession.value)
const savedOrder = await store.saveDraft(cloneDraft(form), tenantStore.company.companyName, editingId.value, editingSession.value)
editingId.value = savedOrder.id
editingSession.value = store.beginDraftEdit(savedOrder)
await store.submitSaved(savedOrder.id, knownCompanyAuditStatus)
@@ -2156,7 +2116,7 @@ async function searchOrders(model: QueryModel) {
</el-popover>
<el-button :loading="downloadingMarks" :disabled="selectedOrderCount === 0" @click="downloadShippingMarks"><Download :size="16" />下载唛头</el-button>
<el-button :loading="exportingOrders" :disabled="selectedOrderCount === 0" @click="exportOrderInformation"><Download :size="16" />导出订单信息</el-button>
<el-button v-if="canSubmitOrder" :loading="batchSubmitting" :disabled="(selectedDraftOrders.length === 0 && pendingBatchSubmissionIds.length === 0) || companySubmissionBlocked" @click="submitSelectedDraftOrders"><Send :size="17" />{{ pendingBatchSubmissionIds.length ? '重试批量提交' : '批量提交草稿' }}</el-button>
<el-button v-if="canSubmitOrder" :loading="batchSubmitting" :disabled="selectedDraftOrders.length === 0 || companySubmissionBlocked" @click="submitSelectedDraftOrders"><Send :size="17" />批量提交草稿</el-button>
<el-button v-if="auth.hasPermission('order:first-leg:create')" @click="openBatchImport"><Upload :size="17" />批量导入订单</el-button>
<el-button v-if="props.showCreateAction && auth.hasPermission('order:first-leg:create')" type="primary" :loading="pageDataLoading" :disabled="pageDataLoading || availableWarehouses.length === 0" @click="openCreate"><FilePlus2 :size="17" />创建订单</el-button>
@@ -2423,7 +2383,7 @@ async function searchOrders(model: QueryModel) {
<el-button link type="primary" class="detail-back-action" @click="router.push({ name: 'first-leg-orders' })">← 返回列表</el-button>
<div><h2>{{ detailOrder.businessSummary.inboundCode || (detailOrder.status === 'CANCELLED' ? (detailOrder.orderNo || '—') : detailOrder.status === 'DRAFT' ? '入仓码提交后生成' : '入仓码待生成') }}</h2><p v-if="detailOrder.status === 'CANCELLED'">订单已取消。</p><p v-else>{{ getFirstLegTransportModeLabel(detailOrder.transportMode) }} · {{ detailOrder.origin || '起运地待更新' }} → {{ detailOrder.destination || '目的地待更新' }}</p></div>
</div>
<div class="detail-heading-actions"><el-tag :type="getFirstLegStatusTone(detailOrder.status)" effect="light">{{ getFirstLegStatusLabel(detailOrder.status) }}</el-tag><el-button v-if="canEditOrder && canClientEditFirstLegOrder(detailOrder.status)" type="primary" plain :loading="openingEditor" @click="openEdit(detailOrder)"><Pencil :size="16" />编辑草稿</el-button><el-button v-if="canOfferCancellation(detailOrder)" type="danger" plain :loading="cancellingOrderId === detailOrder.id" :disabled="!!cancellingOrderId" @click="cancelOrder(detailOrder)">{{ pendingCancellation?.id === detailOrder.id ? '重试取消' : '取消订单' }}</el-button></div>
<div class="detail-heading-actions"><el-tag :type="getFirstLegStatusTone(detailOrder.status)" effect="light">{{ getFirstLegStatusLabel(detailOrder.status) }}</el-tag><el-button v-if="canEditOrder && canClientEditFirstLegOrder(detailOrder.status)" type="primary" plain :loading="openingEditor" @click="openEdit(detailOrder)"><Pencil :size="16" />编辑草稿</el-button><el-button v-if="canOfferCancellation(detailOrder)" type="danger" plain :loading="cancellingOrderId === detailOrder.id" :disabled="!!cancellingOrderId" @click="cancelOrder(detailOrder)">取消订单</el-button></div>
</div>
<section class="detail-section">
<h3>订单与运输</h3>