fix(first-leg): preserve edit commands and add versioned cancellation
This commit is contained in:
@@ -566,8 +566,12 @@ export function createMerchantFirstLegOrderBatch(items: MerchantBatchDraftItem[]
|
||||
})
|
||||
}
|
||||
|
||||
export function updateMerchantFirstLegOrder(id: number | string, payload: FirstLegOrderSaveRequest) {
|
||||
return apiRequest<void>({ method: 'PUT', url: `/merchant/v1/orders/first-leg/${id}`, data: payload })
|
||||
export function updateMerchantFirstLegOrder(id: number | string, payload: { expectedVersion: number; draft: FirstLegOrderSaveRequest }, idempotencyKey: string) {
|
||||
return apiRequest<void>({ method: 'PUT', url: `/merchant/v1/orders/first-leg/${id}`, data: payload, headers: { 'Idempotency-Key': idempotencyKey } })
|
||||
}
|
||||
|
||||
export function cancelMerchantFirstLegOrder(id: number | string, payload: { expectedVersion: number; reason: string }, idempotencyKey: string) {
|
||||
return apiRequest<void>({ method: 'POST', url: `/merchant/v1/orders/first-leg/${id}/cancel`, data: payload, headers: { 'Idempotency-Key': idempotencyKey } })
|
||||
}
|
||||
|
||||
export function submitMerchantFirstLegOrder(id: number | string, idempotencyKey: string) {
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import ts from 'typescript'
|
||||
import * as vue from 'vue'
|
||||
import * as pinia from 'pinia'
|
||||
|
||||
function compile(path, dependencies) {
|
||||
const source = readFileSync(new URL(path, import.meta.url), 'utf8')
|
||||
const code = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }).outputText
|
||||
const exports = {}
|
||||
new Function('require', 'exports', code)(id => { assert.ok(id in dependencies, id); return dependencies[id] }, exports)
|
||||
return exports
|
||||
}
|
||||
function harness(t) {
|
||||
const context = pinia.createPinia(); pinia.setActivePinia(context)
|
||||
t.after(() => pinia.disposePinia(context))
|
||||
const calls = []
|
||||
const behavior = { failWrite: false, failRead: false, version: 9, status: 'DRAFT' }
|
||||
const api = compile('../api/firstLeg.ts', { '@/api/http': { apiRequest: async config => {
|
||||
calls.push(structuredClone(config))
|
||||
if (config.method === 'GET') {
|
||||
if (behavior.failRead) throw new Error('读取失败')
|
||||
return { order: { id: 'one', orderNo: 'FL-ONE', version: behavior.version, status: behavior.status, receivingWarehouseId: 'warehouse', destinationCountryCode: 'US' }, cargoes: [] }
|
||||
}
|
||||
if (behavior.failWrite) throw new Error('响应丢失')
|
||||
} } })
|
||||
const module = compile('./firstLegOrders.ts', {
|
||||
vue, pinia,
|
||||
'@/modules/first-leg/api/firstLeg': api,
|
||||
'@/modules/first-leg/api/unifiedOrders': {},
|
||||
'@/modules/first-leg/utils/firstLegOrder': { canClientEditFirstLegOrder: status => status === 'DRAFT', getFirstLegStatusLabel: value => value },
|
||||
'@/modules/first-leg/utils/warehousePagination': {},
|
||||
})
|
||||
const store = module.useFirstLegOrdersStore()
|
||||
store.warehouses = [{ id: 'warehouse', name: '国内仓', warehouseType: 'DOMESTIC' }]
|
||||
const draft = { receivingWarehouseId: 'warehouse', destinationType: 'PRIVATE', destinationCountryCode: 'US', items: [], customerRemark: '原草稿' }
|
||||
return { store, api, calls, behavior, draft }
|
||||
}
|
||||
|
||||
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[0].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)
|
||||
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)
|
||||
})
|
||||
|
||||
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
|
||||
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))
|
||||
})
|
||||
|
||||
test('read failure after successful edit preserves the same command for retry', async t => {
|
||||
const h = harness(t)
|
||||
const session = h.store.beginDraftEdit(await h.store.loadDraftDetail('one'))
|
||||
h.behavior.failRead = true
|
||||
await assert.rejects(h.store.saveDraft(h.draft, '客户', 'one', session), /读取失败/)
|
||||
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])
|
||||
})
|
||||
|
||||
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
|
||||
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)
|
||||
})
|
||||
|
||||
test('cancel requires a detail version and a nonempty reason', async t => {
|
||||
const h = harness(t)
|
||||
await assert.rejects(h.store.cancelOrder('one', undefined, '理由'))
|
||||
await assert.rejects(h.store.cancelOrder('one', 1, ' '))
|
||||
assert.equal(h.calls.length, 0)
|
||||
})
|
||||
|
||||
test('cancellation decision reads raw server status and version including SUBMITTED', async t => {
|
||||
const h = harness(t)
|
||||
for (const status of ['DRAFT', 'SUBMITTED', 'APPROVED', 'ACCEPTED', 'REJECTED']) {
|
||||
h.behavior.status = status
|
||||
const target = await h.store.prepareCancellation('one')
|
||||
assert.equal(target.expectedVersion, 9)
|
||||
assert.equal(target.businessNo, 'FL-ONE')
|
||||
}
|
||||
for (const status of ['PROCESSING', 'COMPLETED', 'CANCELLED']) {
|
||||
h.behavior.status = status
|
||||
await assert.rejects(h.store.prepareCancellation('one'), /不允许取消/)
|
||||
}
|
||||
assert.ok(h.calls.every(call => call.method === 'GET'))
|
||||
})
|
||||
|
||||
function cancellationViewHarness() {
|
||||
const source = readFileSync(new URL('../views/FirstLegOrdersView.vue', import.meta.url), 'utf8').match(/<script setup lang="ts">([\s\S]*?)<\/script>/)[1]
|
||||
const ast = ts.createSourceFile('view.ts', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS)
|
||||
const functions = ast.statements.filter(node => ts.isFunctionDeclaration(node) && ['canOfferCancellation', 'cancelOrder'].includes(node.name?.text)).map(node => node.getText(ast)).join('\n')
|
||||
const code = ts.transpileModule(functions, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText
|
||||
const calls = [], messages = [], prompts = []
|
||||
const canCancelOrder = vue.ref(true), cancellingOrderId = vue.ref(''), pendingCancellation = vue.shallowRef()
|
||||
class ApiError extends Error { constructor() { super('订单版本已变化'); this.code = 'A0409'; this.status = 409 } }
|
||||
const behavior = { error: null }
|
||||
const store = {
|
||||
prepareCancellation: async id => { calls.push(['prepare', id]); return { id, expectedVersion: 12, businessNo: 'FL-ONE', statusLabel: '审核中' } },
|
||||
cancelOrder: async (...args) => { calls.push(['cancel', ...args]); if (behavior.error) throw behavior.error },
|
||||
load: async query => calls.push(['load', query]),
|
||||
}
|
||||
const ElMessageBox = {
|
||||
prompt: async (message, title, options) => { prompts.push({ message, title, options }); return { value: '客户申请取消' } },
|
||||
confirm: async (...args) => calls.push(['confirm', ...args]),
|
||||
}
|
||||
const ElMessage = { error: message => messages.push(message), warning: message => messages.push(message), success: message => messages.push(message) }
|
||||
const globals = { canCancelOrder, cancellingOrderId, pendingCancellation, store, ElMessageBox, ElMessage, ApiError,
|
||||
isDetailPage: vue.ref(true), router: { push: async route => calls.push(['route', route]) } }
|
||||
const handler = new Function(...Object.keys(globals), code + '\nreturn cancelOrder')(...Object.values(globals))
|
||||
return { handler, calls, messages, prompts, canCancelOrder, pendingCancellation, behavior, ApiError }
|
||||
}
|
||||
|
||||
test('cancel UI uses mandatory-reason centered prompt and refreshes after successful submitted-order cancellation', async () => {
|
||||
const h = cancellationViewHarness()
|
||||
await h.handler({ id: 'one', status: 'PENDING_REVIEW' })
|
||||
assert.match(h.prompts[0].message, /FL-ONE.*审核中/)
|
||||
const validate = h.prompts[0].options.inputValidator
|
||||
assert.notEqual(validate(' '), true)
|
||||
assert.notEqual(validate('x'.repeat(501)), true)
|
||||
assert.equal(validate('合理原因'), true)
|
||||
assert.deepEqual(h.calls.map(call => call[0]), ['prepare', 'cancel', 'load', 'route'])
|
||||
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 blocks unavailable permission and irreversible visible stages before reads or writes', async () => {
|
||||
const h = cancellationViewHarness()
|
||||
h.canCancelOrder.value = false
|
||||
await h.handler({ id: 'one', status: 'DRAFT' })
|
||||
h.canCancelOrder.value = true
|
||||
await h.handler({ id: 'one', status: 'LOADED' })
|
||||
assert.equal(h.calls.length, 0)
|
||||
assert.equal(h.prompts.length, 0)
|
||||
})
|
||||
|
||||
test('both editor entry points capture detail sessions and both save paths pass them', () => {
|
||||
const view = readFileSync(new URL('../views/FirstLegOrdersView.vue', import.meta.url), 'utf8')
|
||||
assert.equal((view.match(/editingSession\.value = store\.beginDraftEdit\(detailedOrder\)/g) ?? []).length, 2)
|
||||
assert.equal((view.match(/store\.saveDraft\(cloneDraft\(form\), tenantStore\.company\.companyName, editingId\.value, editingSession\.value\)/g) ?? []).length, 2)
|
||||
})
|
||||
@@ -206,9 +206,9 @@ test('only blocks submission when a known company audit status is not active', (
|
||||
assert.match(storeSource, /if \(companyAuditStatus && companyAuditStatus !== 'ACTIVE'\)/)
|
||||
})
|
||||
|
||||
test('does not expose the out-of-scope cancellation write', () => {
|
||||
assert.doesNotMatch(storeSource, /cancelMerchant|function cancel|\/cancel/)
|
||||
assert.doesNotMatch(apiSource, /\/cancel/)
|
||||
test('uses the versioned merchant cancellation contract', () => {
|
||||
assert.match(storeSource, /cancelMerchantFirstLegOrder\(id, pending\.payload, pending\.key\)/)
|
||||
assert.match(apiSource, /cancelMerchantFirstLegOrder\(id: number \| string, payload: \{ expectedVersion: number; reason: string \}, idempotencyKey: string\)/)
|
||||
})
|
||||
|
||||
test('sends an idempotency key for create and submit writes', () => {
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
getMerchantWarehouses,
|
||||
submitMerchantFirstLegOrder,
|
||||
updateMerchantFirstLegOrder,
|
||||
cancelMerchantFirstLegOrder,
|
||||
type ApiFirstLegStatus,
|
||||
type FirstLegOrderSaveRequest,
|
||||
type MerchantFirstLegOrder,
|
||||
@@ -468,9 +469,21 @@ function mapWarehouse(item: MerchantWarehouse): ClientWarehouse {
|
||||
}
|
||||
}
|
||||
|
||||
export interface DraftEditSession {
|
||||
readonly orderId: string
|
||||
readonly expectedVersion: number
|
||||
}
|
||||
|
||||
export const useFirstLegOrdersStore = defineStore('client-first-leg-orders', () => {
|
||||
const orders = ref<FirstLegOrder[]>([])
|
||||
const pendingSubmitKeys = new Map<string, 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('请重新打开草稿详情后编辑')
|
||||
return Object.freeze({ orderId: detail.id, expectedVersion: detail.version })
|
||||
}
|
||||
const warehouses = ref<ClientWarehouse[]>([])
|
||||
const loading = ref(false)
|
||||
const loadedFromApi = ref(false)
|
||||
@@ -588,18 +601,52 @@ export const useFirstLegOrdersStore = defineStore('client-first-leg-orders', ()
|
||||
return mapped
|
||||
}
|
||||
|
||||
async function saveDraft(draft: FirstLegOrderDraft, customerName: string, id?: string) {
|
||||
async function saveDraft(draft: FirstLegOrderDraft, customerName: string, id?: string, editSession?: DraftEditSession) {
|
||||
const warehouse = prepareDraftForSave(draft, warehouses.value)
|
||||
if (id) {
|
||||
const order = getById(id)
|
||||
if (!order || !canClientEditFirstLegOrder(order.status)) throw new Error('当前订单状态不允许编辑')
|
||||
await updateMerchantFirstLegOrder(id, savePayload(draft, warehouse, customerName))
|
||||
return loadLegacyDetail(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)
|
||||
const saved = await loadLegacyDetail(id)
|
||||
pendingEdits.delete(editSession)
|
||||
return saved
|
||||
}
|
||||
const createdId = await createMerchantFirstLegOrder(savePayload(draft, warehouse, customerName))
|
||||
return loadLegacyDetail(String(createdId))
|
||||
}
|
||||
|
||||
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)
|
||||
orders.value = orders.value.filter(order => order.id !== id)
|
||||
}
|
||||
|
||||
async function prepareCancellation(id: string) {
|
||||
const { order } = await getMerchantFirstLegOrder(id)
|
||||
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] }
|
||||
}
|
||||
|
||||
async function saveDraftBatch(
|
||||
drafts: Array<{ clientRowId: string; draft: FirstLegOrderDraft }>,
|
||||
customerName: string,
|
||||
@@ -621,8 +668,8 @@ export const useFirstLegOrdersStore = defineStore('client-first-leg-orders', ()
|
||||
return loadUnifiedDetail(id)
|
||||
}
|
||||
|
||||
async function submit(draft: FirstLegOrderDraft, customerName: string, id?: string, companyAuditStatus?: MerchantTenantStatus) {
|
||||
const order = await saveDraft(draft, customerName, id)
|
||||
async function submit(draft: FirstLegOrderDraft, customerName: string, id?: string, companyAuditStatus?: MerchantTenantStatus, editSession?: DraftEditSession) {
|
||||
const order = await saveDraft(draft, customerName, id, editSession)
|
||||
return submitSaved(order.id, companyAuditStatus)
|
||||
}
|
||||
|
||||
@@ -630,5 +677,5 @@ export const useFirstLegOrdersStore = defineStore('client-first-leg-orders', ()
|
||||
return loadLegacyDetail(id, getById(id))
|
||||
}
|
||||
|
||||
return { orders, warehouses, loading, loadedFromApi, loadError, warehouseLoadError, draftLoadError, activeCount, pendingCount, getById, load, loadDetail, loadDraftDetail, loadWarehouseDetail, loadWarehouseType, saveDraft, saveDraftBatch, submitSaved, submit }
|
||||
return { orders, warehouses, loading, loadedFromApi, loadError, warehouseLoadError, draftLoadError, activeCount, pendingCount, getById, load, loadDetail, loadDraftDetail, loadWarehouseDetail, loadWarehouseType, beginDraftEdit, saveDraft, prepareCancellation, cancelOrder, saveDraftBatch, submitSaved, submit }
|
||||
})
|
||||
|
||||
@@ -35,7 +35,7 @@ test('opens order creation as a dedicated protected page while keeping draft edi
|
||||
assert.match(editorShellSource, /\.editor-page-footer :deep\(\.editor-actions\) \{[^}]*justify-content: center;/)
|
||||
})
|
||||
|
||||
test('exposes real list, draft, submit, and detail workflow entries without cancellation', () => {
|
||||
test('exposes real list, draft, submit, and detail workflow entries', () => {
|
||||
assert.match(source, /function openCreate\(\)/)
|
||||
assert.match(source, /async function saveDraft\(\)/)
|
||||
assert.match(source, /function submitOrder\(\)/)
|
||||
@@ -45,7 +45,6 @@ test('exposes real list, draft, submit, and detail workflow entries without canc
|
||||
assert.match(source, /Promise\.allSettled\(\[\s*orderPageRequest,\s*companyRequest/)
|
||||
assert.match(source, /tenantStore\.loadCompanyContext\(\)/)
|
||||
assert.match(source, /await store\.loadDetail\(orderId\)/)
|
||||
assert.doesNotMatch(source, /cancelOrder|取消订单/)
|
||||
})
|
||||
|
||||
test('returns edited submissions to the refreshed order list instead of opening detail', () => {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue'
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, reactive, ref, shallowRef, watch } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { ElMessage, ElMessageBox, type FormInstance, type FormItemRule, type FormRules, type UploadRequestOptions } from 'element-plus'
|
||||
import { AlertTriangle, ChevronDown, ChevronUp, Download, FilePlus2, FileText, GripVertical, ImagePlus, MapPin, PackageCheck, Pencil, Plus, RotateCcw, Send, SlidersHorizontal, Trash2, Upload } from '@lucide/vue'
|
||||
@@ -41,7 +41,7 @@ import {
|
||||
type MerchantPricingChannel,
|
||||
type InboundCodePolicy,
|
||||
} from '@/modules/first-leg/api/firstLeg'
|
||||
import { useFirstLegOrdersStore } from '@/modules/first-leg/store/firstLegOrders'
|
||||
import { useFirstLegOrdersStore, type DraftEditSession } from '@/modules/first-leg/store/firstLegOrders'
|
||||
import { useTenantAdministrationStore } from '@/modules/tenant-management/public'
|
||||
import { useAuthStore } from '@/modules/auth/public'
|
||||
import { useUnsavedWorkRegistration } from '@/navigation/workspace-tabs/unsavedWork'
|
||||
@@ -79,6 +79,53 @@ const companyAuditLoaded = ref(false)
|
||||
const companySubmissionBlocked = computed(() => companyAuditLoaded.value && tenantStore.company.auditStatus !== 'ACTIVE')
|
||||
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)
|
||||
}
|
||||
|
||||
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}。请填写取消原因。`, '取消订单', {
|
||||
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 store.load({ includeDrafts: true })
|
||||
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 = ''
|
||||
}
|
||||
}
|
||||
const canSubmitOrder = computed(() => auth.hasPermission('order:first-leg:submit'))
|
||||
const canConfirmInboundFee = computed(() => auth.hasPermission('order:first-leg:edit'))
|
||||
const availableWarehouses = computed(() => store.warehouses.filter((warehouse) => warehouse.warehouseType === 'DOMESTIC'))
|
||||
@@ -199,6 +246,7 @@ const activeOrderQueue = ref<OrderQueue>('all')
|
||||
const editorOpen = ref(false)
|
||||
const orderFormRef = ref<FormInstance>()
|
||||
const editingId = ref<string>()
|
||||
const editingSession = shallowRef<DraftEditSession>()
|
||||
const openingEditor = ref(false)
|
||||
const copyingOrderId = ref('')
|
||||
const detailId = ref<string>()
|
||||
@@ -640,6 +688,7 @@ async function loadRouteDraft(id: string) {
|
||||
const draft = draftFromOrder(detailedOrder)
|
||||
if (draft.destinationType !== 'PRIVATE') await loadDestinationWarehouses(draft.destinationType)
|
||||
editingId.value = detailedOrder.id
|
||||
editingSession.value = store.beginDraftEdit(detailedOrder)
|
||||
replaceForm(draft)
|
||||
await Promise.all(form.items.map(ensureProductImagePreview))
|
||||
if (form.receivingWarehouseId) await loadSelectedWarehouse(form.receivingWarehouseId)
|
||||
@@ -1306,6 +1355,9 @@ function getOrderRowActions(row: object): TableAction[] {
|
||||
if (canEditOrder.value && canClientEditFirstLegOrder(order.status)) {
|
||||
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) })
|
||||
}
|
||||
if (eligibleCustomsDetail(order)) {
|
||||
actions.push({ key: 'customs', label: '报关资料', run: () => openCustomsDocuments(order) })
|
||||
}
|
||||
@@ -1368,6 +1420,7 @@ async function openEdit(order: FirstLegOrder) {
|
||||
}
|
||||
}
|
||||
editingId.value = detailedOrder.id
|
||||
editingSession.value = store.beginDraftEdit(detailedOrder)
|
||||
replaceForm(draft)
|
||||
await Promise.all(form.items.map(ensureProductImagePreview))
|
||||
if (warehouseAvailable) void loadSelectedWarehouse(detailedOrder.receivingWarehouseId)
|
||||
@@ -1958,8 +2011,9 @@ async function saveDraft() {
|
||||
if (!await validateEditorForm()) return
|
||||
saving.value = true
|
||||
try {
|
||||
const order = await store.saveDraft(cloneDraft(form), tenantStore.company.companyName, editingId.value)
|
||||
const order = await store.saveDraft(cloneDraft(form), tenantStore.company.companyName, editingId.value, editingSession.value)
|
||||
editingId.value = order.id
|
||||
editingSession.value = store.beginDraftEdit(order)
|
||||
markEditorClean()
|
||||
editorOpen.value = false
|
||||
if (isCreatePage.value) await router.push({ name: 'first-leg-orders' })
|
||||
@@ -1994,8 +2048,9 @@ async function submitOrder() {
|
||||
try {
|
||||
saving.value = true
|
||||
const knownCompanyAuditStatus = companyAuditLoaded.value ? tenantStore.company.auditStatus : undefined
|
||||
const savedOrder = await store.saveDraft(cloneDraft(form), tenantStore.company.companyName, editingId.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)
|
||||
markEditorClean()
|
||||
editorOpen.value = false
|
||||
@@ -2358,7 +2413,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 === 'DRAFT' ? '入仓码提交后生成' : '入仓码待生成') }}</h2><p>{{ 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></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>
|
||||
<section class="detail-section">
|
||||
<h3>订单与运输</h3>
|
||||
|
||||
Reference in New Issue
Block a user