feat(appointment): complete customer receiving and trip continuation workflows

This commit is contained in:
2026-10-16 15:41:56 +08:00
parent 148085286d
commit 45f662ecf2
45 changed files with 2042 additions and 131 deletions
@@ -14,7 +14,7 @@ vi.mock('./workApi', async original => ({ ...await original<typeof import('./wor
let guard: LeaveGuard
function render() { return mount(AppointmentBatchForm, { props: { batchKey: 'FBA_APPOINTMENT:1' }, global: { provide: { 'appointment-work-leave-guard': (value: LeaveGuard) => { guard = value; return () => undefined } }, stubs: {
ElButton: { props: ['nativeType', 'disabled'], template: '<button :type="nativeType || \'button\'" :disabled="disabled"><slot /></button>' },
LoadErrorState: { props: ['message'], template: '<p role="alert">{{ message }}</p>' }, ApiErrorMeta: true, CargoVerificationForm: true,
LoadErrorState: { props: ['message'], template: '<section role="alert">{{ message }}<button @click="$emit(\'retry\')">重试读取</button></section>' }, ApiErrorMeta: true, CargoVerificationForm: true,
} } }) }
beforeEach(() => {
vi.clearAllMocks(); vi.mocked(getAppointmentBatch).mockResolvedValue(batchContext())
@@ -34,6 +34,21 @@ it('submits two conservative allocations without fake confirmation times and ren
expect(wrapper.text()).toContain('AP-NEW-1'); expect(wrapper.text()).not.toContain('FBA_APPOINTMENT:')
expect(wrapper.emitted('updated')).toHaveLength(1); wrapper.unmount()
})
it('splits only the entered 60-box later batch into 40/20, never reallocating its original 160-box source', async () => {
const context = batchContext('AP-LATER-60', 'FBA_APPOINTMENT:1')
context.appointment.items = [{ ...context.appointment.items[0]!, packageCount: 60 }]
context.sources = [{ ...context.sources[0]!, packageCount: 60, originalPackages: 160 }]
vi.mocked(getAppointmentBatch).mockResolvedValue(context)
const wrapper = render(); await flushPromises()
await wrapper.get('[aria-label="来源1分出箱数"]').setValue(20)
await wrapper.findAll('textarea')[0]!.setValue('本批40先安排,20待排')
await wrapper.get('form').trigger('submit'); await flushPromises()
const request = vi.mocked(repartitionAppointments).mock.calls[0]![0]
expect(request.originals).toEqual([{ appointmentNo: 'AP-LATER-60', version: 3 }])
expect(request.batches.map(batch => batch.allocations.map(row => row.packageCount))).toEqual([[40], [20]])
expect(request.batches.flatMap(batch => batch.allocations).every(row => row.customerId === 'customer-a' && row.sourceKey === 'ORDER:1')).toBe(true)
wrapper.unmount()
})
it('locks an unknown outcome and retries the same immutable repartition command', async () => {
vi.mocked(repartitionAppointments).mockRejectedValueOnce(new Error('unknown outcome'))
const wrapper = render(); await flushPromises()
@@ -71,3 +86,98 @@ it('loads a candidate context before merging and preserves both original version
expect(repartitionAppointments).toHaveBeenCalledWith(expect.objectContaining({ originals: [{ appointmentNo: 'AP-001', version: 3 }, { appointmentNo: 'AP-002', version: 6 }], batches: [expect.objectContaining({ allocations: [expect.objectContaining({ customerId: 'customer-a', packageCount: 140 }), expect.objectContaining({ customerId: 'customer-b', packageCount: 60 })] })] }))
wrapper.unmount()
})
it('shows every terminal branch with only the original customer/source/destination quantities and opens the real batch', async () => {
const context = batchContext()
const source = context.appointment.items[0]!
context.appointment.items = [source]
context.appointment.replacementBatchKeys = ['FBA_APPOINTMENT:2', 'FBA_APPOINTMENT:3']
context.appointment.replacementAppointmentNos = ['AP-INTERMEDIATE', 'AP-20']
context.sources = []; context.allowedActions = []
const forty = batchContext('AP-40', 'FBA_APPOINTMENT:4').appointment
forty.appointmentStatus = 'SUCCESS'
forty.items = [
{ ...source, packageCount: 40 },
{ ...source, id: 'foreign-customer', customerId: 'other-customer', inboundCode: 'FOREIGN-CUSTOMER', packageCount: 900 },
{ ...source, id: 'foreign-source', sourceKey: 'ORDER:OTHER', inboundCode: 'FOREIGN-SOURCE', packageCount: 800 },
{ ...source, id: 'foreign-destination', destinationKey: 'FBA:OTHER', inboundCode: 'FOREIGN-DESTINATION', packageCount: 700 },
]
const twenty = batchContext('AP-20', 'FBA_APPOINTMENT:3').appointment
twenty.appointmentStatus = 'CANCELLED'; twenty.items = [{ ...source, packageCount: 20 }]
context.currentBatches = [forty, twenty]
vi.mocked(getAppointmentBatch).mockResolvedValue(context)
const wrapper = render(); await flushPromises()
const destinations = wrapper.get('[aria-label="当前货物去向"]')
expect(destinations.findAll('article')).toHaveLength(2)
expect(destinations.text()).toContain('40 箱'); expect(destinations.text()).toContain('20 箱')
expect(destinations.text()).toContain('已取消,分配保留')
expect(destinations.text()).not.toContain('FOREIGN-'); expect(destinations.text()).not.toContain('AP-INTERMEDIATE')
expect(destinations.text()).not.toContain('FBA_APPOINTMENT:')
await destinations.findAll('button').find(button => button.text() === '查看本批预约')!.trigger('click')
expect(wrapper.emitted('appointment')).toEqual([['AP-40']])
await destinations.findAll('button').find(button => button.text() === '查看完整批次')!.trigger('click'); await flushPromises()
expect(getAppointmentBatch).toHaveBeenLastCalledWith('FBA_APPOINTMENT:4')
expect(repartitionAppointments).not.toHaveBeenCalled(); wrapper.unmount()
})
it('does not create zero-quantity destinations or convert unknown quantities to zero', async () => {
const context = batchContext()
context.appointment.replacementBatchKeys = ['FBA_APPOINTMENT:2']
context.sources = []; context.allowedActions = []
const unknown = batchContext('AP-UNKNOWN', 'FBA_APPOINTMENT:2').appointment
unknown.items = [{ ...context.appointment.items[0]!, packageCount: null }]
const empty = batchContext('AP-EMPTY', 'FBA_APPOINTMENT:3').appointment
empty.items = [{ ...context.appointment.items[0]!, packageCount: 0 }]
context.currentBatches = [unknown, empty]
vi.mocked(getAppointmentBatch).mockResolvedValue(context)
const wrapper = render(); await flushPromises()
const destinations = wrapper.get('[aria-label="当前货物去向"]')
expect(destinations.findAll('article')).toHaveLength(1)
expect(destinations.text()).toContain('箱数待核实'); expect(destinations.text()).not.toContain('0 箱')
expect(destinations.text()).not.toContain('AP-EMPTY'); wrapper.unmount()
})
it('does not fall back to historical replacement links when current destinations are empty', async () => {
const context = batchContext()
context.appointment.replacementBatchKeys = ['FBA_APPOINTMENT:2']
context.appointment.replacementAppointmentNos = ['AP-OLD-REPLACEMENT']
context.sources = []; context.allowedActions = []; context.currentBatches = []
vi.mocked(getAppointmentBatch).mockResolvedValue(context)
const wrapper = render(); await flushPromises()
const destinations = wrapper.get('[aria-label="当前货物去向"]')
expect(destinations.findAll('article')).toHaveLength(0)
expect(destinations.text()).toContain('原快照不代表当前待办')
expect(destinations.text()).not.toContain('AP-OLD-REPLACEMENT'); wrapper.unmount()
})
it('keeps every 40/20 destination after the entire customer has left the original current items', async () => {
const context = batchContext(), originalItem = context.appointment.items[0]!
context.appointment.items = [context.appointment.items[1]!]
context.sources = [context.sources[1]!]
const forty = batchContext('AP-40', 'FBA_APPOINTMENT:40').appointment
forty.items = [{ ...originalItem, packageCount: 40 }, { ...originalItem, id: 'unrelated', sourceKey: 'ORDER:OTHER', inboundCode: 'IN-UNRELATED', packageCount: 999 }]
const twenty = batchContext('AP-20', 'FBA_APPOINTMENT:20').appointment
twenty.items = [{ ...originalItem, packageCount: 20 }]
context.currentBatches = [context.appointment, forty, twenty]
vi.mocked(getAppointmentBatch).mockResolvedValue(context)
const wrapper = render(); await flushPromises()
const destinations = wrapper.get('[aria-label="当前货物去向"]')
expect(destinations.text()).toContain('40 箱'); expect(destinations.text()).toContain('20 箱')
expect(destinations.text()).not.toContain('IN-UNRELATED')
expect(wrapper.findAll('[aria-label="来源1分出箱数"]')).toHaveLength(1)
expect((wrapper.get('[aria-label="来源1分出箱数"]').attributes('max'))).toBe('30')
wrapper.unmount()
})
it('retries a new destination without exposing the prior batch or retaining its allocation inputs', async () => {
const original = batchContext()
original.appointment.replacementBatchKeys = ['FBA_APPOINTMENT:2']; original.sources = []; original.allowedActions = []
const current = batchContext('AP-CURRENT', 'FBA_APPOINTMENT:2')
current.appointment.plannedDate = '2026-10-22'
original.currentBatches = [current.appointment]
vi.mocked(getAppointmentBatch).mockResolvedValueOnce(original).mockRejectedValueOnce(new Error('新批次暂不可用')).mockResolvedValue(current)
const wrapper = render(); await flushPromises()
await wrapper.findAll('button').find(button => button.text() === '查看完整批次')!.trigger('click'); await flushPromises()
expect(wrapper.text()).not.toContain('AP-001'); expect(wrapper.find('form').exists()).toBe(false)
await wrapper.get('[role="alert"] button').trigger('click'); await flushPromises()
expect(wrapper.text()).toContain('AP-CURRENT')
expect((wrapper.findAll('input[type="date"]')[0]!.element as HTMLInputElement).value).toBe('2026-10-22')
expect((wrapper.get('[aria-label="来源1分出箱数"]').element as HTMLInputElement).value).toBe('0')
expect(getAppointmentBatch).toHaveBeenLastCalledWith('FBA_APPOINTMENT:2')
expect(repartitionAppointments).not.toHaveBeenCalled(); wrapper.unmount()
})
@@ -20,16 +20,28 @@ const baseline = ref(JSON.stringify(form)), verification = ref<CargoVerification
const canLeave = useWorkDraft(computed(() => baseline.value !== JSON.stringify(form)), computed(() => saving.value || !!pending.value))
const candidates = ref<WorkPage | null>(null), candidatePage = ref(1), keyword = ref(''), candidateLoading = ref(false), candidateError = ref<ApiErrorDetails | null>(null)
let candidateRequest = 0
let initializedKey: string | null = null
const canWrite = computed(() => access.can('platform:overseas-warehouse:inbound-order:fba-appointment'))
const replaced = computed(() => !!context.value?.appointment.replacementBatchKeys?.length || !!context.value?.appointment.replacementAppointmentNos?.length)
const hasCurrentDestinations = computed(() => replaced.value || context.value?.currentBatches.some(batch => batch.batchKey !== context.value?.appointment.batchKey))
const currentDestinations = computed(() => {
if (!context.value) return []
const sourceIdentity = (item: FbaAppointmentBatchContext['appointment']['items'][number]) => JSON.stringify([item.customerId, item.sourceKey, item.destinationKey])
const originalSources = new Set(context.value.originalSourceRefs.map(allocationKey))
return context.value.currentBatches.map(appointment => ({ appointment, items: appointment.items.filter(item => item.destinationKey && originalSources.has(sourceIdentity(item)) && (item.packageCount == null || item.packageCount > 0)) })).filter(row => row.items.length)
})
function bookingStatus(status: string) { return ({ PENDING: '待预约', SUCCESS: '已确认预约', FAILED: '未约成', CANCELLED: '已取消,分配保留' } as Record<string, string>)[status] || '预约状态待核实' }
async function openAppointment(number: string) { if (await canLeave()) emit('appointment', number) }
const canSubmit = computed(() => canWrite.value && ready.value && !loading.value && !error.value && !!context.value?.allowedActions.includes(mode.value === 'split' ? 'SPLIT' : 'MERGE') && (mode.value !== 'merge' || !!other.value?.allowedActions.includes('MERGE')))
async function load(preserve = false) {
loading.value = true; ready.value = false; error.value = null
try {
context.value = await getAppointmentBatch(activeKey.value)
if (other.value?.appointment.batchKey) other.value = await getAppointmentBatch(other.value.appointment.batchKey)
if (!preserve) {
if (!preserve || initializedKey !== activeKey.value) {
Object.assign(form, { firstDate: context.value.appointment.plannedDate || '', nextDate: '', reason: '', remark: '', moved: Object.fromEntries(context.value.sources.map(source => [allocationKey(source), 0])) })
baseline.value = JSON.stringify(form)
initializedKey = activeKey.value
}
ready.value = true
} catch (cause) { error.value = getApiErrorDetails(cause, '批次资料读取失败') }
@@ -62,7 +74,7 @@ function sourceLabel(source: CargoVerificationSource) {
}
async function verify(source: CargoVerificationSource) { if (await canLeave()) { baseline.value = JSON.stringify(form); verification.value = source } }
async function verified() { verification.value = null; await load(); emit('updated') }
async function openBatch(key: string) { if (!await canLeave()) return; activeKey.value = key; result.value = null; other.value = null; mode.value = 'split'; await load() }
async function openBatch(key: string) { if (!await canLeave()) return; activeKey.value = key; context.value = null; result.value = null; other.value = null; mode.value = 'split'; await load() }
async function save() {
if (!context.value || !canSubmit.value || saving.value) return
if (!pending.value) {
@@ -92,7 +104,20 @@ onMounted(() => load())
<template v-if="result"><p>原批次 {{ result.replacedAppointmentNos.join('、') }} 已保留历史并被替代。</p><div v-for="appointment in result.appointments" :key="appointment.appointmentNo" class="batch-result"><strong>{{ appointment.appointmentNo }}</strong><span>{{ appointment.plannedDate || '日期未定' }} · 待安排</span><el-button @click="emit('appointment', appointment.appointmentNo)">登记安排</el-button><el-button v-if="appointment.batchKey" @click="openBatch(appointment.batchKey)">继续分批</el-button></div></template>
<template v-else-if="context">
<p>{{ context.appointment.fbaWarehouseCode }} · {{ context.appointment.items.length }} 条货物来源;客户与原来源逐票保留。</p>
<template v-if="context.appointment.replacementAppointmentNos?.length"><p>该批次已被替代,当前只读。{{ context.appointment.repartitionReason }}</p><div v-for="(number, index) in context.appointment.replacementAppointmentNos" :key="number"><el-button @click="emit('appointment', number)">{{ number }}</el-button><el-button v-if="context.appointment.replacementBatchKeys?.[index]" @click="openBatch(context.appointment.replacementBatchKeys[index]!)">查看当前批次</el-button></div></template>
<template v-if="hasCurrentDestinations">
<p v-if="replaced">该批次已被替代,原货物快照仅供追溯。{{ context.appointment.repartitionReason }}</p>
<p v-else>本批仍有保留货物,以下同时列出服务端返回的当前后送去向。</p>
<section aria-label="当前货物去向">
<h4>当前货物去向</h4><p>以下仅展示原批次客户、来源及目的仓对应的当前分配;合并批次可能还含其他货物,进入完整批次后可查看。</p>
<article v-for="destination in currentDestinations" :key="destination.appointment.batchKey" class="allocation-row">
<strong>{{ destination.appointment.appointmentNo }}</strong><p>{{ bookingStatus(destination.appointment.appointmentStatus) }} · {{ destination.appointment.plannedDate || '日期未定' }}</p>
<div v-for="item in destination.items" :key="item.id"><p>{{ item.inboundCode || '原票业务号未提供' }} · {{ item.fbaWarehouseCode }} · {{ item.packageCount == null ? '箱数待核实' : `${item.packageCount} 箱` }}</p><p>货件:{{ item.shipmentReferences?.join('、') || '待核实' }}</p></div>
<el-button :disabled="loading || !!error || saving || !!pending" @click="openAppointment(destination.appointment.appointmentNo)">查看本批预约</el-button>
<el-button v-if="destination.appointment.batchKey" :disabled="loading || !!error || saving || !!pending" @click="openBatch(destination.appointment.batchKey)">查看完整批次</el-button>
</article>
<p v-if="!currentDestinations.length && !loading && !error">当前没有与原货物范围匹配的分配;原快照不代表当前待办。</p>
</section>
</template>
<p v-for="reason in context.blockReasons" :key="reason" role="status">{{ reason }}</p>
<div v-if="!context.sources.length" aria-label="原批次货物快照"><p>当前批次无分批资格,以下为原预约保留的货物资料。</p><div v-for="(item, index) in context.appointment.items" :key="item.id" class="allocation-row"><b>来源 {{ index + 1 }} · {{ item.inboundCode || '原票业务号未提供' }}</b><p>{{ item.fbaWarehouseCode }} · {{ item.packageCount ?? '箱数待核实' }}<span v-if="item.packageCount != null"> 箱</span></p><p>货件:{{ item.shipmentReferences?.join('、') || '待核实' }}</p></div></div>
<div class="batch-modes"><el-button :disabled="saving || !!pending || !context.allowedActions.includes('SPLIT')" @click="changeMode('split')">分成两次送仓</el-button><el-button :disabled="saving || !!pending || !context.allowedActions.includes('MERGE')" @click="changeMode('merge')">同仓合并安排</el-button></div>
@@ -1,6 +1,7 @@
import { flushPromises, mount } from '@vue/test-utils'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { inject, onBeforeUnmount } from 'vue'
import { ElDialog } from 'element-plus'
import type { LeaveGuard } from './useWorkDraft'
import AppointmentCalendarView from './AppointmentCalendarView.vue'
import { getWorkCalendar, getWorkItems, getWorkSummary } from './workApi'
@@ -11,10 +12,13 @@ vi.mock('vue-router', () => ({ useRoute: () => routing, useRouter: () => routing
vi.mock('@/core/access/accessPreview', () => ({ useAccessPreviewStore: () => ({ can: (permission: string) => permission !== 'platform:overseas-warehouse:last-mile-order:list' || routing.canReadSource }) }))
vi.mock('./workApi', async original => ({ ...await original<typeof import('./workApi')>(), getWorkCalendar: vi.fn(), getWorkItems: vi.fn(), getWorkSummary: vi.fn() }))
vi.mock('./api', async original => ({ ...await original<typeof import('./api')>(), listArrivalCalendar: vi.fn() }))
function render() {
return mount(AppointmentCalendarView, { global: { stubs: {
function render(realDialog = false) {
return mount(AppointmentCalendarView, { attachTo: document.body, global: { components: { ElDialog }, directives: { loading: {} }, stubs: {
teleport: true,
ElTooltip: { template: '<slot />' },
ElDialog: realDialog ? ElDialog : { name: 'ElDialog', props: ['modelValue', 'title', 'fullscreen', 'beforeClose', 'closeOnClickModal', 'closeOnPressEscape'], emits: ['update:modelValue'], template: '<div v-if="modelValue" class="el-dialog" :class="{ \'is-fullscreen\': fullscreen }"><button aria-label="关闭工作面板" @click="beforeClose(() => $emit(\'update:modelValue\', false))">关闭</button><slot name="header" /><slot /><slot name="footer" /></div>' },
AdminPage: { template: '<main><slot /></main>' },
ElButton: { template: '<button><slot /></button>' },
ElButton: { props: ['type'], template: '<button type="button" :data-variant="type"><slot /></button>' },
WorkCalendarPanel: { name: 'WorkCalendarPanel', props: ['anchor', 'mode', 'flow', 'types', 'calendar', 'failed', 'reference', 'selectedDate', 'selectedType'], template: '<div data-calendar><slot name="inbox" /></div>' },
WorkDetailPanel: { name: 'WorkDetailPanel', props: ['itemKey', 'initialAction', 'canLeave'], setup() {
const register = inject<(guard: LeaveGuard) => () => void>('appointment-work-leave-guard')!
@@ -35,6 +39,21 @@ describe('appointment work calendar', () => {
vi.mocked(getWorkItems).mockResolvedValue({ records: [workItem()], page: 1, size: 8, total: 1, pages: 1 })
vi.mocked(listArrivalCalendar).mockResolvedValue([])
})
it('retains the old batch and page when a resolved later batch continues into its vehicle work', async () => {
routing.query = { workAnchor: '2026-10-15', workScope: 'global', workView: 'UNDATED', workPage: '3', workItem: 'old-batch-work' }
const wrapper = render(); await flushPromises()
wrapper.getComponent({ name: 'WorkDetailPanel' }).vm.$emit('open', 'later-batch-work'); await flushPromises()
expect(wrapper.getComponent({ name: 'WorkDetailPanel' }).props('itemKey')).toBe('later-batch-work')
wrapper.getComponent({ name: 'WorkDetailPanel' }).vm.$emit('open', 'later-vehicle-work', followAction); await flushPromises()
expect(wrapper.getComponent({ name: 'WorkDetailPanel' }).props('itemKey')).toBe('later-vehicle-work')
await wrapper.get('.panel-nav button').trigger('click'); await flushPromises()
expect(wrapper.getComponent({ name: 'WorkDetailPanel' }).props('itemKey')).toBe('later-batch-work')
await wrapper.get('.panel-nav button').trigger('click'); await flushPromises()
expect(wrapper.getComponent({ name: 'WorkDetailPanel' }).props('itemKey')).toBe('old-batch-work')
await wrapper.get('.panel-nav button').trigger('click'); await flushPromises()
expect(getWorkItems).toHaveBeenLastCalledWith(expect.objectContaining({ view: 'UNDATED', page: 3 }), expect.any(AbortSignal))
wrapper.unmount()
})
it('opens the real work calendar by default and converts its half-open helper range to the inclusive API contract', async () => {
const wrapper = render(); await flushPromises()
expect(wrapper.text()).toContain('预约工作日历')
@@ -65,8 +84,8 @@ describe('appointment work calendar', () => {
await wrapper.get('.work-row-action button').trigger('click'); await flushPromises()
const detail = wrapper.getComponent({ name: 'WorkDetailPanel' }).vm
routing.allowLeave = false
await wrapper.get('.panel-tools button:first-child').trigger('click')
expect(wrapper.get('.work-panel').classes()).toContain('is-expanded')
await wrapper.get('[aria-label="展开全屏"]').trigger('click')
expect(wrapper.get('.el-dialog').classes()).toContain('is-fullscreen')
expect(wrapper.getComponent({ name: 'WorkDetailPanel' }).vm).toBe(detail)
await wrapper.get('[aria-label="关闭工作面板"]').trigger('click'); await flushPromises()
expect(wrapper.find('.work-panel').exists()).toBe(true)
@@ -75,6 +94,45 @@ describe('appointment work calendar', () => {
expect(wrapper.find('.work-panel').exists()).toBe(false)
wrapper.unmount()
})
it.each(['mask', 'escape'] as const)('closes from %s through the real dialog without bypassing draft protection', async method => {
const wrapper = render(true); await flushPromises()
await wrapper.get('[data-view="ALL"]').trigger('click'); await flushPromises()
await wrapper.get('.work-row-action button').trigger('click'); await flushPromises()
await wrapper.get('.panel-body').trigger('click')
expect(wrapper.find('[data-detail]').exists()).toBe(true)
const dismiss = async () => {
if (method === 'mask') {
const mask = wrapper.get('.el-overlay-dialog')
await mask.trigger('mousedown'); await mask.trigger('mouseup'); await mask.trigger('click')
} else {
document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', code: 'Escape', bubbles: true }))
}
await flushPromises()
}
routing.allowLeave = false
await dismiss()
expect(wrapper.find('[data-detail]').exists()).toBe(true)
routing.allowLeave = true
await dismiss()
expect(wrapper.find('.work-panel').exists()).toBe(false)
wrapper.unmount()
})
it.each(['VIEW_DETAIL', 'VIEW_HISTORY', 'SAVE_FOLLOWUP'] as const)('keeps %s navigation intact while distinguishing read-only actions', async code => {
const nextAction = { ...followAction, code, label: '服务端动作文案' }
vi.mocked(getWorkItems).mockResolvedValue({ records: [workItem({ nextAction })], page: 1, size: 8, total: 1, pages: 1 })
const wrapper = render(); await flushPromises()
await wrapper.get('[data-view="ALL"]').trigger('click'); await flushPromises()
const button = wrapper.get('.work-row-action button')
expect(button.attributes('data-variant')).toBe(code === 'SAVE_FOLLOWUP' ? 'primary' : 'default')
expect(wrapper.get('.item-schedule').text()).toContain('作业日期未定')
expect(wrapper.get('.item-schedule').text()).toContain('America/Los_Angeles')
expect(wrapper.get('.item-context').text()).toContain('地点:ONT8')
expect(wrapper.get('.item-context').text()).toContain('负责人:测试调度')
expect(wrapper.get('.item-context').text()).toContain('跟进:2026-10-15')
await button.trigger('click'); await flushPromises()
expect(wrapper.getComponent({ name: 'WorkDetailPanel' }).props('initialAction')).toEqual(nextAction)
wrapper.unmount()
})
it('sends an explicit safe return context with external business navigation', async () => {
routing.query = { workAnchor: '2026-10-15', workItem: 'work:1', workScope: 'global', workView: 'UNDATED', workPage: '3', workOrigins: '["work:0"]' }
const wrapper = render(); await flushPromises()
@@ -83,6 +141,18 @@ describe('appointment work calendar', () => {
expect(routing.push).toHaveBeenCalledWith({ path: '/overseas-master-data/trips/TR-001', query: { tab: 'loading', appointmentReturn: expect.stringContaining('/appointment-calendar?') } })
wrapper.unmount()
})
it('keeps a successful save in the current detail and retains the original global page on return', async () => {
routing.query = { workAnchor: '2026-10-15', workItem: 'work:1', workScope: 'global', workView: 'UNDATED', workPage: '3' }
const wrapper = render(); await flushPromises()
const detail = wrapper.getComponent({ name: 'WorkDetailPanel' }).vm
detail.$emit('saved', { item: workItem(), affectedWorkItemKeys: [] }, 'SAVE_FOLLOWUP'); await flushPromises()
expect(wrapper.getComponent({ name: 'WorkDetailPanel' }).vm).toBe(detail)
expect(getWorkItems).toHaveBeenLastCalledWith({ view: 'UNDATED', page: 3, size: 8 }, expect.any(AbortSignal))
await wrapper.get('.panel-nav button').trigger('click'); await flushPromises()
expect(wrapper.find('[data-detail]').exists()).toBe(false)
expect(getWorkItems).toHaveBeenLastCalledWith({ view: 'UNDATED', page: 3, size: 8 }, expect.any(AbortSignal))
wrapper.unmount()
})
it('retains all global counts and unfiltered global detail through month, flow and all-off layer changes', async () => {
const wrapper = render(); await flushPromises()
await wrapper.get('[data-view="UNDATED"]').trigger('click'); await flushPromises()
@@ -1,8 +1,9 @@
<script setup lang="ts">
import '@/styles/adminDensity.css'
import { computed, nextTick, onBeforeUnmount, onMounted, provide, ref, watch } from 'vue'
import { computed, onBeforeUnmount, onMounted, provide, ref, watch } from 'vue'
import { onBeforeRouteLeave, onBeforeRouteUpdate, useRoute, useRouter } from 'vue-router'
import AdminPage from '@/shared/components/AdminPage.vue'
import AppDialog from '@/shared/components/AppDialog.vue'
import LoadErrorState from '@/shared/components/LoadErrorState.vue'
import ApiErrorMeta from '@/shared/components/ApiErrorMeta.vue'
import { getApiErrorDetails, type ApiErrorDetails } from '@/shared/api/http'
@@ -48,21 +49,11 @@ const heading = computed(() => {
})
const scopeDescription = computed(() => scope.value?.kind === 'day' ? '按所选日期、流程与类型查询,包含已完成事项' : scope.value?.kind === 'arrivals' ? '独立到港来源,不计工作量;来源未提供流程筛选,展示该日全部参考' : '跨月份、流程与类型,包含未预约和未定日期事项')
const panelOpen = computed(() => !!scope.value || !!detailKey.value || !!sourceLink.value)
const panelExpanded = ref(false), panelHeading = ref<HTMLElement | null>(null), panelBody = ref<HTMLElement | null>(null)
const panelBody = ref<HTMLElement | null>(null)
const selectedDate = computed(() => scope.value?.kind === 'day' || scope.value?.kind === 'arrivals' ? scope.value.date : undefined)
const selectedType = computed(() => scope.value?.kind === 'day' && scope.value.types.length === 1 ? scope.value.types[0] : undefined)
const panelTitle = computed(() => sourceLink.value ? '货源与预约' : detailKey.value ? '事项详情' : heading.value)
const listVisible = computed(() => !sourceLink.value && !detailKey.value && scope.value?.kind !== 'arrivals')
let panelTrigger: HTMLElement | null = null
watch(panelOpen, async open => {
if (open) {
panelTrigger = document.activeElement instanceof HTMLElement ? document.activeElement : null
await nextTick(); panelHeading.value?.focus()
} else {
panelExpanded.value = false
await nextTick(); if (panelTrigger?.isConnected) panelTrigger.focus()
}
})
watch([detailKey, sourceLinkKey, scope, page], () => { if (panelBody.value) panelBody.value.scrollTop = 0 }, { flush: 'post' })
const guards = new Set<LeaveGuard>()
provide('appointment-work-leave-guard', (guard: LeaveGuard) => { guards.add(guard); return () => { guards.delete(guard) } })
@@ -131,9 +122,15 @@ async function back() {
if (!origin && !scope.value) scope.value = { kind: 'global', view: 'ALL' }
if (!origin) await loadItems()
}
async function closePanel() {
if (!await canLeave()) return
scope.value = null; detailKey.value = null; initialAction.value = null; sourceLink.value = null; origins.value = []; ++itemsRequest; itemsController?.abort()
let closingPanel = false
async function closePanel(done: () => void) {
if (closingPanel) return
closingPanel = true
try {
if (!await canLeave()) return
done()
scope.value = null; detailKey.value = null; initialAction.value = null; sourceLink.value = null; origins.value = []; ++itemsRequest; itemsController?.abort()
} finally { closingPanel = false }
}
async function filterCalendar(change: () => void) {
if (!await canLeave()) return
@@ -149,7 +146,7 @@ async function saved(result?: WorkCommandResult, command?: WorkCommand['command'
if (command === 'CONFIRM_ROUTE' && result?.item.containers[0]) {
const container = result.item.containers[0]
scope.value = { kind: 'container', containerBookingId: container.containerBookingId, label: container.containerNo || container.bookingNo || '本柜' }; page.value = 1; detailKey.value = null; origins.value = []; initialAction.value = null
} else { detailKey.value = origins.value.pop() || null; initialAction.value = null; sourceLink.value = null }
} else { if (origins.value.length) detailKey.value = origins.value.pop()!; initialAction.value = null; sourceLink.value = null }
await Promise.all([loadCalendar(), loadSummary(), loadItems()])
}
async function refreshWork() { await Promise.all([loadCalendar(), loadSummary(), loadItems()]) }
@@ -197,20 +194,22 @@ onBeforeUnmount(() => { ++calendarRequest; ++summaryRequest; ++itemsRequest; ++r
<WorkCalendarPanel :selected-date="selectedDate" :selected-type="selectedType" :anchor="anchor" :mode="mode" :flow="flow" :types="types" :calendar="calendar" :loading="calendarLoading" :failed="!!calendarError" :reference="reference" :arrivals="arrivals" :reference-ready="referenceReady" @anchor="offset => filterCalendar(() => anchor = moveCalendar(anchor, mode, offset))" @today="filterCalendar(() => anchor = dateKey(new Date()))" @mode="value => filterCalendar(() => mode = value)" @flow="value => filterCalendar(() => flow = value)" @types="value => filterCalendar(() => types = value)" @reference="toggleReference" @day="(date, type) => setScope({ kind: 'day', date, types: type ? [type] : [...types], flow })" @arrivals="date => setScope({ kind: 'arrivals', date })">
<template #inbox>
<nav class="work-inbox" aria-label="全局待办">
<button v-for="button in summaryButtons" :key="button.view" type="button" :data-view="button.view" :aria-pressed="scope?.kind === 'global' && scope.view === button.view" @click="setScope({ kind: 'global', view: button.view })">{{ viewLabels[button.view] }} <strong>{{ summaryLoading ? '…' : summaryError ? '加载失败' : summary?.[button.field] ?? '—' }}</strong></button><span>不受日历筛选影响 · 数量可重叠</span>
<button v-for="button in summaryButtons" :key="button.view" type="button" :data-view="button.view" :aria-pressed="scope?.kind === 'global' && scope.view === button.view" @click="setScope({ kind: 'global', view: button.view })">{{ viewLabels[button.view] }} <strong :class="{ 'is-zero': !summaryLoading && !summaryError && summary?.[button.field] === 0, 'is-overdue': !summaryLoading && !summaryError && button.view === 'OVERDUE' && (summary?.overdue ?? 0) > 0 }">{{ summaryLoading ? '…' : summaryError ? '加载失败' : summary?.[button.field] ?? '—' }}</strong></button><span>全局待办 · 不受日历筛选影响 · 数量可重叠</span>
</nav>
<LoadErrorState v-if="summaryError" title="全局待办读取失败" :message="summaryError.message" :loading="summaryLoading" @retry="loadSummary"><template #details><ApiErrorMeta :details="summaryError" /></template></LoadErrorState>
</template>
</WorkCalendarPanel>
<aside v-if="panelOpen" class="work-panel" :class="{ 'is-expanded': panelExpanded }" aria-label="工作明细与事项操作">
<AppDialog :model-value="panelOpen" :title="panelTitle" class="admin-density-dialog admin-density appointment-work work-dialog" width="min(1120px, calc(100vw - 48px))" fullscreenable append-to-body :close-on-click-modal="true" :close-on-press-escape="true" :before-close="closePanel" :show-footer="listVisible && !!items && !itemsError && !itemsLoading" destroy-on-close>
<template #header>
<header class="panel-header">
<div class="panel-nav"><button v-if="detailKey || sourceLink" type="button" @click="back">‹ {{ origins.length ? '返回原事项' : '返回工作明细' }}</button><div class="panel-tools"><button type="button" :aria-expanded="panelExpanded" @click="panelExpanded = !panelExpanded">{{ panelExpanded ? '收起面板' : '展开面板' }}</button><button type="button" aria-label="关闭工作面板" @click="closePanel">关闭 ×</button></div></div>
<h3 ref="panelHeading" tabindex="-1">{{ panelTitle }}</h3>
<div class="panel-nav"><button v-if="detailKey || sourceLink" type="button" @click="back">‹ {{ origins.length ? '返回原事项' : '返回工作明细' }}</button><h3>{{ panelTitle }}</h3></div>
<template v-if="!detailKey && !sourceLink">
<p class="scope-description">{{ scopeDescription }}</p>
<div v-if="scope?.kind === 'day'" class="bucket-buttons"><button v-for="bucket in buckets" :key="bucket.label" type="button" :aria-pressed="scope.bucket === bucket.key" @click="setBucket(bucket.key)">{{ bucket.label }}</button></div>
</template>
</header>
</template>
<section v-if="panelOpen" class="work-panel" aria-label="工作明细与事项操作">
<div ref="panelBody" class="panel-body">
<p v-if="origins.length" class="origin-context">正在处理关联前置事项,完成后可继续原事项。</p>
<p v-if="navigationError" role="alert">{{ navigationError }}</p>
@@ -222,15 +221,21 @@ onBeforeUnmount(() => { ++calendarRequest; ++summaryRequest; ++itemsRequest; ++r
<p v-if="itemsLoading" role="status">正在读取明细…</p>
<template v-else-if="items && !itemsError">
<article v-for="item in items.records" :key="item.workItemKey" class="work-row">
<div class="work-row-action"><el-button v-if="item.nextAction" type="primary" @click="openItem(item.workItemKey, item.nextAction)">{{ item.nextAction.label }}</el-button><el-button v-else @click="openItem(item.workItemKey)">查看详情</el-button></div>
<div class="work-row-content"><div class="item-heading"><button type="button" class="item-title" @click="openItem(item.workItemKey)">{{ item.title }}</button><span class="item-status">{{ workStatus(item) }}</span></div><p>{{ typeLabels[item.type] }} · {{ workDate(item) }} · {{ item.timezone || '地点时区待核实' }}</p><p>{{ item.destinationName || item.originName || '地点待核实' }} · {{ flowLabels[item.flow] }} · {{ item.owner?.name || '待分派' }}<span v-if="item.followupDate"> · 跟进 {{ item.followupDate }}</span></p><p v-for="reason in [...item.overdueReasons, ...item.blockReasons]" :key="reason" class="work-warning">{{ reason }}</p></div>
<div class="work-row-action"><el-button v-if="item.nextAction" :type="['VIEW_DETAIL', 'VIEW_HISTORY'].includes(item.nextAction.code) ? 'default' : 'primary'" @click="openItem(item.workItemKey, item.nextAction)">{{ item.nextAction.label }}</el-button><el-button v-else @click="openItem(item.workItemKey)">查看详情</el-button></div>
<div class="work-row-content">
<div class="item-heading"><button type="button" class="item-title" @click="openItem(item.workItemKey)">{{ item.title }}</button><span class="item-status">{{ workStatus(item) }}</span></div>
<p class="item-schedule"><span class="item-date">{{ workDate(item) }}</span><span>{{ item.timezone || '地点时区待核实' }}</span></p>
<p class="item-context"><span v-if="!item.title.endsWith(typeLabels[item.type])">{{ typeLabels[item.type] }}</span><span>{{ flowLabels[item.flow] }}</span><span>地点:{{ item.destinationName || item.originName || '地点待核实' }}</span><span>负责人:{{ item.owner?.name || '待分派' }}</span><span v-if="item.followupDate">跟进:{{ item.followupDate }}</span></p>
<p v-for="reason in [...item.overdueReasons, ...item.blockReasons]" :key="reason" class="work-warning">{{ reason }}</p>
</div>
</article>
<p v-if="!items.records.length">当前范围没有工作事项。</p>
</template>
</template>
</div>
<footer v-if="listVisible && items && !itemsError && !itemsLoading" class="panel-footer"><span>共 {{ items.total }} 项</span><div v-if="items.total > 8" class="work-pagination"><button type="button" :disabled="page <= 1" @click="changePage(page - 1)">上一页</button><span>{{ page }} / {{ Math.max(1, Math.ceil(items.total / 8)) }}</span><button type="button" :disabled="page * 8 >= items.total" @click="changePage(page + 1)">下一页</button></div></footer>
</aside>
</section>
<template #footer><footer v-if="items" class="panel-footer"><span>共 {{ items.total }} 项</span><div v-if="items.total > 8" class="work-pagination"><button type="button" :disabled="page <= 1" @click="changePage(page - 1)">上一页</button><span>{{ page }} / {{ Math.max(1, Math.ceil(items.total / 8)) }}</span><button type="button" :disabled="page * 8 >= items.total" @click="changePage(page + 1)">下一页</button></div></footer></template>
</AppDialog>
</div>
</AdminPage>
</template>
@@ -242,6 +247,9 @@ onBeforeUnmount(() => { ++calendarRequest; ++summaryRequest; ++itemsRequest; ++r
.work-inbox { padding: var(--admin-space-2) var(--admin-space-5); }
.work-inbox button { display: flex; gap: var(--admin-space-3); align-items: center; }
.work-inbox strong { font-variant-numeric: tabular-nums; }
.work-inbox strong.is-zero { color: var(--el-text-color-secondary); font-weight: 400; }
.work-inbox strong.is-overdue { color: var(--el-color-danger-dark-2); }
.appointment-work .work-inbox button[aria-pressed=true] { box-shadow: inset 0 -2px 0 var(--el-color-primary); }
.work-search input { width: 280px; }
.appointment-work button:not(.el-button), .appointment-work input { font: inherit; }
.appointment-work button:not(.el-button) { cursor: pointer; min-height: var(--admin-control-height); border: 1px solid var(--cc-border); border-radius: var(--admin-radius); background: var(--admin-surface); padding: 0 var(--admin-space-3); }
@@ -249,24 +257,28 @@ onBeforeUnmount(() => { ++calendarRequest; ++summaryRequest; ++itemsRequest; ++r
.appointment-work input { min-height: var(--admin-control-height); border: 1px solid var(--cc-border); border-radius: var(--admin-radius); padding: 0 var(--admin-space-3); }
.appointment-work button:not(.el-button):focus-visible, .appointment-work input:focus-visible, .panel-header h3:focus-visible { outline: 2px solid var(--el-color-primary); outline-offset: 1px; }
.work-layout { position: relative; min-width: 0; }
.work-panel { position: absolute; top: 0; right: 0; z-index: 4; width: min(680px, 100%); height: min(720px, calc(100dvh - 260px)); min-height: 320px; box-sizing: border-box; display: flex; flex-direction: column; border: 1px solid var(--cc-border); background: var(--admin-surface); box-shadow: var(--el-box-shadow-light); overflow-wrap: anywhere; }
.work-panel.is-expanded { width: 100%; }
.panel-header { flex: none; padding: var(--admin-space-3) var(--admin-space-5); border-bottom: 1px solid var(--cc-border); }
.panel-nav, .panel-tools { display: flex; align-items: center; gap: var(--admin-space-3); }
.panel-tools { margin-left: auto; }
.panel-header h3 { font-size: var(--admin-font-section); margin: var(--admin-space-2) 0; }
:global(.work-dialog.el-dialog:not(.is-fullscreen)) { height: 88dvh; max-height: 88dvh; margin-top: 6dvh; }
:global(.work-dialog .el-dialog__body) { display: flex; flex: 1; overflow: hidden; }
:global(.work-dialog .app-dialog__body) { display: flex; flex: 1; min-width: 0; }
.work-panel { min-width: 0; min-height: 0; flex: 1; display: flex; flex-direction: column; overflow-wrap: anywhere; }
.panel-header { flex: none; min-width: 0; font-size: var(--admin-font-body); font-weight: 400; }
.panel-nav { display: flex; align-items: center; gap: var(--admin-space-3); }
.panel-header h3 { font-size: var(--admin-font-title); margin: var(--admin-space-2) 0; }
.scope-description { margin: var(--admin-space-1) 0; }
.panel-body { flex: 1; min-height: 0; overflow-y: auto; overscroll-behavior: contain; padding: 0 var(--admin-space-5) var(--admin-space-3); }
.panel-footer { display: flex; align-items: center; justify-content: space-between; gap: var(--admin-space-3); flex-wrap: wrap; flex: none; padding: var(--admin-space-3) var(--admin-space-5); border-top: 1px solid var(--cc-border); font-size: var(--admin-font-caption); }
.panel-body { flex: 1; min-height: 0; overflow-y: auto; overscroll-behavior: contain; padding: 0 var(--admin-space-1); }
.panel-footer { display: flex; align-items: center; justify-content: space-between; gap: var(--admin-space-3); flex-wrap: wrap; flex: none; font-size: var(--admin-font-caption); }
.origin-context { background: var(--el-fill-color-light); padding: var(--admin-space-3); }
.work-row { display: grid; grid-template-columns: 108px minmax(0, 1fr); gap: var(--admin-space-3); padding: var(--admin-space-4) 0; border-bottom: 1px solid var(--cc-border); }
.work-row-action .el-button { white-space: normal; width: 100%; min-height: var(--admin-control-height); height: auto; padding: var(--admin-space-2); line-height: 20px; }
.work-row-action :deep(.el-button > span) { min-width: 0; max-width: 100%; white-space: normal; overflow-wrap: anywhere; line-height: inherit; }
.work-row-content { min-width: 0; }
.item-heading { display: flex; align-items: baseline; justify-content: space-between; gap: var(--admin-space-3); }
.item-status { flex: none; color: var(--el-text-color-secondary); font-size: var(--admin-font-caption); }
.work-row-content p { margin: var(--admin-space-1) 0; color: var(--el-text-color-secondary); font-size: var(--admin-font-caption); line-height: 1.6; }
.item-status { flex: none; color: var(--el-text-color-regular); background: var(--el-fill-color-light); border-radius: var(--admin-radius); padding: 0 var(--admin-space-2); font-size: var(--admin-font-caption); line-height: 24px; }
.work-row-content p { margin: var(--admin-space-1) 0; color: var(--el-text-color-regular); font-size: var(--admin-font-body); line-height: 1.6; }
.item-schedule, .item-context { display: flex; flex-wrap: wrap; column-gap: var(--admin-space-4); row-gap: 2px; }
.item-date { color: var(--el-text-color-regular); font-variant-numeric: tabular-nums; }
.appointment-work .work-row-content .item-title { border: 0; padding: 0; text-align: left; min-height: 24px; color: var(--el-color-primary); background: transparent; font-weight: 600; }
.work-row-content .work-warning { color: var(--el-color-warning-dark-2); }
.work-row-content .work-warning { color: var(--el-color-warning-dark-2); border-left: 2px solid var(--el-color-warning-light-5); padding-left: var(--admin-space-2); }
.work-pagination, .bucket-buttons { display: flex; align-items: center; gap: var(--admin-space-2); flex-wrap: wrap; }
.bucket-buttons { margin-top: var(--admin-space-2); }
.bucket-buttons button { font-size: var(--admin-font-caption); }
@@ -1,11 +1,148 @@
# 预约工作日历逐操作矩阵
本轮依据:`C:/Users/BY-OY/.codex/visualizations/2026/10/14/01a13a8d-e968-7962-906b-1a514792d921/appointment-calendar-guided.html`(v10)与预约工作日历开发协作契约 v1。下表取代旧三视图、整行选货和日历辅助方案;不改变原业务实际执行入口。
本轮依据:`C:/Users/BY-OY/.codex/visualizations/2026/10/14/01a13a8d-e968-7962-906b-1a514792d921/appointment-calendar-guided.html`(V13,SHA-256 `61902e410be755aa9cbf9fcfaa9d393bfa49dd8d592cd8773af5396e78c29836`)及 `docs/海外仓业务/预约工作日历V13变更说明.md`、开发协作契约。保留既有日历和居中弹框优化,不改变原业务实际执行入口。
本次密度调整依据:用户提供的主页面截图 `codex-clipboard-93984795-68cb-4082-96b3-c83189d8a357.png`、展开明细截图 `codex-clipboard-a98edd3b-82af-4f1b-989e-7d0f028e0965.png`,以及用户确认的压缩留白、日期定位、控件统一、零值弱化和统计范围说明。
2026-10-16 当前承载调整:用户反馈“点击外面关闭不了,也看不清”。日期/类型/全局明细、事项详情、原侧边编辑表单和到港参考统一改用带遮罩的居中 `AppDialog`,常规宽度 1120px、高度 88dvh,支持全屏;标题与分页固定、仅正文滚动。遮罩、Esc 和关闭按钮统一经过未保存/提交结果待确认保护。此结论优先于下表早期侧边承载描述;原业务独立页面跳转、确认流程和统计口径保持原样。改后待人工截图确认。
V13 日历布局:按已确认定高要求,月日格固定 146px,周日格固定 270px;只展示五类服务端计数和独立到港参考,不追加逐事项卡片、不依明细条数扩高。替代下表早期“随内容自然增高”的结论;不裁掉五类入口,仍需人工核对 1920×1080、100% 下完整内容。
## V13 前端本轮最终收口(2026-10-16)
已完成 cargo-refresh 按客户最新资料预览/明确采用、60+40 原排车单共车续办,以及原车当前/历史稳定批次引用。当前合同与具体范围以下述对应章节为准,早期分批检查数字仅为过程记录。
- 最新完整受影响组合:41 文件、357 项通过(18.64 秒),覆盖全部 appointment-calendar、Fleet trips API/页面/安排/交接、排车预排/详情/列表及密度合同。
- 全量前端 `pnpm test`:397 文件、3290 项通过(137.44 秒),无失败;存在既有 Vue const reactive v-model 编译提示,本批未扩展修改无关模块。
- 最终 `pnpm typecheck` 通过;`pnpm build`(另含 vue-tsc)通过,Vite 16.24 秒,仅既有 AnalyticsChart 588.19 kB 分块警告。`git diff --check` 通过。
- 本地日志:`.logs/appointment-v13-final-combined.log`、`appointment-v13-final-full-test.log`、`appointment-v13-final-typecheck.log`、`appointment-v13-final-build.log`;冻结文件与 SHA-256 清单为 `.logs/appointment-v13-frontend-freeze.json`。日志为本地证据,不提交。
- 本轮前端冻结;没有提交、推送、部署、SQL 或真实 HTTP。人工 1920×1080、100% 截图与真实 60+40 装载、客户移出后重进、后送 40/20、cargo-refresh 持久事实仍待总控组织验收。后端客户间 FAILED/PENDING 排车资格隔离由总控收口,不改变本轮前端合同。
## V13 第一批实现与接口依赖
### 本批收货覆盖合同接入
已按生产者 `FbaReceivingContracts.java`、`FbaReceivingController.java`、`FbaReceivingService.java` 和 `appointment-receiving-v1.yaml` 接入 `receivingApi.ts`,浏览器前缀为 `/platform/v1/last-leg/appointment-receiving`(公共 HTTP 层统一提供 `/api`)。真实入口如下:
- GET `/batches/{batchKey}` 和 `/agreements/{agreementKey}`:读取批次、当前覆盖、待确认变化、车辆范围版本及重约 eligible/excluded。
- POST `/changes` 和 `/changes/{changeKey}/resolve`:逐来源先送 0..当前量,持久 WAITING;明确回复 CONFIRM 或撤回 WITHDRAW。保留原批次/来源/核实/transport 版本,未知结果重试原幂等命令。
- POST `/bookings`:一份共同 booking 或每成员独立 booking,沿用当前批次,不新建货物;取消组携带原 agreementKey/version,只提交 eligible 成员。
- POST `/agreements/{agreementKey}/reschedule`、`/cancel`:展示整份当前范围,提交真实范围版本;取消需要 delete 权限及二次确认,普通编辑和客户移出分别遵循 Controller 的独立权限组合。
接入文件:`WorkReceivingPanel.vue`、只读 `ReceivingScope.vue`;入口为 `WorkAppointmentForm.vue` 的“客户调整 / 共同预约范围”,由 `WorkDetailPanel.vue` 在原居中弹框内装配并保留结果。Member.customerName、Source.inboundCode 已消费,无名无号显示“—”,不以内部标识回退。原批次快照未提供客户名时只能从已返回的覆盖成员匹配或显示“—”,不猜客户名称。
结果只报告服务端实际 steps;本地原子事务失败不包装成部分成功。待确认结果明确原安排未变;保存成功但刷新失败只重试 GET。范围变化后保留输入并重新确认;重约成员集合变化时禁止把原输入套给新成员,显式重新填写。已返回的真实车次可跳原详情核对,后送步骤按 ALLOCATE_CARGO.targetKey 匹配成功批次,不取任意第一批;无业务号不拼车辆链接。未知箱数不替换为 0 或加入可预约范围。
本批前端直接验证:`receivingApi.test.ts`、`WorkReceivingPanel.test.ts`、`WorkDetailPanel.test.ts`、`WorkAppointmentForm.test.ts` 共 4 文件、36 项通过,`pnpm typecheck` 通过。未重复全模块测试或全量构建。生产者已通知新源码编译通过,但本批后端回归和真实环境验收尚无通过结论;不能据前端模拟 HTTP 的定向测试宣称端到端通过。
后续闭合情况见下节:子批真实事项解析、原车按需客户卡片、原来源过滤及单批真实托盘预选均已接入;重约按最新 executionScope/executionVersion 判断客户资格;普通调整和整份操作继续使用 transportVersion。以下早期依赖表用于逐场景定位,新合同的实际实现与剩余缺口以本节及下节为准。
已消费的合同为 `workApi.ts`、`batchApi.ts`、`planningApi.ts` 及原预约/排车 API。本批不新增接口或推导数量。已接核心冻结的 `FbaAppointmentBatchContext.currentBatches`:服务端解析全部替代分支、按稳定批次去重,前端只显示与 originalSourceRefs 的 customerId/sourceKey/destinationKey 完全匹配的当前明细,合并后的其他来源不算入原范围。未知箱数不显示 0,零量不生成去向卡片,空结果不回退历史替代链接。`replacementBatchKeys` 只用于识别历史快照,不能据此推导当前 20/40 箱去向。取消保留分配后的续办通过原预约更新接口提交版本和幂等键,不整票重建或重新分配。当前前端 `splitBatch` 与表单一次拆两批;服务端普通 repartition 的 DTO/OpenAPI 已支持 1 至 20 个非空目标批次,普通多批能力不构成接口依赖。本轮 100/60、40/20 保持两批交互。先送 0、已确认且有车的客户移出、共约范围变更仍需专用命令,不能以普通分批代替;尚未冻结的共享范围命令继续等待生产者。
| V13 场景 | 当前前端与直接检查 | 依赖/剩余验收 |
|---|---|---|
| 01 整客户 160 移出续办 | `WorkDetailPanel.test.ts` 保存后读取主要下一步;`WorkExistingDispatchForm.test.ts` 沿用真实排车单继续安排本批车辆 | 单客户移出命令、当前数量/车辆版本、原车 120 保留结果及后续目标;真实发车签收待集成 |
| 02 100 先送、60 后送 | `AppointmentBatchForm.test.ts` 保留普通分批与来源版本;`WorkDetailPanel.test.ts` 区分未定作业日和跟进日 | 已确认预约/装载关系的部分移出与调整回复语义,不能以普通分批代替 |
| 03 后送 60 加另一客户 40 共车 | 本批与另一客户按实际托盘各建排车单;结果页“与同仓其他排车单共车”沿业务号核对两单后复用 TripPreparationDialog/Fleet prepare,可加入已有计划车次;WorkDispatchForm、WorkSharedTripForm、TripPreparationDialog、trips API 测试覆盖传递与导航 | 实物须能对应本次数量,不能对应时先走原库存拆托;共车后的路线、容量、审核及发车须真实 HTTP 验收,非任意箱级拆托开发缺口 |
| 04 后送 40 新批、20 待排 | `AppointmentBatchForm.test.ts` 消费 `currentBatches` 的 40/20 全部分支;逐客户/来源/目的仓过滤,排除合并的其他货物;未知量不当 0 | 已接客户变化确认及真实批次续办;已接当前/历史排车全量批次引用,实际装载链待集成;实物拆托是原库存前置 |
| 05 全部再分配后的旧入口 | `AppointmentBatchForm.test.ts` 只显示当前终点,不显示中间替代批次;零量无卡片,空结果不回退旧链接,原快照明确仅供追溯 | 服务端负责图遍历及稳定键去重;真实多次再分配与跨页返回待集成 |
| 06 待回复先保存再续办 | `WorkAppointmentForm` 保留计划/确认分开;`WorkDetailPanel` 保存后留在当前项 | 单客户调整草稿、仓库回复范围、待确认变化、原车阻断条件 DTO/命令 |
| 07 共约旧约号冲突 | 原预约错误继续保留表单;不按文本约号判断共约 | 生产者共约身份、当前覆盖成员、唯一性冲突合同;真实冲突验收待集成 |
| 08 整份改期、无变化保存 | `WorkAppointmentForm.test.ts` 无变化及空白字符归一化后不重复提交;跨日/偏移原样保留 | 整份范围、成员版本、车辆影响与无变化后端幂等;不能仅凭前端禁用证明不重复复核 |
| 09 整份取消后共同重约 | `WorkAppointmentForm.test.ts` 已接取消保留分配后的原批更新续办,可先保存日期未定/PENDING;保留历史、版本及幂等键,不再创建整票;取消不能重复提交,只读权限不能续办 | 整组共同/分别重约已接 receiving Book,消费 eligible/excluded;新关联及原车实际资格待后端/集成验收 |
| 10 分别重约与排除已另约成员 | 不复制现有逐票新建接口实现假整组成功 | 当前组资格、排除原因、分别重约结果、冲突/部分失败续办及所有时段核对 |
| 11 保留量为 0、原车无货 | 当前前端普通拆分保留两批均非空的交互约束,不绕过服务端业务资格 | “取消本次安排/全部移出”专用语义、无货原车权威处理结果;不能用空批次代替 |
| 12 未定日期、换月、图层、分页 | `AppointmentCalendarView.test.ts` 全局范围不带日历条件,保存后留在当前详情、返回保持原分页;既有前置返回/外部路由上下文继续检查;`WorkDetailPanel.test.ts` 跟进日不作作业日 | 新去向与新范围的上下文等待对应稳定标识;人工截图与真实再进入待验 |
| 13 部分失败、超时、并发 | `WorkDispatchForm.test.ts` 重试原草稿、不重锁已提交实物;`WorkDetailPanel.test.ts` 保存成功但下一步读取失败仅重试 GET、旧操作禁用;`WorkAppointmentForm.test.ts` 原批重约结果未知同键重试,明确冲突保留输入、读取新版本后显式再提交 | 多步骤逐项结果/可重试动作及范围版本合同;现有草稿恢复不代表跨域 V13 全部已完成 |
| 14 权限、失败、时区、DST | 既有 work/form/presentation/API 直接测试保留;来源失败显示明确错误 | 新增合同对应权限/版本/持久幂等与真实时区场景待生产者和集成验证 |
| 15 五类计数、真实车次与执行门槛 | `WorkCalendarPanel.test.ts` 五类聚合固定数量入口,服务端 2 批送仓/1 车原样展示;日格定高,不在浏览器重算车辆数;原实际执行入口保留 | 去重由后端保证;直送卸货、还空、共车发车资格及接手结果继续真实验收 |
当前定向检查(含首批与 currentBatches/原批重约新增 6 项):`pnpm test src/modules/appointment-calendar src/styles/adminDensity.test.ts`,29 文件、210 项通过;`pnpm typecheck` 通过。完整测试/构建窗口按开发协作契约交总控安排,本批未执行。以上是本地实现与检查,不表示部署或 15 项全链已验收;居中弹框及新增去向/续办内容仍待人工截图确认。
### 60+40 两步共车入口
`WorkSharedTripForm.vue` 仅按明确排车业务号读取两单,复用原 Fleet 安排弹框。真实 60/40 数量从两单读取,不自行生成装载结论;已关联、异仓、重复、错误业务号均不进入安排。子弹框打开时保护父工作面板,成功导航服务端返回的车次。增量联通检查覆盖 WorkDispatchForm、WorkSharedTripForm、既有 TripPreparationDialog 与 trips API;完整本轮验证见下一节。
### 最新货物资料显式采用
已消费 RefreshCargo/REFRESH_CARGO:WorkReceivingPanel 按客户提供“核对并采用本客户最新货物资料”,只按该客户原来源读取既有 cargo-verification(预约及尾程列表读权限),展示原票、本批箱数、最新核实/有效/已分配量及货件号。读取不会保存核实资料或自动采用。源/核实版本、身份、目的地、起运仓、未知分配、已分配超量及来源阻断均检查;任何一票失败不提交部分范围。
明确确认后 POST `/appointment-receiving/cargo-refresh` 只携带该客户成员及显示的 batchVersion、executionVersion、各来源最新版本;不提交箱数或正式确认。已确认、待变化、已完成客户禁用。冲突后重读并清除确认,未知结果保持原请求键,成功刷新事项并可继续本客户计划/正式预约,不跳回会影响其他客户的旧整批 PUT。
本轮共车与资料采用最初组合为 8 文件、81 项通过;已被下述当前/历史引用收口后的完整组合覆盖。未执行 HTTP、部署或人工截图。
### 客户级普通计划补齐(V13 06 / 09 / 10)
- 已消费实际 `Context.plans`、`CustomerPlan` 和 `Plan`,通过 POST `/appointment-receiving/plans` 提交明确 batchKey/customerId/batchVersion、executionVersion 与幂等键。`WorkReceivingPanel` 客户卡片和本批重约范围提供“保存目标 / 未约成”;不走旧整批 PUT,不改变甲的确认或借分批保存日期。
- 只允许 PENDING/FAILED,FAILED 必须有原因;普通计划无外部约号和正式确认时间。资格同时要求 PLAN_RECEIVING、当前执行资格、无活动确认和无待变化记录。时区来自该客户计划(未有计划时来自批次目的仓);非空目标缺时区阻止提交。计划窗口支持跨日及 startOffset/endOffset,DST 歧义或不存在时间由权威接口校验;只填日期或全空目标不带偏移。
- 回显优先当前 batch/customer 的 plans,明确空日期保持空;无独立客户计划时,仅无任何有效独立覆盖且 header 为 PENDING/FAILED 才带入旧计划和原因,剔除正式确认。混合覆盖不借甲日期,CANCELLED 不回填旧目标。混合状态测试为同一稳定批次中甲已有独立确认、乙与丁未确认;覆盖乙保存日期、未约成、清空日期、丁从空白开始、只读/已完成/待变化禁用、版本冲突保留输入、未知结果同键重试、UNCHANGED、跨日/DST 和未知时区。保存后刷新当前工作事项,保留 receiving 面板及真实结果,原“记录回复与跟进”入口保留。
- 整组取消后支持按客户勾选子集,共同或分别确认只提交所选成员。通过实际只读 POST `/appointment-receiving/execution-scope` 查询所选 batch/customer 的执行资格,使用返回版本,不复用全组或猜测 token;保留展示时的 batchVersion/groupVersion。选择变化清除范围确认,读失败禁止提交,可单独重读;过期异步响应不覆盖新选择。新增同批仅甲独立确认、跨批仅乙子集、分别表单与客户匹配、查询失败及迟到响应回归。
- 直接测试:`WorkReceivingPanel.test.ts`、`receivingApi.test.ts`、`WorkDetailPanel.test.ts`、`TripAppointmentPanel.test.ts` 共 4 文件、56 项通过;`pnpm typecheck` 和最终 `pnpm build`(含 vue-tsc)通过,构建 4.78 秒;仅既有 AnalyticsChart 约 588 kB 分块警告。`git diff --check` 通过。本批前端冻结。未执行真实 HTTP、部署或人工截图验收;服务端甲确认不变、客户计划工作域投影及日历归属仍由总控集成核对。
### 本批续办、原车入口和历史来源收敛
- `batchApi.ts` 必需字段 `originalSourceRefs` 已与生产者 SourceRef/OpenAPI 同步;`AppointmentBatchForm` 与 `TripAppointmentPanel` 均按完整客户/来源/目的地过滤当前全部去向。原批仍保留货物但另有后送批时也显示当前去向。全客户移出后不再依赖原批当前 items,且不拿历史来源授权可分配数量;新增全移出、40/20、合并其他来源隔离回归。
- `workApi.ts`、`WorkBatchContinuation.vue` 接真实客户级解析;保存原/后送预约后继续当前子批事项,原事项留作返回上下文,多客户不默认取第一项。
- `TripDetailView.vue` 按需装配公开 `TripAppointmentPanel`:本车当前 appointmentBatches 与 previousDispatches 稳定引用→批次/currentBatches/receiving 范围;客户卡片列当前所有匹配去向,直接进入对应客户调整或当前批次续办。新弹框复用未保存/未知结果保护,刷新车次和路由离开也经过保护,业务提交后刷新本车事实。
- `WorkDispatchForm.vue` 从单客户单批入口仅预选当前合格实物,候选跨批/客户、重复实物、未知箱数均不误选;提交仍复制服务端 allocations。可直接进入本批逐来源分批,60→40/20 测试只提交该 60 的原批和来源版本,不把原总量 160 再分配。多客户、超车型容量不自动全选;真实整托无法覆盖的部分箱量不伪造实物。
- `WorkReceivingPanel.test.ts` 新增跨批 A 已另约、仅 B/D eligible 的重约回归:提交 B/D 的真实 batchKeys 与 GroupContext.executionScope.version(Book.executionVersion),不带回 A,也不使用原 A/B/D 范围版本或运输版本。待确认 WITHDRAW 仍可提交,不以普通货物可变性条件禁用撤回。
- 最新接收合同已消费:ChangeIntent.ownerId 由本人、当前事项及关联事项负责人候选选择,父事项传入候选,不新增用户目录或用自由姓名充当账号;Pending.followup 展示服务端 ownerName/nextFollowupDate。普通正式预约按 Context.executionScope 排除 completed 或 canRebook=false 的客户,整组按服务端 eligibleMembers;Book 只提交对应 executionVersion,运输展示或无关客户的运输阻断不再一刀切禁止重约。货物调整、确认/撤回和整份改期/取消仍使用 transportVersion。新增负责人候选/真实姓名、已完成 A 不挡未完成 B、缺失执行资格不擅自放行等回归。
当前合同接入、实物前置与真实验收边界:
1. 原车当前/历史引用已按冻结 DTO 接入:`DispatchResponse.appointmentBatches`、`TripBinding.appointmentBatches` 与 `Detail.previousDispatches` 均为必需数组,`batchNo` 允许 null,不依赖可空 `fbaAppointmentNo` 或内部排车 ID。`TripAppointmentPanel` 按批次/客户聚合并对排车业务号、来源和当前终点去重,精确匹配客户/来源/目的地,只展示 `currentBatches` 当前量。历史卡片只提供追溯和权威解析后的当前工作入口,不使用历史数量授权调整或排车。`appointmentHistoryUnavailableReason` 单独提示,缺乏证据的引用不开入口,当前车次仍可读。已补空原约号、多批引用、历史客户移出后重进、40/20 全去向、其他客户/来源隔离、重复记录、缺失历史提示和错误身份回归。真实持久历史及装载链待集成验收。
2. 60+40 按真实两步流程收口:各客户按本批分配及实际托盘生成排车单,WorkDispatchForm 结果页进入 WorkSharedTripForm,按另一张业务号重读两单,核对当前状态、未绑定及真实起运仓一致后交给既有 TripPreparationDialog;Fleet prepare 复用多个 dispatchNos,可新建或加入原计划车次。未新增共车命令、未扫描全局待办、未按名称推仓。数量不能映射完整实物时必须先走原库存拆托,这属于实物前置,不列为待开发任意拆托;仍待真实 60+40 HTTP 和装载链验收。
3. receiving 仍以当前源码接入,待核心与工作事项后端回归及真实场景。UI 本地通过不证明服务端初始化、同步及最终执行门槛已经部署验收。
验证:最新完整定向命令 `pnpm test src/modules/appointment-calendar src/modules/overseas-master-data/pages/TripsBehavior.test.ts src/styles/adminDensity.test.ts` 34 文件、260 项通过;`pnpm typecheck` 通过。`pnpm build`(含 vue-tsc)通过,Vite 构建 3.92 秒;既有 AnalyticsChart 约 588 kB 分块警告保留,无构建失败。`git diff --check` 通过;未提交、发布或部署,真实页面待人工截图确认。
### 下一批精确接入点与合同门槛
下表路径除特别标注外相对 `src/modules/appointment-calendar/`。新增语义仅列需求,不预定义字段名、HTTP 路径或动作代码。生产者交付真实 DTO/OpenAPI、权限、直接测试后再接写入;不在现有普通分批或跟进命令中夹带未实现的共约调整。
| 接入点与现有真实入口 | 可用部分 | 尚需生产者提供的精确语义 |
|---|---|---|
| `AppointmentBatchForm.vue`、`batchApi.ts`;GET `/appointment-planning/batches/{batchKey}`、POST `/appointment-planning/appointments/repartition` | 原来源核实、当前前端一次拆两批(服务端支持最多 20 批)、全部当前终点 | 车次/排车单到逐客户逐来源当前装载的引用;当前可调整量及版本;先送 0/全量/中间量各自资格;移出确认后原车保留结果与后送批次,是否有待确认草稿。不能把现有 splitBatch 的非空限制直接删除 |
| `WorkAppointmentForm.vue`、`overseas-warehouse/api/inboundOrders.ts` 的 get/updateFbaAppointment;`api.ts` 的 deleteAppointment | 单批计划、确认、取消、原批续办、同键重试 | 独立共同预约身份、范围版本、当前成员/箱数/原确认时段/关联车辆、仅本客户或整份的允许动作;读取待回复变化及保存/确认/拒绝语义。旧事实与待确认输入分别返回,不能写普通计划来冒充移出成功 |
| `WorkAppointmentForm.vue` 的重约衔接,后续独立共约表单只在合同冻结后装配 | 已取消单批沿原号 update,保留分配 | 整组重约的当前候选、已退出/已另约/已完成/其他处理中成员与原因、各成员当前去向;共用/独立结果、新有效关系身份、仓库覆盖确认依据、原车复用资格及范围并发校验 |
| `WorkDispatchForm.vue`、`WorkExistingDispatchForm.vue`;`overseas-warehouse/api/dispatches.ts` 的 getBatchDispatchCandidates、草稿锁定/预排;既有 TripPreparationDialog | 按真实托盘、每客户排车,再沿已有排车单安排车辆 | 已按当前真实整托候选分别创建客户排车单,再从结果页使用另一张已备排车单业务号共车;本批默认只选当前合格实物。部分箱量无法映射时先走原库存拆托,非本轮新建任意拆托接口需求;真实资源资格和装载链待 HTTP |
| `overseas-master-data/pages/TripDetailView.vue` 本车排车单及 `overseas-warehouse/pages/DispatchesView.vue` | 原业务排车、审核、装载、发车规则继续使用;当前任务未修改这些页面 | 本车客户卡片的客户业务名称、batchKey/来源/数量/当前预约覆盖、未确认变化、当前去向与可调整目标;对应允许动作;原车无货的权威关闭结果。不能以解除排车单关联替代客户移出 |
| `WorkDetailPanel.vue`、`workApi.ts` 的 GET `/appointment-work/items/{key}` | 消费 allowedActions、nextAction、blockReasons、relatedItems;保存成功后刷新 | 新命令的稳定目标与白名单动作、受影响工作键、原批到当前批次的工作项引用。当前 currentBatches 只有预约快照,子批保存后不能凭业务号或拼接 batchKey 猜新工作键;目前仍刷新进入时的原事项 |
| `WorkDetailPanel.vue`、`AppointmentCalendarView.vue`、`workNavigation.ts` | 日期、月份、流程、类型、范围、分页及原事项返回已有支持 | 新结果逐步骤成功/失败/待补、已持久保存对象、失败步骤允许的重试动作和幂等身份;用于只重试失败部分,并明确原车和后送需求都存在 |
独立修复:`WorkAppointmentForm` 首次读取失败后重试须初始化真实确认资料和偏移;版本冲突后仍保留已编辑输入。`AppointmentBatchForm` 切换当前去向先清除旧快照,首次读新批失败再重试须按新批初始化日期/数量,不能复用旧批草稿。对应新增直接测试分别在同名 `.test.ts`;不涉及新合同或环境写入。本次仅运行上述两个测试文件,16 项通过(新增 2 项);未重复运行上一批完整模块检查。
只读联审的子批续办缺口已接入真实 GET `/appointment-work/items/resolve?batchKey=...&customerId=...`:`BatchWorkResolution` 返回唯一 detail 或多客户 candidates。`WorkBatchContinuation.vue` 多候选必须明确选客户,再读权威 detail;读失败只重试 GET。`WorkAppointmentForm` 保存返回真实预约快照,`WorkDetailPanel` 用其 batchKey 定位子批,刷新摘要但不再先刷新旧事项/弹回旧事项。`WorkDetailPanel.test.ts` 与 `AppointmentCalendarView.test.ts` 已覆盖子批下一步、车辆续办、返回旧事项及原未定日期分页;工作键不在浏览器拼接。
### V13 集成操作与判定清单(待合同与集成窗口)
以下是验收设计,不是通过记录。01–11 每项恢复独立的甲 80、乙 160、丁 40 基准,均按客户+来源+目的地核对,不跨场景累计;涉及环境写入时由总控按授权窗口执行。
| 场景 | 操作与必须观察到的结果 |
|---|---|
| 01 | 原车乙卡片先送 0,确认仓库回复后原车 120、乙后送 160;沿乙入口重新约仓/用车,其他客户确认不变,无新增整票占量 |
| 02 | 乙先送 100、后送 60,后送不填日期;原车 220,60 在全局未定日期可续办,跟进日不填入送货日 |
| 03 | 从 60 入口按实际托盘形成客户排车单;另一客户 40 同理。结果页核对两单业务号与真实同仓资格后,沿 Fleet 安排同一车次;分别/共同约仓范围可辨,一车 100,客户归属保留。实物不匹配先走原库存拆托 |
| 04 | 后送 60 再选 40,原车客户卡片列 40 新批与 20 待排各一次;两者可直达,不把合并的其他客户数算入乙 |
| 05 | 后送量全部再分配,旧入口显示全部当前终点;中间历史、0 箱卡片和重复后送待办均不出现 |
| 06 | 调整后先保存待仓库回复,退出再进入仍有待确认输入,旧有效安排保留;未解决前发车被阻断,继续明确回复后只影响对应范围 |
| 07 | 退出客户填写他人有效旧约号,提交冲突后保留号码、时段及输入;不自动加入共同预约;重新读取范围后明确再提交 |
| 08 | 选择整份共同改期,先核对完整当前成员和车辆;保存同一新时段只影响相关已安排工作,再次无变化保存与复核不新生复核 |
| 09 | 整份取消后旧确认和失效目标清除、历史保留;共同重约只选仍需履约成员,仓库确认覆盖后产生新有效关联,沿可用原车续办 |
| 10 | 一名成员先独立另约,再进入整组重约;其被排除并显示去向,退出/已完成/其他处理中成员同样不可静默加入;其他成员可分别重约 |
| 11 | 先送为 0 合法,全量先送不产生空后送;原车所有有效货物移出后按原车命令关闭待办,已发车则进入原异常处理,不能普通移出 |
| 12 | 未定日期分页进入→切月份/图层→当前批续办→返回;原范围、分页、日期及筛选恢复,全局待办不因日历筛选丢失 |
| 13 | 分别在货物保存、车辆关联、读取下一步失败处中断;只重试失败步骤,未知结果同键,已成功批次/排车/车次不重复创建;显示真实部分结果 |
| 14 | 只读权限、来源不可用、版本变化、约号冲突、跨日和 DST 逐项验证;首次 GET 失败重试不得出现空白可写旧事实,冲突后保留输入,未知数量不作 0 |
| 15 | 五类高计数仍固定日格,同车多批只计一辆车;中转与直送分别走真实备货/卸货/还空门槛,未完成卸货或未接手责任不能借复核结束工作 |
阻塞场景不以按钮禁用、静态截图或 Mock 成功响应记为已验收。合同冻结后先扩充对应组件/API 定向测试,再由总控安排真实场景及 1920×1080、100% 人工截图。本次读取恢复修复后的 `pnpm typecheck` 和 `git diff --check` 均通过;未执行全量构建、真实 HTTP 或部署。
| 本次操作 | 证据与现状 | 调整结论 |
|---|---|---|
| 列表信息层级与日历视觉细化 | 用户 2026-10-16 截图 `codex-clipboard-6858cde3-eda3-4a02-a043-e1a47143f67c.png`、`codex-clipboard-5a68965d-cdbd-4ce9-b8b3-385d9d76b4f2.png`,并明确要求按建议优化 | 查看详情/历史使用普通描边按钮,办理动作保留主色且仍在左侧;完整标题、状态、作业时间、时区、地点、流程、负责人、跟进日期及异常分层显示。日历类型改浅色底与弱边框,保留语义色、今天/选中态;周末表头与到港参考保持辅助层级,零值弱化、超期数字提示。保留现有覆盖面板、字号、统计和动作链;改后待人工截图确认 |
| 工作明细左侧长操作按钮 | Admin #621 真实 1920×1080 截图 `baiyue-firstleg/reports/appointment-browser-20261015/admin-621-follow-today-1920.png`;按钮与文本实际行高仅 13px | 保留完整文案和 108px 操作列,统一使用 20px 行高、自然换行和自适应高度;普通/展开面板及主操作/查看详情使用同一规则 |
| 流程与工具栏分组 | 用户后续流程下拉、日期工具栏及上下操作区截图(`115df974`、`d217350b`、`80dd9fa1`) | 流程改为四个直接切换按钮;全局待办、流程、日期与类型筛选收进连续白底工作区,各行靠左,保留全局与区间统计边界 |
| 日历浏览与日期选择 | 主页面截图;原型 `renderCalendar()`、`.day.selected`、`.todaymark` | 缩小日格空白,今天与选择态分别标识;零项日期只显示日期;显示实际查询起止日期,保留加载失败状态 |
@@ -0,0 +1,15 @@
<script setup lang="ts">
import type { ReceivingMember, ReceivingTransport } from './receivingApi'
defineProps<{ members: ReceivingMember[]; transport?: ReceivingTransport }>()
</script>
<template>
<div aria-label="当前覆盖范围">
<div v-for="(member, index) in members" :key="`${member.batchKey}:${member.customerId}`" class="receiving-member">
<b>{{ member.appointmentNo }} · {{ member.customerName || '—' }} · 范围 {{ index + 1 }}</b>
<p v-for="source in member.sources" :key="`${source.sourceKey}:${source.destinationKey}`">{{ source.inboundCode || '—' }} · {{ source.packageCount }} 箱</p>
</div>
<p v-if="!members.length">当前无可纳入的货物。</p>
<template v-if="transport"><p v-for="(vehicle, index) in transport.vehicles" :key="index">车辆:{{ vehicle.tripNo || '车次未关联' }} · 排车单 {{ vehicle.dispatchNo || '未关联' }} · {{ vehicle.packageCount }} 箱</p><p v-for="reason in transport.blockReasons" :key="reason" role="status">{{ reason }}</p><p v-if="!transport.vehicles.length">当前未关联车辆。</p></template>
</div>
</template>
<style scoped>.receiving-member { border-bottom: 1px solid var(--cc-border); padding-block: var(--admin-space-3); }</style>
@@ -0,0 +1,102 @@
import { flushPromises, mount } from '@vue/test-utils'
import { beforeEach, expect, it, vi } from 'vitest'
import TripAppointmentPanel from './TripAppointmentPanel.vue'
import { getDispatch, getFbaAppointment, type DispatchBatchReference } from '@/modules/overseas-warehouse'
import { getAppointmentBatch } from './batchApi'
import { getReceivingContext } from './receivingApi'
import { batchContext } from './batch.test-support'
vi.mock('vue-router', () => ({ onBeforeRouteLeave: vi.fn() }))
vi.mock('@/core/access/accessPreview', () => ({ useAccessPreviewStore: () => ({ can: () => true }) }))
vi.mock('@/modules/overseas-warehouse', async original => ({ ...await original<typeof import('@/modules/overseas-warehouse')>(), getDispatch: vi.fn(), getFbaAppointment: vi.fn() }))
vi.mock('./batchApi', async original => ({ ...await original<typeof import('./batchApi')>(), getAppointmentBatch: vi.fn() }))
vi.mock('./receivingApi', async original => ({ ...await original<typeof import('./receivingApi')>(), getReceivingContext: vi.fn() }))
const reference = (batchKey = 'FBA_APPOINTMENT:1', batchNo: string | null = 'AP-001'): DispatchBatchReference => ({ batchKey, batchNo, customerId: 'customer-a', sources: [{ sourceKey: 'ORDER:1', destinationKey: 'FBA:ONT8', packageCount: 70 }] })
function render(overrides: Partial<InstanceType<typeof TripAppointmentPanel>['$props']> = {}) { return mount(TripAppointmentPanel, { props: { dispatches: [{ dispatchNo: 'DS-A', customerId: 'customer-a', packageCount: 70, appointmentBatches: [reference()] }], previousDispatches: [], historyUnavailableReason: null, canWrite: true, ...overrides }, global: { stubs: {
ElButton: { props: ['disabled'], template: '<button :disabled="disabled"><slot /></button>' },
AppDialog: { props: ['modelValue'], template: '<div v-if="modelValue"><slot /></div>' },
WorkReceivingPanel: { name: 'WorkReceivingPanel', props: ['batchKey', 'initialCustomerId'], template: '<div data-receiving />' },
WorkBatchContinuation: { name: 'WorkBatchContinuation', props: ['batchKey', 'customerId'], template: '<div data-continuation />' },
AppointmentBatchForm: true, WorkAppointmentForm: true,
LoadErrorState: { props: ['message'], template: '<p role="alert">{{ message }}</p>' },
} } }) }
beforeEach(() => {
vi.clearAllMocks()
vi.mocked(getAppointmentBatch).mockResolvedValue(batchContext())
vi.mocked(getReceivingContext).mockResolvedValue({ batch: batchContext().appointment, agreements: [], pendingChanges: [], plans: [], executionScope: { version: 'execution-v1', members: [] }, transport: { version: 'scope-v1', vehicles: [], blockReasons: [] }, allowedActions: [], blockReasons: [] })
})
it('renders all current 40/20 destinations for the bound customer and directly opens the exact customer adjustment', async () => {
const context = batchContext(), forty = batchContext('AP-40', 'FBA_APPOINTMENT:40').appointment, twenty = batchContext('AP-20', 'FBA_APPOINTMENT:20').appointment
forty.items[0]!.packageCount = 40; forty.items[1]!.packageCount = 999; twenty.items = [{ ...context.appointment.items[0]!, packageCount: 20 }]
context.currentBatches = [forty, twenty]; vi.mocked(getAppointmentBatch).mockResolvedValue(context)
const wrapper = render(); await flushPromises()
expect(wrapper.text()).toContain('40 箱'); expect(wrapper.text()).toContain('20 箱'); expect(wrapper.text()).not.toContain('999')
expect(wrapper.text()).not.toContain('internal-dispatch'); expect(wrapper.text()).not.toContain('customer-a')
await wrapper.findAll('button').find(button => button.text() === '调整本客户先送 / 后送')!.trigger('click'); await flushPromises()
expect(wrapper.getComponent({ name: 'WorkReceivingPanel' }).props()).toMatchObject({ batchKey: 'FBA_APPOINTMENT:1', initialCustomerId: 'customer-a' })
wrapper.unmount()
})
it('continues a current destination by its batch and customer rather than guessing a work key', async () => {
const wrapper = render(); await flushPromises()
await wrapper.findAll('button').find(button => button.text() === '继续本批当前工作')!.trigger('click'); await flushPromises()
const continuation = wrapper.getComponent({ name: 'WorkBatchContinuation' })
expect(continuation.props()).toMatchObject({ batchKey: 'FBA_APPOINTMENT:1', customerId: 'customer-a' })
continuation.vm.$emit('open', 'real-work-key'); expect(wrapper.emitted('work')).toEqual([['real-work-key']]); wrapper.unmount()
})
it('uses historical source refs when the bound customer has completely left the original batch', async () => {
const context = batchContext(), moved = context.appointment.items[0]!
context.appointment.items = [context.appointment.items[1]!]
const current = batchContext('AP-LATER', 'FBA_APPOINTMENT:2').appointment
current.items = [{ ...moved, packageCount: 70 }]; context.currentBatches = [context.appointment, current]
vi.mocked(getAppointmentBatch).mockResolvedValue(context)
const wrapper = render(); await flushPromises()
expect(wrapper.text()).toContain('AP-LATER')
expect(wrapper.text()).toContain('IN-A · 70 箱')
expect(wrapper.text()).not.toContain('范围当前不可匹配'); wrapper.unmount()
})
it('reports missing references and read failures without looking up legacy appointment numbers', async () => {
const wrapper = render({ dispatches: [{ dispatchNo: 'DS-A', customerId: 'customer-a', packageCount: 70, appointmentBatches: [] }] }); await flushPromises()
expect(wrapper.text()).toContain('没有预约批次引用')
expect(getDispatch).not.toHaveBeenCalled(); expect(getFbaAppointment).not.toHaveBeenCalled(); expect(getAppointmentBatch).not.toHaveBeenCalled()
vi.mocked(getAppointmentBatch).mockRejectedValueOnce(new Error('read failed'))
await wrapper.setProps({ dispatches: [{ dispatchNo: 'DS-A', customerId: 'customer-a', packageCount: 70, appointmentBatches: [reference()] }] }); await flushPromises()
expect(wrapper.get('[role="alert"]').text()).toContain('读取失败'); wrapper.unmount()
})
it('reads all stable references without a legacy appointment number and deduplicates repeated bindings', async () => {
vi.mocked(getAppointmentBatch).mockImplementation(async key => batchContext(key === 'FBA_APPOINTMENT:1' ? 'AP-001' : 'AP-002', key))
vi.mocked(getReceivingContext).mockImplementation(async key => ({ batch: batchContext('AP', key).appointment, agreements: [], pendingChanges: [], plans: [], executionScope: { version: 'v1', members: [] }, transport: { version: 'v1', vehicles: [], blockReasons: [] }, allowedActions: [], blockReasons: [] }))
const refs = [reference(), reference('FBA_APPOINTMENT:2', 'AP-002')]
const wrapper = render({ dispatches: [{ dispatchNo: 'DS-A', customerId: 'customer-a', packageCount: 100, appointmentBatches: refs }, { dispatchNo: 'DS-B', customerId: 'customer-a', packageCount: 70, appointmentBatches: [reference()] }] }); await flushPromises()
expect(wrapper.findAll('article')).toHaveLength(2)
expect(wrapper.text()).toContain('DS-A、DS-B'); expect(wrapper.text()).toContain('AP-002')
expect(getAppointmentBatch).toHaveBeenCalledTimes(2); expect(getReceivingContext).toHaveBeenCalledTimes(2)
expect(getDispatch).not.toHaveBeenCalled(); expect(getFbaAppointment).not.toHaveBeenCalled(); wrapper.unmount()
})
it('reenters a removed customer through history and displays only current 40/20 source destinations', async () => {
const context = batchContext(), source = context.appointment.items[0]!
const forty = batchContext('AP-40', 'FBA_APPOINTMENT:40').appointment, twenty = batchContext('AP-20', 'FBA_APPOINTMENT:20').appointment
forty.items = [{ ...source, packageCount: 40 }, { ...source, id: 'other', sourceKey: 'ORDER:OTHER', inboundCode: 'OTHER-SOURCE', packageCount: 888 }]
twenty.items = [{ ...source, packageCount: 20 }, { ...context.appointment.items[1]!, packageCount: 777 }]
context.originalSourceRefs.push({ customerId: 'customer-a', sourceKey: 'ORDER:OTHER', destinationKey: 'FBA:ONT8' })
context.appointment.items = []; context.currentBatches = [forty, twenty, forty]
vi.mocked(getAppointmentBatch).mockResolvedValue(context)
const previous = { dispatchNo: 'DS-REMOVED', customerId: 'customer-a', recordVersion: 4, recordedAt: '2026-10-16T01:00:00Z', appointmentBatches: [{ ...reference(), sources: [{ ...reference().sources[0]!, packageCount: 9999 }] }] }
const wrapper = render({ dispatches: [], previousDispatches: [previous, { ...previous, recordVersion: 5 }] }); await flushPromises()
expect(wrapper.findAll('article')).toHaveLength(1)
expect(wrapper.text()).toContain('仅供追溯'); expect(wrapper.text()).toContain('40 箱'); expect(wrapper.text()).toContain('20 箱')
for (const unexpected of ['9999', '888', '777', 'OTHER-SOURCE', '调整本客户先送 / 后送']) expect(wrapper.text()).not.toContain(unexpected)
const buttons = wrapper.findAll('button').filter(button => button.text() === '继续本批当前工作'); expect(buttons).toHaveLength(2)
await buttons[1]!.trigger('click'); await flushPromises()
expect(wrapper.getComponent({ name: 'WorkBatchContinuation' }).props()).toMatchObject({ batchKey: 'FBA_APPOINTMENT:20', customerId: 'customer-a' })
expect(getAppointmentBatch).toHaveBeenCalledTimes(1); wrapper.unmount()
})
it('keeps current cards readable with incomplete history and never fabricates historical entries', async () => {
const wrapper = render({ historyUnavailableReason: '部分原绑定记录缺少来源证据' }); await flushPromises()
expect(wrapper.get('[role="alert"]').text()).toContain('部分原绑定记录缺少来源证据')
expect(wrapper.findAll('article')).toHaveLength(1); expect(wrapper.text()).toContain('当前关联排车单:DS-A')
expect(wrapper.text()).not.toContain('历史关联排车单:'); expect(wrapper.text()).toContain('70 箱'); wrapper.unmount()
})
it('blocks invalid reference customer identity before reading or opening current work', async () => {
const wrapper = render({ dispatches: [{ dispatchNo: 'DS-A', customerId: 'another-customer', packageCount: 70, appointmentBatches: [reference()] }] }); await flushPromises()
expect(wrapper.get('[role="alert"]').text()).toContain('客户或来源范围不完整')
expect(getAppointmentBatch).not.toHaveBeenCalled(); expect(wrapper.text()).not.toContain('继续本批当前工作'); wrapper.unmount()
})
@@ -0,0 +1,103 @@
<script setup lang="ts">
import { computed, onMounted, onBeforeUnmount, provide, ref, watch } from 'vue'
import { onBeforeRouteLeave } from 'vue-router'
import { useAccessPreviewStore } from '@/core/access/accessPreview'
import { type DispatchBatchReference, type FbaAppointmentDto } from '@/modules/overseas-warehouse'
import { getApiErrorDetails, type ApiErrorDetails } from '@/shared/api/http'
import AppDialog from '@/shared/components/AppDialog.vue'
import LoadErrorState from '@/shared/components/LoadErrorState.vue'
import { getAppointmentBatch, type FbaAppointmentBatchContext } from './batchApi'
import { getReceivingContext, type ReceivingContext } from './receivingApi'
import WorkReceivingPanel from './WorkReceivingPanel.vue'
import AppointmentBatchForm from './AppointmentBatchForm.vue'
import WorkAppointmentForm from './WorkAppointmentForm.vue'
import WorkBatchContinuation from './WorkBatchContinuation.vue'
import type { TripPreviousDispatch } from '@/modules/overseas-master-data'
import type { LeaveGuard } from './useWorkDraft'
const props = defineProps<{ dispatches: Array<{ dispatchNo: string; customerId: string; packageCount: number; appointmentBatches: DispatchBatchReference[] }>; previousDispatches: TripPreviousDispatch[]; historyUnavailableReason: string | null; canWrite: boolean }>()
const emit = defineEmits<{ updated: []; work: [key: string]; external: [path: string] }>()
type Card = { key: string; batchKey: string; batchNo: string | null; customerId: string; current: boolean; dispatchNos: string[]; historyNos: string[]; sources: DispatchBatchReference['sources']; batch: FbaAppointmentBatchContext | null; receiving: ReceivingContext | null; error: ApiErrorDetails | null }
const access = useAccessPreviewStore(), cards = ref<Card[]>([]), loading = ref(false)
const readable = computed(() => ['platform:appointment:list', 'platform:overseas-warehouse:dispatch:list'].every(permission => access.can(permission)))
const selected = ref<{ batchKey: string; customerId: string } | null>(null), mode = ref<'receiving' | 'batch' | 'appointment' | 'continue'>('receiving'), appointmentNo = ref('')
const guards = new Set<LeaveGuard>()
provide('appointment-work-leave-guard', (guard: LeaveGuard) => { guards.add(guard); return () => guards.delete(guard) })
async function canLeave() { for (const guard of guards) if (!await guard()) return false; return true }
defineExpose({ canLeave })
onBeforeRouteLeave(canLeave)
let generation = 0
async function load() {
if (!readable.value) return
const current = ++generation; loading.value = true
const batches = new Map<string, Promise<FbaAppointmentBatchContext>>(), receiving = new Map<string, Promise<ReceivingContext>>()
const references = new Map<string, Card>()
const add = (binding: { dispatchNo: string; customerId: string; appointmentBatches: DispatchBatchReference[] }, historical: boolean) => {
for (const reference of binding.appointmentBatches) {
const key = JSON.stringify([reference.batchKey, reference.customerId])
let card = references.get(key)
if (!card) { card = { key, batchKey: reference.batchKey, batchNo: reference.batchNo, customerId: reference.customerId, current: false, dispatchNos: [], historyNos: [], sources: [], batch: null, receiving: null, error: null }; references.set(key, card) }
if (reference.customerId !== binding.customerId || !reference.batchKey || !reference.sources.length) card.error = { message: '排车引用的客户或来源范围不完整,请核对原排车单。' }
card.current ||= !historical
const numbers = historical ? card.historyNos : card.dispatchNos
if (!numbers.includes(binding.dispatchNo)) numbers.push(binding.dispatchNo)
for (const source of reference.sources) if (!card.sources.some(existing => existing.sourceKey === source.sourceKey && existing.destinationKey === source.destinationKey)) card.sources.push(source)
}
}
props.dispatches.forEach(binding => add(binding, false))
props.previousDispatches.forEach(binding => add(binding, true))
const loaded = await Promise.all([...references.values()].map(async card => {
if (card.error) return card
try {
if (!batches.has(card.batchKey)) batches.set(card.batchKey, getAppointmentBatch(card.batchKey))
if (!receiving.has(card.batchKey)) receiving.set(card.batchKey, getReceivingContext(card.batchKey))
const [batch, scope] = await Promise.all([batches.get(card.batchKey)!, receiving.get(card.batchKey)!])
if (batch.appointment.batchKey !== card.batchKey || scope.batch.batchKey !== card.batchKey) throw new Error('批次范围不匹配')
card.batch = batch; card.receiving = scope
} catch (cause) { card.error = getApiErrorDetails(cause, '本客户预约与去向读取失败') }
return card
}))
if (current === generation) { cards.value = loaded; loading.value = false }
}
function customerName(card: Card) { return card.receiving?.agreements.flatMap(row => row.members).find(member => member.customerId === card.customerId)?.customerName || '—' }
function destinations(card: Card) {
if (!card.batch) return []
const original = new Set(card.batch.originalSourceRefs.filter(item => item.customerId === card.customerId && card.sources.some(source => source.sourceKey === item.sourceKey && source.destinationKey === item.destinationKey)).map(item => JSON.stringify([item.sourceKey, item.destinationKey])))
return [...new Map(card.batch.currentBatches.map(batch => [batch.batchKey, batch])).values()].map(batch => ({ batch, items: batch.items.filter(item => item.customerId === card.customerId && original.has(JSON.stringify([item.sourceKey, item.destinationKey])) && (item.packageCount == null || item.packageCount > 0)) })).filter(row => row.items.length)
}
async function open(batchKey: string, customerId: string, next: 'receiving' | 'batch' | 'continue') { if (await canLeave()) { selected.value = { batchKey, customerId }; mode.value = next } }
async function openAppointment(number: string) { if (await canLeave()) { appointmentNo.value = number; mode.value = 'appointment' } }
async function close(done: () => void) { if (await canLeave()) { done(); selected.value = null } }
function saved(appointment: FbaAppointmentDto) { if (appointment.batchKey && selected.value) { selected.value = { ...selected.value, batchKey: appointment.batchKey }; mode.value = 'continue' }; updated() }
function updated() { emit('updated'); void load() }
watch(() => JSON.stringify([props.dispatches, props.previousDispatches]), () => { void load() })
onMounted(load)
onBeforeUnmount(() => { ++generation })
</script>
<template>
<section aria-label="本车客户预约与后送去向">
<p v-if="!readable">需要预约及排车列表权限才能读取客户预约范围。</p>
<p v-if="loading">正在核对本车客户的预约与当前去向…</p>
<el-button :loading="loading" @click="load">刷新客户预约与去向</el-button>
<p v-if="historyUnavailableReason" role="alert">历史预约引用读取不完整:{{ historyUnavailableReason }}。当前车次仍可查看,请重试读取后再核对历史去向。</p><p v-for="binding in dispatches.filter(row => !row.appointmentBatches.length)" :key="binding.dispatchNo" role="status">{{ binding.dispatchNo }}:本排车单没有预约批次引用,请从原排车单核对业务来源。</p><article v-for="card in cards" :key="card.key" class="trip-customer-card">
<h4>{{ customerName(card) }} · {{ card.batchNo || '批次业务号未提供' }}</h4><p v-if="card.current">当前关联排车单:{{ card.dispatchNos.join('、') }}</p><p v-if="card.historyNos.length">历史关联排车单:{{ card.historyNos.join('、') }} · 仅供追溯,不代表当前装载或可排数量。</p>
<LoadErrorState v-if="card.error" title="本客户范围不可用" :message="card.error.message" @retry="load" />
<template v-if="card.batch && card.receiving">
<p v-for="pending in card.receiving.pendingChanges.filter(row => row.intent.customerId === card.customerId)" :key="pending.changeKey" role="status">待仓库回复:{{ pending.intent.reason }}。原安排保留,请继续处理。</p>
<el-button v-if="card.current" :disabled="loading || !canWrite" @click="open(card.batch.appointment.batchKey!, card.customerId, 'receiving')">调整本客户先送 / 后送</el-button>
<el-button v-if="card.current" :disabled="loading" @click="open(card.batch.appointment.batchKey!, card.customerId, 'batch')">查看批次与完整去向</el-button>
<div v-for="destination in destinations(card)" :key="destination.batch.batchKey"><b>{{ destination.batch.appointmentNo }}</b><p>{{ destination.batch.plannedDate || '日期未定' }}</p><p v-for="item in destination.items" :key="item.id">{{ item.inboundCode || '—' }} · {{ item.packageCount == null ? '箱数待核实' : `${item.packageCount} 箱` }}</p><el-button :disabled="loading" @click="open(destination.batch.batchKey!, card.customerId, 'continue')">继续本批当前工作</el-button></div>
<p v-if="!destinations(card).length">原客户来源范围当前不可匹配,请核对完整批次去向;此处不代表已完成或没有后送需求。</p>
</template>
</article>
<p v-if="readable && !loading && !cards.length">当前没有可读取的预约批次引用。</p>
<AppDialog :model-value="!!selected" title="客户预约与后送安排" width="min(1120px, calc(100vw - 48px))" class="admin-density-dialog admin-density" fullscreenable append-to-body :show-footer="false" :before-close="close" :close-on-click-modal="true" :close-on-press-escape="true" destroy-on-close>
<template v-if="selected">
<WorkReceivingPanel v-if="mode === 'receiving'" :key="`${selected.batchKey}:${selected.customerId}`" :batch-key="selected.batchKey" :initial-customer-id="selected.customerId" :can-write="canWrite" @updated="updated" @appointment="openAppointment" @batch="key => open(key, selected!.customerId, 'batch')" @external="path => emit('external', path)" />
<AppointmentBatchForm v-else-if="mode === 'batch'" :key="selected.batchKey" :batch-key="selected.batchKey" @updated="updated" @appointment="openAppointment" />
<WorkAppointmentForm v-else-if="mode === 'appointment'" :key="appointmentNo" :appointment-no="appointmentNo" :cancel="false" :can-write="canWrite" @saved="saved" @batch="key => open(key, selected!.customerId, 'batch')" @receiving="key => open(key, selected!.customerId, 'receiving')" />
<WorkBatchContinuation v-else :key="`${selected.batchKey}:${selected.customerId}`" :batch-key="selected.batchKey" :customer-id="selected.customerId" @open="key => emit('work', key)" />
</template>
</AppDialog>
</section>
</template>
<style scoped>.trip-customer-card { padding-block: var(--admin-space-4); border-bottom: 1px solid var(--cc-border); }</style>
@@ -3,19 +3,42 @@ import { beforeEach, expect, it, vi } from 'vitest'
import WorkAppointmentForm from './WorkAppointmentForm.vue'
import { getFbaAppointment, updateFbaAppointment, type FbaAppointmentDto } from '@/modules/overseas-warehouse'
import { deleteAppointment } from './api'
import { ApiResponseError } from '@/shared/api/http'
vi.mock('@/core/access/accessPreview', () => ({ useAccessPreviewStore: () => ({ can: () => true }) }))
vi.mock('element-plus', () => ({ ElMessage: { warning: vi.fn(), success: vi.fn() }, ElMessageBox: { confirm: vi.fn() } }))
vi.mock('@/modules/overseas-warehouse', async original => ({ ...await original<typeof import('@/modules/overseas-warehouse')>(), getFbaAppointment: vi.fn(), updateFbaAppointment: vi.fn() }))
vi.mock('./api', async original => ({ ...await original<typeof import('./api')>(), deleteAppointment: vi.fn() }))
const detail: FbaAppointmentDto = { id: '1', appointmentNo: 'AP-001', batchKey: 'FBA_APPOINTMENT:1', version: 3, originWarehouseId: 'warehouse-1', fbaWarehouseCode: 'ONT8', selectedCount: 1, items: [], appointmentStatus: 'SUCCESS', confirmationNo: 'EXT-001', appointmentAt: '2026-10-15T23:30:00', appointmentEndAt: '2026-10-16T01:00:00', appointmentStartUtc: '2026-10-16T06:30:00Z', appointmentEndUtc: '2026-10-16T08:00:00Z', timezone: 'America/Los_Angeles' }
function render(cancel = false) { return mount(WorkAppointmentForm, { props: { appointmentNo: 'AP-001', cancel, canWrite: true }, global: { stubs: { ElButton: { props: ['disabled'], template: '<button :disabled="disabled"><slot /></button>' }, FbaAppointmentFields: { name: 'FbaAppointmentFields', props: ['model', 'disabled'], template: '<div />' }, LoadErrorState: true, ApiErrorMeta: true } } }) }
function render(cancel = false) { return mount(WorkAppointmentForm, { props: { appointmentNo: 'AP-001', cancel, canWrite: true }, global: { stubs: { ElButton: { props: ['disabled'], template: '<button :disabled="disabled"><slot /></button>' }, FbaAppointmentFields: { name: 'FbaAppointmentFields', props: ['model', 'disabled'], template: '<div />' }, LoadErrorState: { props: ['message'], template: '<section role="alert">{{ message }}<button @click="$emit(\'retry\')">重试读取</button></section>' }, ApiErrorMeta: true } } }) }
beforeEach(() => { vi.clearAllMocks(); vi.mocked(getFbaAppointment).mockResolvedValue(detail); vi.mocked(updateFbaAppointment).mockResolvedValue(detail) })
it('initializes confirmed facts after an initial read failure instead of showing an empty editable plan', async () => {
vi.mocked(getFbaAppointment).mockRejectedValueOnce(new Error('来源暂不可用'))
const wrapper = render(); await flushPromises()
expect(wrapper.findComponent({ name: 'FbaAppointmentFields' }).exists()).toBe(false)
await wrapper.get('[role="alert"] button').trigger('click'); await flushPromises()
const model = wrapper.getComponent({ name: 'FbaAppointmentFields' }).props('model')
expect(model.confirmationNo).toBe('EXT-001'); expect(model.appointmentStatus).toBe('SUCCESS')
expect(model.appointmentAt).toBe('2026-10-15T23:30:00'); expect(model.startOffset).toBe('-07:00')
expect(wrapper.findAll('button').find(button => button.text() === '保存预约安排')!.attributes('disabled')).toBeDefined()
expect(updateFbaAppointment).not.toHaveBeenCalled(); wrapper.unmount()
})
it('preserves both dates of an existing cross-day appointment and its explicit offsets in the original business command', async () => {
const wrapper = render(); await flushPromises()
wrapper.getComponent({ name: 'FbaAppointmentFields' }).props('model').appointmentRemark = '已核对仓库回复'
await flushPromises()
await wrapper.findAll('button').find(button => button.text() === '保存预约安排')!.trigger('click'); await flushPromises()
expect(updateFbaAppointment).toHaveBeenCalledWith('AP-001', expect.objectContaining({ version: 3, details: expect.objectContaining({ appointmentAt: '2026-10-15T23:30:00', appointmentEndAt: '2026-10-16T01:00:00', startOffset: '-07:00', endOffset: '-07:00' }) }))
wrapper.unmount()
})
it('does not resubmit unchanged appointment facts, including whitespace-only edits', async () => {
const wrapper = render(); await flushPromises()
const save = wrapper.findAll('button').find(button => button.text() === '保存预约安排')!
expect(save.attributes('disabled')).toBeDefined()
wrapper.getComponent({ name: 'FbaAppointmentFields' }).props('model').confirmationNo = ' EXT-001 '
await flushPromises(); await save.trigger('click')
expect(updateFbaAppointment).not.toHaveBeenCalled()
expect(wrapper.text()).toContain('无需重复保存'); wrapper.unmount()
})
it('does not edit or cancel replaced snapshots and offers the stable batch context for replacement history', async () => {
vi.mocked(getFbaAppointment).mockResolvedValue({ ...detail, replacementAppointmentNos: ['AP-NEW'], replacementBatchKeys: ['FBA_APPOINTMENT:2'], repartitionReason: '分批送仓' })
const wrapper = render(true); await flushPromises()
@@ -25,3 +48,44 @@ it('does not edit or cancel replaced snapshots and offers the stable batch conte
await wrapper.findAll('button').find(button => button.text() === '查看替代批次')!.trigger('click')
expect(wrapper.emitted('batch')).toEqual([['FBA_APPOINTMENT:1']]); wrapper.unmount()
})
const cancelled: FbaAppointmentDto = { ...detail, version: 4, appointmentStatus: 'CANCELLED', confirmationNo: null, plannedDate: null, plannedAt: null, plannedEndAt: null, appointmentAt: null, appointmentEndAt: null, appointmentStartUtc: null, appointmentEndUtc: null }
it('rebooks the cancelled original batch as undated pending without creating or reallocating cargo', async () => {
vi.mocked(getFbaAppointment).mockResolvedValueOnce(cancelled).mockResolvedValue({ ...cancelled, version: 5, appointmentStatus: 'PENDING' })
const wrapper = render(); await flushPromises()
expect(wrapper.text()).toContain('货物分配仍保留')
const model = wrapper.getComponent({ name: 'FbaAppointmentFields' }).props('model')
expect(model.appointmentStatus).toBe('PENDING'); expect(model.confirmationNo).toBe(''); expect(model.appointmentAt).toBe('')
await wrapper.findAll('button').find(button => button.text() === '保存本批重新预约')!.trigger('click'); await flushPromises()
expect(updateFbaAppointment).toHaveBeenCalledWith('AP-001', expect.objectContaining({ version: 4, idempotencyKey: expect.any(String), details: expect.objectContaining({ appointmentStatus: 'PENDING', plannedDate: null, confirmationNo: null, appointmentAt: null, appointmentEndAt: null }) }))
const payload = vi.mocked(updateFbaAppointment).mock.calls[0]![1]
expect(payload).not.toHaveProperty('items'); expect(payload).not.toHaveProperty('sources')
expect(deleteAppointment).not.toHaveBeenCalled(); expect(wrapper.emitted('saved')).toHaveLength(1)
expect(wrapper.findAll('button').find(button => button.text() === '保存预约安排')!.attributes('disabled')).toBeDefined()
wrapper.unmount()
})
it('retries an uncertain rebooking using the identical command, and preserves input on an explicit conflict', async () => {
vi.mocked(getFbaAppointment).mockResolvedValueOnce(cancelled).mockResolvedValue({ ...cancelled, version: 6 })
vi.mocked(updateFbaAppointment).mockRejectedValueOnce(new Error('unknown outcome')).mockRejectedValueOnce(new ApiResponseError('外部约号已占用', 'A0409', 409))
const wrapper = render(); await flushPromises()
const fields = wrapper.getComponent({ name: 'FbaAppointmentFields' })
Object.assign(fields.props('model'), { appointmentStatus: 'SUCCESS', confirmationNo: 'NEW-EXT', appointmentAt: '2026-10-20T10:00:00' })
await wrapper.findAll('button').find(button => button.text() === '保存本批重新预约')!.trigger('click'); await flushPromises()
const first = vi.mocked(updateFbaAppointment).mock.calls[0]![1]
expect(fields.props('disabled')).toBe(true)
await wrapper.findAll('button').find(button => button.text() === '重试本次保存')!.trigger('click'); await flushPromises()
expect(updateFbaAppointment).toHaveBeenNthCalledWith(2, 'AP-001', first)
expect(fields.props('model').confirmationNo).toBe('NEW-EXT'); expect(fields.props('disabled')).toBe(false)
expect(wrapper.emitted('saved')).toBeUndefined()
await wrapper.findAll('button').find(button => button.text() === '保存本批重新预约')!.trigger('click'); await flushPromises()
const next = vi.mocked(updateFbaAppointment).mock.calls[2]![1]
expect(next.version).toBe(6); expect(next.idempotencyKey).not.toBe(first.idempotencyKey)
wrapper.unmount()
})
it('cannot cancel twice or rebook with read-only access', async () => {
vi.mocked(getFbaAppointment).mockResolvedValue(cancelled)
const wrapper = render(true); await flushPromises()
expect(wrapper.findAll('button').find(button => button.text() === '确认取消并继续跟进')!.attributes('disabled')).toBeDefined()
await wrapper.setProps({ cancel: false, canWrite: false }); await flushPromises()
expect(wrapper.findAll('button').find(button => button.text() === '保存本批重新预约')!.attributes('disabled')).toBeDefined()
expect(updateFbaAppointment).not.toHaveBeenCalled(); expect(deleteAppointment).not.toHaveBeenCalled(); wrapper.unmount()
})
@@ -9,23 +9,33 @@ import { getApiErrorDetails, type ApiErrorDetails } from '@/shared/api/http'
import { deleteAppointment } from './api'
import { rejectedCommand, useWorkDraft } from './useWorkDraft'
const props = defineProps<{ appointmentNo: string; cancel: boolean; canWrite: boolean }>()
const emit = defineEmits<{ saved: []; batch: [key: string] }>()
const emit = defineEmits<{ saved: [appointment: FbaAppointmentDto]; batch: [key: string]; receiving: [key: string] }>()
const access = useAccessPreviewStore(), detail = ref<FbaAppointmentDto | null>(null)
const form = reactive(createAppointmentForm()), reason = ref(''), baseline = ref(JSON.stringify(form))
const form = reactive(createAppointmentForm()), reason = ref(''), baseline = ref(JSON.stringify(appointmentPayload(form)))
const loading = ref(false), saving = ref(false), error = ref<ApiErrorDetails | null>(null), saveError = ref<ApiErrorDetails | null>(null)
let initialized = false
type SaveRequest = { kind: 'update'; payload: { details: ReturnType<typeof appointmentPayload>; version: number; idempotencyKey: string } } | { kind: 'cancel'; version: number; reason: string }
const pending = ref<SaveRequest | null>(null)
useWorkDraft(computed(() => JSON.stringify(form) !== baseline.value || !!reason.value), computed(() => saving.value || !!pending.value))
const changed = computed(() => JSON.stringify(appointmentPayload(form)) !== baseline.value)
useWorkDraft(computed(() => changed.value || !!reason.value), computed(() => saving.value || !!pending.value))
const replaced = computed(() => !!detail.value?.replacementAppointmentNos?.length || !!detail.value?.replacementBatchKeys?.length)
const writable = computed(() => props.canWrite && !replaced.value && detail.value?.appointmentStatus !== 'CANCELLED' && access.can(props.cancel ? 'platform:appointment:delete' : 'platform:overseas-warehouse:inbound-order:fba-appointment'))
const rebooking = computed(() => !props.cancel && detail.value?.appointmentStatus === 'CANCELLED' && !replaced.value)
const writable = computed(() => props.canWrite && !replaced.value && (!props.cancel || detail.value?.appointmentStatus !== 'CANCELLED') && access.can(props.cancel ? 'platform:appointment:delete' : 'platform:overseas-warehouse:inbound-order:fba-appointment'))
async function load(preserve = false) {
loading.value = true; error.value = null
try { detail.value = await getFbaAppointment(props.appointmentNo); if (!preserve) { Object.assign(form, createAppointmentForm(detail.value)); baseline.value = JSON.stringify(form) } }
try {
detail.value = await getFbaAppointment(props.appointmentNo)
if (!preserve || !initialized) {
Object.assign(form, createAppointmentForm(detail.value)); if (rebooking.value) form.appointmentStatus = 'PENDING'
baseline.value = JSON.stringify(appointmentPayload(form)); initialized = true
}
}
catch (cause) { error.value = getApiErrorDetails(cause, '预约详情读取失败') }
finally { loading.value = false }
}
async function save() {
if (!detail.value || !writable.value || loading.value || error.value || saving.value) return
if (!props.cancel && !pending.value && !changed.value && !rebooking.value) return
if (!pending.value) {
if (props.cancel) {
if (!reason.value.trim()) { ElMessage.warning('请填写取消原因'); return }
@@ -38,9 +48,9 @@ async function save() {
saving.value = true; saveError.value = null
try {
if (pending.value.kind === 'cancel') await deleteAppointment(props.appointmentNo, pending.value.version, pending.value.reason)
else await updateFbaAppointment(props.appointmentNo, pending.value.payload)
pending.value = null; reason.value = ''; baseline.value = JSON.stringify(form)
ElMessage.success(props.cancel ? '原预约已取消,工作需求继续跟进' : '预约安排已保存'); emit('saved'); await load()
else detail.value = await updateFbaAppointment(props.appointmentNo, pending.value.payload)
pending.value = null; reason.value = ''; baseline.value = JSON.stringify(appointmentPayload(form))
ElMessage.success(props.cancel ? '原预约已取消,工作需求继续跟进' : '预约安排已保存'); emit('saved', detail.value); await load()
} catch (cause) { saveError.value = getApiErrorDetails(cause, '保存结果待确认,请重试本次保存'); if (rejectedCommand(cause)) { pending.value = null; await load(true) } }
finally { saving.value = false }
}
@@ -48,18 +58,21 @@ onMounted(() => load())
</script>
<template>
<section class="work-form" aria-label="预约安排">
<h3>{{ cancel ? '取消本次预约' : '登记预约安排' }}</h3>
<h3>{{ cancel ? '取消本次预约' : rebooking ? '沿原批次重新预约' : '登记预约安排' }}</h3>
<LoadErrorState v-if="error" title="预约详情读取失败" :message="error.message" :loading="loading" @retry="load(true)"><template #details><ApiErrorMeta :details="error" /></template></LoadErrorState>
<p v-if="loading">正在读取原预约…</p>
<template v-if="detail">
<p>{{ detail.fbaWarehouseCode }} · {{ detail.appointmentNo }}</p>
<p v-if="rebooking">原预约已取消,货物分配仍保留。重新预约将更新本批安排,保留取消历史;请重新填写目标日期或仓库确认,日期未定也可先保存待预约。</p>
<p v-if="replaced">原预约已被替代,保留历史只读。当前批次:{{ detail.replacementAppointmentNos?.join('、') || '—' }}。{{ detail.repartitionReason }}</p>
<el-button v-if="detail.batchKey && !saving && !pending" @click="emit('batch', detail.batchKey)">{{ replaced ? '查看替代批次' : '分批 / 合并与货物来源' }}</el-button>
<el-button v-if="detail.batchKey && !replaced && !saving && !pending" :disabled="loading || !!error" @click="emit('receiving', detail.batchKey)">客户调整 / 共同预约范围</el-button>
<template v-if="cancel"><p>取消原预约并保留历史;工作需求与后续跟进仍保留。已有运输安排须满足原业务取消条件。</p><label>取消原因<textarea v-model="reason" :disabled="!writable || saving || !!pending" maxlength="1000" /></label></template>
<FbaAppointmentFields v-else :model="form" :appointment-no="detail.appointmentNo" :timezone="detail.timezone" :disabled="!writable || loading || !!error || saving || !!pending" />
<p v-if="!writable">当前预约仅可查看。</p>
<LoadErrorState v-if="saveError" title="预约未保存" :message="saveError.message" :show-retry="false"><template #details><ApiErrorMeta :details="saveError" /></template></LoadErrorState>
<el-button :type="cancel ? 'danger' : 'primary'" :disabled="!writable || loading || !!error" :loading="saving" @click="save">{{ pending ? '重试本次保存' : cancel ? '确认取消并继续跟进' : '保存预约安排' }}</el-button>
<p v-if="!cancel && !rebooking && writable && !changed && !pending">预约内容未修改,无需重复保存。</p>
<el-button :type="cancel ? 'danger' : 'primary'" :disabled="!writable || loading || !!error || (!cancel && !rebooking && !pending && !changed)" :loading="saving" @click="save">{{ pending ? '重试本次保存' : cancel ? '确认取消并继续跟进' : rebooking ? '保存本批重新预约' : '保存预约安排' }}</el-button>
</template>
</section>
</template>
@@ -0,0 +1,23 @@
import { flushPromises, mount } from '@vue/test-utils'
import { beforeEach, expect, it, vi } from 'vitest'
import WorkBatchContinuation from './WorkBatchContinuation.vue'
import { resolveBatchWork } from './workApi'
import { workDetail, workItem } from './work.test-support'
vi.mock('./workApi', async original => ({ ...await original<typeof import('./workApi')>(), resolveBatchWork: vi.fn() }))
function render() { return mount(WorkBatchContinuation, { props: { batchKey: 'FBA_APPOINTMENT:40', labels: [{ customerId: 'customer-a', label: 'IN-A' }] }, global: { stubs: { ElButton: { props: ['disabled'], template: '<button :disabled="disabled"><slot /></button>' }, LoadErrorState: { props: ['message'], template: '<div role="alert">{{ message }}<button @click="$emit(\'retry\')">重试读取</button></div>' }, ApiErrorMeta: true } } }) }
beforeEach(() => vi.clearAllMocks())
it('requires a customer selection for multiple real work candidates and uses the selected resolver result', async () => {
vi.mocked(resolveBatchWork).mockResolvedValueOnce({ batchKey: 'FBA_APPOINTMENT:40', customerId: null, detail: null, candidates: [{ customerId: 'customer-a', workItemKey: 'real-work-a', batchNo: 'AP-40' }, { customerId: 'customer-b', workItemKey: 'real-work-b', batchNo: 'AP-40' }] }).mockResolvedValue({ batchKey: 'FBA_APPOINTMENT:40', customerId: 'customer-a', detail: workDetail({ item: workItem({ workItemKey: 'current-work-a' }) }), candidates: [] })
const wrapper = render(); await flushPromises()
expect(wrapper.emitted('open')).toBeUndefined(); expect(wrapper.text()).toContain('IN-A'); expect(wrapper.text()).not.toContain('customer-a')
await wrapper.findAll('button')[0]!.trigger('click'); await flushPromises()
expect(resolveBatchWork).toHaveBeenLastCalledWith('FBA_APPOINTMENT:40', 'customer-a', expect.any(AbortSignal))
expect(wrapper.emitted('open')).toEqual([['current-work-a']]); wrapper.unmount()
})
it('keeps saved results on resolution failure and only retries the read', async () => {
vi.mocked(resolveBatchWork).mockRejectedValueOnce(new Error('同步未完成')).mockResolvedValue({ batchKey: 'FBA_APPOINTMENT:40', customerId: null, detail: workDetail({ item: workItem({ workItemKey: 'actual-key' }) }), candidates: [] })
const wrapper = render(); await flushPromises()
expect(wrapper.text()).toContain('无需重复提交'); expect(wrapper.emitted('open')).toBeUndefined()
await wrapper.get('[role="alert"] button').trigger('click'); await flushPromises()
expect(resolveBatchWork).toHaveBeenCalledTimes(2); expect(wrapper.emitted('open')).toEqual([['actual-key']]); wrapper.unmount()
})
@@ -0,0 +1,26 @@
<script setup lang="ts">
import { onBeforeUnmount, onMounted, ref } from 'vue'
import { getApiErrorDetails, type ApiErrorDetails } from '@/shared/api/http'
import LoadErrorState from '@/shared/components/LoadErrorState.vue'
import ApiErrorMeta from '@/shared/components/ApiErrorMeta.vue'
import { resolveBatchWork, type BatchWorkResolution } from './workApi'
const props = defineProps<{ batchKey: string; customerId?: string; labels?: Array<{ customerId: string; label: string }> }>()
const emit = defineEmits<{ open: [key: string] }>()
const resolution = ref<BatchWorkResolution | null>(null), error = ref<ApiErrorDetails | null>(null), loading = ref(false)
const controller = new AbortController()
async function load(customerId = props.customerId) {
loading.value = true; error.value = null
try { const value = await resolveBatchWork(props.batchKey, customerId, controller.signal); if (controller.signal.aborted) return; resolution.value = value; if (value.detail) emit('open', value.detail.item.workItemKey) }
catch (cause) { if (!controller.signal.aborted) error.value = getApiErrorDetails(cause, '当前批次下一步读取失败') }
finally { loading.value = false }
}
onMounted(() => load())
onBeforeUnmount(() => controller.abort())
</script>
<template>
<section aria-label="当前批次续办">
<p>正在定位当前批次的工作事项;已保存的内容无需重复提交。</p>
<LoadErrorState v-if="error" title="当前批次下一步读取失败" :message="error.message" :loading="loading" @retry="load()"><template #details><ApiErrorMeta :details="error" /></template></LoadErrorState>
<template v-if="resolution && !resolution.detail && !error"><p>本批有多个客户,请选择本次继续办理的货物。</p><el-button v-for="(candidate, index) in resolution.candidates" :key="candidate.workItemKey" :disabled="loading" @click="load(candidate.customerId)">{{ candidate.batchNo || '—' }} · {{ labels?.find(row => row.customerId === candidate.customerId)?.label || `客户范围 ${index + 1}` }}</el-button><p v-if="!resolution.candidates.length">当前没有可定位的送仓事项,请核对服务端同步结果。</p></template>
</section>
</template>
@@ -5,6 +5,17 @@ import { workCalendar } from './work.test-support'
import { workTypes } from './workApi'
function render() { return mount(WorkCalendarPanel, { props: { anchor: '2026-10-15', mode: 'month', flow: '', types: [...workTypes], calendar: workCalendar, loading: false, failed: false, reference: false, arrivals: [], referenceReady: false } }) }
afterEach(() => vi.useRealTimers())
it('keeps a busy day at five type summaries and consumes authoritative transport counts unchanged', async () => {
const wrapper = render()
const counts = { PICKUP: 300, WAREHOUSE_RECEIPT: 300, DELIVERY: 2, TRANSPORT: 1, EMPTY_RETURN: 300 }
await wrapper.setProps({ calendar: { ...workCalendar, days: [{ ...workCalendar.days[0]!, total: 903, typeCounts: counts }] } })
const day = wrapper.get('[data-date="2026-10-15"]')
expect(day.findAll('.type-counts button')).toHaveLength(5)
expect(day.get('[data-type="TRANSPORT"]').text()).toContain('1')
expect(day.get('[data-type="DELIVERY"]').text()).toContain('2')
await day.get('[data-type="TRANSPORT"]').trigger('click')
expect(wrapper.emitted('day')).toEqual([['2026-10-15', 'TRANSPORT']]); wrapper.unmount()
})
it('offers all four flows directly and emits the original filter values with an exclusive selection', async () => {
const wrapper = render()
const buttons = wrapper.findAll('.flow-controls button')
@@ -25,7 +25,7 @@ function arrivalCount(date: string) { return props.arrivals.filter(row => row.ar
<div class="work-layers"><span class="muted">显示类型</span><label v-for="type in workTypes" :key="type" :data-type="type"><input type="checkbox" :checked="types.includes(type)" @change="toggle(type, ($event.target as HTMLInputElement).checked)">{{ typeLabels[type] }}</label><label><input type="checkbox" :checked="reference" @change="emit('reference', ($event.target as HTMLInputElement).checked)">到港参考</label></div>
<div class="calendar-counts" aria-live="polite">
<span v-if="loading">正在读取工作统计…</span><span v-else-if="failed">工作统计加载失败</span><span v-else-if="!types.length">未勾选工作类型,全局待办仍可查看</span>
<template v-else-if="calendar"><strong>当前显示区间 {{ calendar.from }} ~ {{ calendar.to }} · {{ calendar.total }} 项工作</strong><span>待安排 {{ calendar.counts.pending }}</span><span>已落实 {{ calendar.counts.confirmed }}</span><span>无需预约 {{ calendar.counts.noBookingRequired }}</span><span>需复核 {{ calendar.counts.review }}</span><span>已完成 {{ calendar.counts.completed }}</span></template>
<template v-else-if="calendar"><strong>当前显示区间 {{ calendar.from }} ~ {{ calendar.to }} · {{ calendar.total }} 项工作</strong><span :class="{ 'is-zero': calendar.counts.pending === 0 }">待安排 {{ calendar.counts.pending }}</span><span :class="{ 'is-zero': calendar.counts.confirmed === 0 }">已落实 {{ calendar.counts.confirmed }}</span><span :class="{ 'is-zero': calendar.counts.noBookingRequired === 0 }">无需预约 {{ calendar.counts.noBookingRequired }}</span><span :class="{ 'is-zero': calendar.counts.review === 0 }">需复核 {{ calendar.counts.review }}</span><span :class="{ 'is-zero': calendar.counts.completed === 0 }">已完成 {{ calendar.counts.completed }}</span></template>
</div>
<div class="weekdays"><span v-for="day in ['一', '二', '三', '四', '五', '六', '日']" :key="day">周{{ day }}</span></div>
<div class="calendar-days">
@@ -48,25 +48,29 @@ function arrivalCount(date: string) { return props.arrivals.filter(row => row.ar
.work-layers, .calendar-counts { padding: var(--admin-space-2) var(--admin-space-5); border-top: 1px solid var(--cc-border); }
.work-layers label { display: inline-flex; align-items: center; gap: var(--admin-space-2); cursor: pointer; }
.calendar-counts { min-height: 24px; font-size: var(--admin-font-caption); }
.calendar-counts .is-zero { color: var(--el-text-color-secondary); }
.weekdays, .calendar-days { display: grid; grid-template-columns: repeat(7, minmax(0, 1fr)); }
.weekdays { text-align: center; padding-block: var(--admin-space-3); background: var(--el-fill-color-light); }
.work-day { min-height: 112px; box-sizing: border-box; border-top: 1px solid var(--cc-border); border-right: 1px solid var(--cc-border); padding: var(--admin-space-1); }
.week-view .work-day { min-height: 240px; }
.weekdays span:nth-last-child(-n+2) { color: var(--el-text-color-secondary); }
.work-day { height: 146px; min-height: 146px; max-height: 146px; box-sizing: border-box; border-top: 1px solid var(--cc-border); border-right: 1px solid var(--cc-border); padding: var(--admin-space-1); }
.week-view .work-day { height: 270px; min-height: 270px; max-height: 270px; }
.work-day:nth-child(7n) { border-right: 0; }
.outside { background: var(--el-fill-color-lighter); }
.work-calendar .day-heading { display: flex; align-items: center; gap: var(--admin-space-1); width: 100%; border: 0; padding: 0; min-height: 24px; background: transparent; margin-bottom: var(--admin-space-1); }
.date-number { display: inline-flex; align-items: center; justify-content: center; min-width: 24px; height: 24px; border-radius: 50%; }
.date-number { display: inline-flex; align-items: center; justify-content: center; min-width: 24px; height: 24px; border-radius: 50%; font-weight: 600; font-variant-numeric: tabular-nums; }
.is-today .date-number { color: var(--el-color-white); background: var(--el-color-primary); font-weight: 600; }
.today-mark { color: var(--el-color-primary); font-size: var(--admin-font-caption); }
.day-total { margin-left: auto; color: var(--el-text-color-secondary); font-size: var(--admin-font-caption); }
.work-day.is-selected { box-shadow: inset 0 0 0 2px var(--el-color-primary); background: var(--el-color-primary-light-9); }
.outside .day-heading { color: var(--el-text-color-secondary); }
.type-counts { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); grid-auto-rows: minmax(24px, auto); gap: 2px; }
.work-calendar .type-counts button { display: flex; align-items: center; justify-content: space-between; gap: 2px; border: 1px solid currentColor; padding: 0 3px; font-size: var(--admin-font-caption); background: transparent; min-width: 0; min-height: 24px; white-space: nowrap; }
.type-counts button[aria-pressed=true] { background: var(--admin-surface); box-shadow: inset 0 0 0 1px currentColor; }
.type-counts { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); grid-auto-rows: minmax(24px, auto); gap: var(--admin-space-1); }
.work-calendar .type-counts button { display: flex; align-items: center; justify-content: space-between; gap: 2px; border: 1px solid color-mix(in srgb, currentColor 20%, transparent); padding: 0 var(--admin-space-1); font-size: var(--admin-font-caption); background: color-mix(in srgb, currentColor 7%, var(--admin-surface)); min-width: 0; min-height: 24px; white-space: nowrap; }
.work-calendar .type-counts button:hover:not(:disabled) { border-color: currentColor; background: color-mix(in srgb, currentColor 12%, var(--admin-surface)); }
.work-calendar .type-counts button[aria-pressed=true] { border-color: currentColor; background: color-mix(in srgb, currentColor 14%, var(--admin-surface)); box-shadow: inset 0 0 0 1px currentColor; }
.type-counts b { font-variant-numeric: tabular-nums; }
[data-type=PICKUP] { color: var(--el-color-primary); } [data-type=WAREHOUSE_RECEIPT] { color: #8356ad; } [data-type=DELIVERY] { color: #27815c; } [data-type=TRANSPORT] { color: #b26a12; } [data-type=EMPTY_RETURN] { color: #a64f69; }
.work-calendar .arrival-reference { border: 0; background: transparent; padding: 0; min-height: 24px; font-size: var(--admin-font-caption); color: var(--el-text-color-secondary); }
.work-calendar .arrival-reference { display: block; border: 0; background: transparent; padding: 0 var(--admin-space-1); margin-top: var(--admin-space-1); min-height: 24px; font-size: var(--admin-font-caption); color: var(--el-text-color-secondary); }
.work-calendar .arrival-reference:hover { color: var(--el-text-color-regular); background: var(--el-fill-color-light); }
footer { padding: var(--admin-space-3) var(--admin-space-5); }
button { font: inherit; cursor: pointer; border-radius: var(--admin-radius); min-height: var(--admin-control-height); color: inherit; border: 1px solid var(--cc-border); background: var(--admin-surface); padding: 0 var(--admin-space-3); }
.view-switch { display: inline-flex; }
@@ -1,24 +1,60 @@
import { flushPromises, mount } from '@vue/test-utils'
import { beforeEach, expect, it, vi } from 'vitest'
import WorkDetailPanel from './WorkDetailPanel.vue'
import { getWorkDetail, type WorkAction, type WorkDetail } from './workApi'
import { getWorkDetail, resolveBatchWork, type WorkAction, type WorkDetail } from './workApi'
import { batchContext } from './batch.test-support'
import { followAction, workDetail, workItem } from './work.test-support'
vi.mock('./workApi', async original => ({ ...await original<typeof import('./workApi')>(), getWorkDetail: vi.fn() }))
vi.mock('./workApi', async original => ({ ...await original<typeof import('./workApi')>(), getWorkDetail: vi.fn(), resolveBatchWork: vi.fn() }))
function render(detail: WorkDetail, initialAction?: WorkAction) {
vi.mocked(getWorkDetail).mockResolvedValue(detail)
return mount(WorkDetailPanel, { props: { itemKey: detail.item.workItemKey, initialAction, canLeave: async () => true }, global: { stubs: {
ElButton: { template: '<button><slot /></button>' },
ElButton: { props: ['disabled'], template: '<button :disabled="disabled"><slot /></button>' },
CargoVerificationForm: { name: 'CargoVerificationForm', props: ['source'], template: '<div data-cargo />' },
WorkCommandForm: { name: 'WorkCommandForm', props: ['detail', 'action'], template: '<div data-command />' },
WorkAppointmentForm: { name: 'WorkAppointmentForm', props: ['appointmentNo', 'canWrite'], template: '<div data-appointment />' },
WorkReceivingPanel: { name: 'WorkReceivingPanel', props: ['batchKey', 'canWrite'], template: '<div data-receiving-scope />' },
WorkCreateAppointmentForm: { name: 'WorkCreateAppointmentForm', props: ['sources', 'canWrite'], template: '<div data-create />' },
WorkDispatchForm: { name: 'WorkDispatchForm', props: ['batchKeys', 'canWrite'], template: '<div data-dispatch />' },
WorkExistingDispatchForm: { name: 'WorkExistingDispatchForm', props: ['dispatches', 'canWrite'], template: '<div data-existing-dispatch />' },
WorkReceiptPlans: { name: 'WorkReceiptPlans', props: ['containerBookingId'], template: '<div data-receiving />' },
LoadErrorState: { props: ['message'], template: '<p>{{ message }}</p>' }, ApiErrorMeta: true,
LoadErrorState: { props: ['message'], template: '<section role="alert">{{ message }}<button @click="$emit(\'retry\')">重试读取</button></section>' }, ApiErrorMeta: true,
} } })
}
beforeEach(() => vi.clearAllMocks())
it('stays on the saved item and offers only the newly fetched primary next step', async () => {
const wrapper = render(workDetail(), followAction); await flushPromises()
const transport: WorkAction = { code: 'ARRANGE_TRANSPORT', label: '继续安排本批车辆', targetWorkItemKey: 'transport-current', target: { kind: 'FLEET_TRIP', tripId: null, batchKeys: ['FBA_APPOINTMENT:1'] } }
vi.mocked(getWorkDetail).mockResolvedValue(workDetail({ item: workItem({ nextAction: transport, allowedActions: [transport, followAction] }) }))
wrapper.getComponent({ name: 'WorkCommandForm' }).vm.$emit('saved', { item: workItem(), affectedWorkItemKeys: [] }, 'SAVE_FOLLOWUP'); await flushPromises()
expect(wrapper.find('[data-command]').exists()).toBe(false)
expect(wrapper.text()).toContain('本次保存已完成')
expect(wrapper.get('.primary-next-action').text()).toBe('继续安排本批车辆')
expect(wrapper.findAll('.more-actions button').map(button => button.text())).toEqual(['记录回复'])
await wrapper.get('.primary-next-action').trigger('click'); await flushPromises()
expect(wrapper.emitted('open')).toEqual([['transport-current', transport]])
wrapper.unmount()
})
it('does not repeat a saved command or enable stale actions when the next-step read fails', async () => {
const wrapper = render(workDetail(), followAction); await flushPromises()
vi.mocked(getWorkDetail).mockRejectedValueOnce(new Error('下一步服务暂不可用'))
wrapper.getComponent({ name: 'WorkCommandForm' }).vm.$emit('saved', { item: workItem(), affectedWorkItemKeys: [] }, 'SAVE_FOLLOWUP'); await flushPromises()
expect(wrapper.text()).toContain('无需重复提交已保存内容')
expect(wrapper.get('.primary-next-action').attributes('disabled')).toBeDefined()
await wrapper.get('[role="alert"] button').trigger('click'); await flushPromises()
expect(wrapper.get('.primary-next-action').attributes('disabled')).toBeUndefined()
expect(wrapper.emitted('saved')).toHaveLength(1)
wrapper.unmount()
})
it('shows an undated job separately from its follow-up date and flags missing follow-up ownership', async () => {
const wrapper = render(workDetail()); await flushPromises()
expect(wrapper.get('.followup-summary').text()).toContain('2026-10-15')
expect(wrapper.get('.followup-summary').text()).toContain('作业日期未定,跟进日不作为作业日期')
wrapper.unmount()
const missing = render(workDetail({ item: workItem({ owner: null, followupDate: null }) })); await flushPromises()
expect(missing.text()).toContain('负责人待分派')
expect(missing.text()).toContain('请补充下一次跟进安排')
missing.unmount()
})
it('never sends customer-warehouse dispatch batches to the FBA candidate endpoint', async () => {
const action: WorkAction = { code: 'ARRANGE_TRANSPORT', label: '安排运输', targetWorkItemKey: null, target: { kind: 'FLEET_TRIP', tripId: null, batchKeys: ['DISPATCH:9007199254740999'] } }
const wrapper = render(workDetail({ item: workItem({ allowedActions: [action], nextAction: action }) }), action); await flushPromises()
@@ -81,6 +117,41 @@ it('uses the matched appointment business number and never passes the internal a
expect(missing.findComponent({ name: 'WorkAppointmentForm' }).exists()).toBe(false)
expect(missing.text()).toContain('尚未关联可操作的预约记录'); missing.unmount()
})
it('opens the receiving scope for the exact batch without changing the current work identity or losing result context', async () => {
const action: WorkAction = { code: 'CHANGE_BOOKING', label: '调整预约', targetWorkItemKey: null, target: { kind: 'FBA_APPOINTMENT', appointmentId: 'internal-id', batchKey: 'FBA_APPOINTMENT:1', sources: [] } }
const wrapper = render(workDetail({ item: workItem({ allowedActions: [action], nextAction: action }), references: [{ kind: 'FBA_APPOINTMENT', key: 'FBA_APPOINTMENT:1', businessNo: 'AP-TEST', label: '预约' }] }), action)
await flushPromises(); wrapper.getComponent({ name: 'WorkAppointmentForm' }).vm.$emit('receiving', 'FBA_APPOINTMENT:1'); await flushPromises()
const scope = wrapper.getComponent({ name: 'WorkReceivingPanel' })
expect(scope.props('batchKey')).toBe('FBA_APPOINTMENT:1')
scope.vm.$emit('updated'); await flushPromises()
expect(wrapper.emitted('updated')).toHaveLength(1)
expect(getWorkDetail).toHaveBeenCalledTimes(2)
expect(getWorkDetail).toHaveBeenLastCalledWith('work-delivery-1', expect.any(AbortSignal))
expect(wrapper.findComponent({ name: 'WorkReceivingPanel' }).exists()).toBe(true)
expect(wrapper.emitted('saved')).toBeUndefined()
scope.vm.$emit('appointment', 'AP-LATER'); await flushPromises()
expect(wrapper.getComponent({ name: 'WorkAppointmentForm' }).props('appointmentNo')).toBe('AP-LATER')
wrapper.unmount()
})
it('resolves the saved later batch and offers its real vehicle next action instead of refreshing the historical work', async () => {
const edit: WorkAction = { code: 'CHANGE_BOOKING', label: '调整预约', targetWorkItemKey: null, target: { kind: 'FBA_APPOINTMENT', appointmentId: '1', batchKey: 'FBA_APPOINTMENT:1', sources: [] } }
const original = workDetail({ item: workItem({ allowedActions: [edit], nextAction: edit }), references: [{ kind: 'FBA_APPOINTMENT', key: 'FBA_APPOINTMENT:1', businessNo: 'AP-OLD', label: '预约' }] })
const wrapper = render(original, edit); await flushPromises()
wrapper.getComponent({ name: 'WorkAppointmentForm' }).vm.$emit('receiving', 'FBA_APPOINTMENT:1'); await flushPromises()
wrapper.getComponent({ name: 'WorkReceivingPanel' }).vm.$emit('appointment', 'AP-LATER-40'); await flushPromises()
const transport: WorkAction = { code: 'ARRANGE_TRANSPORT', label: '继续安排本批车辆', targetWorkItemKey: 'real-transport-later', target: { kind: 'FLEET_TRIP', tripId: null, batchKeys: ['FBA_APPOINTMENT:40'] } }
const childDetail = workDetail({ item: workItem({ workItemKey: 'real-work-child', batchKey: 'FBA_APPOINTMENT:40', nextAction: transport, allowedActions: [transport] }) })
vi.mocked(resolveBatchWork).mockResolvedValue({ batchKey: 'FBA_APPOINTMENT:40', customerId: 'customer-a', detail: childDetail, candidates: [] })
wrapper.getComponent({ name: 'WorkAppointmentForm' }).vm.$emit('saved', batchContext('AP-LATER-40', 'FBA_APPOINTMENT:40').appointment); await flushPromises()
expect(resolveBatchWork).toHaveBeenCalledWith('FBA_APPOINTMENT:40', undefined, expect.any(AbortSignal))
expect(getWorkDetail).toHaveBeenCalledTimes(1)
expect(wrapper.emitted('saved')).toBeUndefined()
expect(wrapper.emitted('open')).toEqual([['real-work-child']]); wrapper.unmount()
const current = render(childDetail); await flushPromises()
expect(current.get('.primary-next-action').text()).toBe('继续安排本批车辆')
await current.get('.primary-next-action').trigger('click'); await flushPromises()
expect(current.emitted('open')).toEqual([['real-transport-later', transport]]); current.unmount()
})
it('displays all associated containers of a shared trip without creating duplicate transport work', async () => {
const wrapper = render(workDetail({ item: workItem({ type: 'TRANSPORT', containers: [{ containerBookingId: '1', bookingNo: 'D-1', containerNo: 'TEST-CN-A' }, { containerBookingId: '2', bookingNo: 'D-2', containerNo: 'TEST-CN-B' }] }) })); await flushPromises()
expect(wrapper.findAll('.container-links button')).toHaveLength(2)
@@ -4,7 +4,7 @@ import LoadErrorState from '@/shared/components/LoadErrorState.vue'
import ApiErrorMeta from '@/shared/components/ApiErrorMeta.vue'
import { getApiErrorDetails, type ApiErrorDetails } from '@/shared/api/http'
import { getWorkDetail, type WorkAction, type WorkDetail, type WorkCommand, type WorkCommandResult } from './workApi'
import { actionAllowed, actionRoute, referenceRoute, commandName, flowLabels, typeLabels, workDate, workStatus, workReason } from './workPresentation'
import { actionAllowed, actionRoute, referenceRoute, commandName, flowLabels, typeLabels, workDate, workStatus, workReason, sameAction } from './workPresentation'
import CargoVerificationForm from './CargoVerificationForm.vue'
import WorkCommandForm from './WorkCommandForm.vue'
import WorkAppointmentForm from './WorkAppointmentForm.vue'
@@ -13,13 +13,20 @@ import WorkDispatchForm from './WorkDispatchForm.vue'
import WorkExistingDispatchForm from './WorkExistingDispatchForm.vue'
import WorkReceiptPlans from './WorkReceiptPlans.vue'
import AppointmentBatchForm from './AppointmentBatchForm.vue'
import WorkReceivingPanel from './WorkReceivingPanel.vue'
import WorkBatchContinuation from './WorkBatchContinuation.vue'
import type { FbaAppointmentDto } from '@/modules/overseas-warehouse'
import type { LeaveGuard } from './useWorkDraft'
const props = defineProps<{ itemKey: string; initialAction?: WorkAction | null; canLeave: LeaveGuard }>()
const emit = defineEmits<{ open: [key: string, action?: WorkAction]; external: [path: string]; saved: [result?: WorkCommandResult, command?: WorkCommand['command']]; updated: []; container: [id: string, label: string] }>()
const detail = ref<WorkDetail | null>(null), loading = ref(false), error = ref<ApiErrorDetails | null>(null), action = ref<WorkAction | null>(null)
const receivingOwners = computed(() => [detail.value?.item.owner, ...(detail.value?.relatedItems.map(item => item.owner) || [])].filter((person): person is { id: string; name: string } => !!person?.id))
const actionNotice = ref('')
const saveCompleted = ref(false)
const creatingFromCargo = ref(false)
const batchKey = ref<string | null>(null), openedAppointmentNo = ref<string | null>(null)
const receivingKey = ref<string | null>(null)
const continuation = ref<{ batchKey: string; customerId?: string; labels?: Array<{ customerId: string; label: string }> } | null>(null)
let controller: AbortController | null = null, request = 0
async function load() {
const generation = ++request; controller?.abort(); controller = new AbortController(); loading.value = true; error.value = null
@@ -49,24 +56,38 @@ const existingDispatches = computed(() => {
return /^DISPATCH:\d+$/.test(batchKey) && item?.batchKey === batchKey && item.batchNo ? [{ batchKey, dispatchNo: item.batchNo }] : []
})
const canAct = computed(() => !!detail.value && !!action.value && actionAllowed(detail.value.item, action.value) && !error.value && !loading.value)
const secondaryActions = computed(() => detail.value?.item.allowedActions.filter(candidate => candidate.code !== action.value?.code && (action.value || !detail.value?.item.nextAction || !sameAction(candidate, detail.value.item.nextAction))) || [])
async function choose(next: WorkAction) {
if (!detail.value || loading.value || error.value || !await props.canLeave()) return
actionNotice.value = ''
if (!actionAllowed(detail.value.item, next)) { actionNotice.value = '操作资格已变化,请刷新事项后查看当前下一步。'; return }
saveCompleted.value = false
if (next.targetWorkItemKey && next.targetWorkItemKey !== props.itemKey) { emit('open', next.targetWorkItemKey, next); return }
const path = actionRoute(next, detail.value.references, detail.value.item)
if (path) { emit('external', path); return }
action.value = next; batchKey.value = null; openedAppointmentNo.value = null; creatingFromCargo.value = false
action.value = next; batchKey.value = null; openedAppointmentNo.value = null; receivingKey.value = null; continuation.value = null; creatingFromCargo.value = false
if (next.code === 'EDIT_BATCH' && next.target.kind === 'FBA_APPOINTMENT' && next.target.batchKey) { batchKey.value = next.target.batchKey; return }
if (next.target.kind === 'WORK_COMMAND' && !commandName(next)) actionNotice.value = '当前操作尚未提供可用入口,请联系负责人核对。'
if (next.target.kind === 'FBA_APPOINTMENT' && !fbaNumber.value && !createSources.value) actionNotice.value = '尚未关联可操作的预约记录,请先核实批次与预约关系。'
if (next.target.kind === 'FLEET_TRIP' && !dispatchBatchKeys.value?.length && !existingDispatches.value.length) actionNotice.value = '尚未关联可进入的车次或可排批次,请核对运输来源。'
}
function saved(result?: WorkCommandResult, command?: WorkCommand['command']) { emit('saved', result, command) }
async function saved(result?: WorkCommandResult, command?: WorkCommand['command']) {
action.value = null; batchKey.value = null; openedAppointmentNo.value = null; receivingKey.value = null; creatingFromCargo.value = false; actionNotice.value = ''; saveCompleted.value = true
emit('saved', result, command)
await load()
}
async function savedAppointment(appointment: FbaAppointmentDto) {
if (!appointment.batchKey) { await saved(); return }
action.value = null; batchKey.value = null; openedAppointmentNo.value = null; receivingKey.value = null; saveCompleted.value = true
continuation.value = { batchKey: appointment.batchKey, labels: [...new Set(appointment.items.map(item => item.customerId))].map(customerId => ({ customerId, label: appointment.items.filter(item => item.customerId === customerId).map(item => item.inboundCode || '—').join('、') })) }
emit('updated')
}
async function receivingUpdated() { emit('updated'); await load() }
async function cargoSaved() { emit('updated'); await load() }
async function createFromCargo() { if (canAct.value && await props.canLeave()) creatingFromCargo.value = true }
async function openBatch(key: string) { if (await props.canLeave()) { batchKey.value = key; openedAppointmentNo.value = null } }
async function openAppointment(number: string) { if (await props.canLeave()) { openedAppointmentNo.value = number; batchKey.value = null } }
async function openBatch(key: string) { if (await props.canLeave()) { batchKey.value = key; openedAppointmentNo.value = null; receivingKey.value = null } }
async function openAppointment(number: string) { if (await props.canLeave()) { openedAppointmentNo.value = number; batchKey.value = null; receivingKey.value = null } }
async function openReceiving(key: string) { if (await props.canLeave()) { receivingKey.value = key; batchKey.value = null; openedAppointmentNo.value = null } }
onMounted(async () => {
await load()
// A predecessor's action is only a hint: use the newly fetched item's own qualification.
@@ -85,25 +106,30 @@ onBeforeUnmount(() => { ++request; controller?.abort() })
<template v-if="detail">
<h3>{{ detail.item.title }}</h3><p>{{ typeLabels[detail.item.type] }} · {{ flowLabels[detail.item.flow] }} · {{ workStatus(detail.item) }}</p>
<p>{{ workDate(detail.item) }} · {{ detail.item.timezone || '地点时区待核实' }}</p><p>{{ detail.item.destinationName || detail.item.originName || '地点待核实' }} · {{ detail.item.owner?.name || '待分派' }}</p>
<p class="followup-summary">下次跟进:{{ detail.item.followupDate || '尚未安排' }}<span v-if="detail.item.dateBasis === 'NONE'"> · 作业日期未定,跟进日不作为作业日期</span></p>
<p v-if="detail.item.executionStatus !== 'COMPLETED' && (!detail.item.owner || !detail.item.followupDate)" class="work-warning">{{ !detail.item.owner ? '负责人待分派。' : '' }}{{ !detail.item.followupDate ? '请补充下一次跟进安排。' : '' }}请记录跟进;若无操作权限,请联系负责人。</p>
<div class="container-links"><button v-for="container in detail.item.containers" :key="container.containerBookingId" type="button" @click="emit('container', container.containerBookingId, container.containerNo || container.bookingNo || '本柜')">{{ container.containerNo || container.bookingNo || '—' }} · 本柜待办</button></div>
<p v-for="reason in [...detail.item.blockReasons, ...detail.item.missingFields, ...detail.item.overdueReasons]" :key="reason" class="work-warning">{{ workReason(reason) }}</p>
<p v-if="detail.returnHandoff">还空责任:{{ detail.returnHandoff.from.name }} → {{ detail.returnHandoff.to.name }} · {{ detail.returnHandoff.status === 'PENDING_ACCEPTANCE' ? '接手方待确认,持续跟进' : '已确认接手' }}</p>
<template v-if="!action">
<el-button v-if="detail.item.nextAction" type="primary" :disabled="loading || !!error" @click="choose(detail.item.nextAction)">{{ detail.item.nextAction.label }}</el-button>
<template v-if="!action && !continuation">
<p v-if="saveCompleted" role="status" class="save-result">本次保存已完成。{{ loading ? '正在读取当前下一步…' : error ? '下一步读取失败,请重试读取事项,无需重复提交已保存内容。' : detail.item.executionStatus === 'COMPLETED' ? '当前事项已完成,可返回查看其他待办。' : '请按当前下一步继续处理。' }}</p>
<el-button v-if="detail.item.nextAction" class="primary-next-action" type="primary" :disabled="loading || !!error" @click="choose(detail.item.nextAction)">{{ detail.item.nextAction.label }}</el-button>
<p v-else-if="detail.item.executionStatus !== 'COMPLETED'">当前没有可执行的下一步,请根据缺项或前置说明联系负责人。</p>
</template>
<p v-if="actionNotice" role="status" class="work-warning">{{ actionNotice }}</p>
<AppointmentBatchForm v-if="batchKey" :key="batchKey" :batch-key="batchKey" @updated="emit('updated')" @appointment="openAppointment" />
<WorkAppointmentForm v-else-if="openedAppointmentNo" :key="openedAppointmentNo" :appointment-no="openedAppointmentNo" :cancel="false" :can-write="true" @saved="saved()" @batch="openBatch" />
<WorkBatchContinuation v-if="continuation" :key="JSON.stringify(continuation)" v-bind="continuation" @open="key => emit('open', key)" />
<WorkReceivingPanel v-else-if="receivingKey" :key="receivingKey" :batch-key="receivingKey" :owners="receivingOwners" :can-write="!loading && !error" @updated="receivingUpdated" @appointment="openAppointment" @batch="openBatch" @external="path => emit('external', path)" />
<AppointmentBatchForm v-else-if="batchKey" :key="batchKey" :batch-key="batchKey" @updated="emit('updated')" @appointment="openAppointment" />
<WorkAppointmentForm v-else-if="openedAppointmentNo" :key="openedAppointmentNo" :appointment-no="openedAppointmentNo" :cancel="false" :can-write="true" @saved="savedAppointment" @batch="openBatch" @receiving="openReceiving" />
<WorkCommandForm v-else-if="action && commandName(action)" :key="`${itemKey}:${action.code}`" :detail="detail" :action="action" :refreshing="loading || !!error" @refresh="load" @saved="saved" />
<template v-else-if="cargoSource && !creatingFromCargo"><CargoVerificationForm :key="`${cargoSource.customerId}:${cargoSource.sourceKey}:${cargoSource.destinationKey}`" :source="cargoSource" @saved="cargoSaved" /><el-button :disabled="!canAct" @click="createFromCargo">核对货物并新建原预约</el-button></template>
<WorkAppointmentForm v-else-if="fbaNumber && action" :key="`${fbaNumber}:${action.code}`" :appointment-no="fbaNumber" :cancel="action.code === 'CANCEL_BOOKING'" :can-write="canAct" @saved="saved()" @batch="openBatch" />
<WorkAppointmentForm v-else-if="fbaNumber && action" :key="`${fbaNumber}:${action.code}`" :appointment-no="fbaNumber" :cancel="action.code === 'CANCEL_BOOKING'" :can-write="canAct" @saved="savedAppointment" @batch="openBatch" @receiving="openReceiving" />
<WorkCreateAppointmentForm v-else-if="createSources" :key="JSON.stringify(createSources)" :sources="createSources" :can-write="canAct" @saved="saved()" />
<WorkDispatchForm v-else-if="dispatchBatchKeys?.length" :key="JSON.stringify(dispatchBatchKeys)" :batch-keys="dispatchBatchKeys" :can-write="canAct" @updated="emit('updated')" @external="path => emit('external', path)" />
<WorkDispatchForm v-else-if="dispatchBatchKeys?.length" :key="JSON.stringify(dispatchBatchKeys)" :batch-keys="dispatchBatchKeys" :can-write="canAct" @updated="emit('updated')" @external="path => emit('external', path)" @batch="openBatch" />
<WorkExistingDispatchForm v-else-if="existingDispatches.length" :key="JSON.stringify(existingDispatches)" :dispatches="existingDispatches" :can-write="canAct" @updated="emit('updated')" @external="path => emit('external', path)" />
<WorkReceiptPlans v-else-if="action?.target.kind === 'WAREHOUSE_RECEIPT'" :key="action.target.containerBookingId" :container-booking-id="action.target.containerBookingId" :can-write="canAct" @updated="emit('updated')" @external="path => emit('external', path)" />
<section v-else-if="action?.target.kind === 'READ_ONLY'" aria-label="原业务进度"><h4>原业务进度</h4><p v-for="reference in action.target.references" :key="`${reference.kind}:${reference.key}`"><el-button v-if="referenceRoute(reference)" :disabled="!canAct" @click="emit('external', referenceRoute(reference)!)">{{ reference.label }} · {{ reference.businessNo }}</el-button><span v-else>{{ reference.label }} · {{ reference.businessNo || '—' }}</span></p></section>
<details v-if="detail.item.allowedActions.length"><summary>更多操作</summary><div class="more-actions"><el-button v-for="candidate in detail.item.allowedActions.filter(candidate => candidate.code !== action?.code)" :key="`${candidate.code}:${candidate.targetWorkItemKey}`" :disabled="loading || !!error" @click="choose(candidate)">{{ candidate.label }}</el-button></div></details>
<details v-if="secondaryActions.length"><summary>更多操作</summary><div class="more-actions"><el-button v-for="candidate in secondaryActions" :key="`${candidate.code}:${candidate.targetWorkItemKey}`" :disabled="loading || !!error" @click="choose(candidate)">{{ candidate.label }}</el-button></div></details>
<details><summary>关联工作 · {{ detail.relatedItems.length }} 项</summary><div v-for="related in detail.relatedItems" :key="related.workItemKey" class="related-row"><div>{{ related.title }}<p>{{ workStatus(related) }} · {{ workDate(related) }}</p></div><el-button @click="emit('open', related.workItemKey)">查看</el-button></div></details>
<details><summary>原业务记录 · {{ detail.references.length }} 项</summary><p v-for="reference in detail.references" :key="`${reference.kind}:${reference.key}`">{{ reference.label }} · {{ reference.businessNo || '—' }}</p></details>
<details :open="action?.code === 'VIEW_HISTORY'"><summary>操作记录</summary><div v-for="(entry, index) in detail.history" :key="index" class="history-entry"><b>{{ entry.action }}</b><p>{{ entry.summary }}</p><small>{{ entry.operatorName || '—' }} · {{ entry.occurredAt }}</small></div><p v-if="!detail.history.length">暂无记录</p></details>
@@ -9,7 +9,7 @@ vi.mock('element-plus', () => ({ ElMessage: { warning: vi.fn(), success: vi.fn()
vi.mock('@/modules/overseas-warehouse', async original => ({ ...await original<typeof import('@/modules/overseas-warehouse')>(), getBatchDispatchCandidates: vi.fn(), createDispatchDraftContainer: vi.fn(), listDispatchDrafts: vi.fn(), lockDispatchDraftPallet: vi.fn(), preArrangeDraftDispatch: vi.fn(), releaseDispatchDraft: vi.fn() }))
const candidate: BatchDispatchCandidate = { planPalletId: '9007199254740993', palletNo: 'PL-TEST', planId: 'plan-1', planNo: 'IP-001', customerId: 'customer-a', sourceStage: 'RECEIVED', packageCount: 12, allocations: [{ planPalletId: '9007199254740993', batchKey: 'FBA_APPOINTMENT:1', customerId: 'customer-a', sourceKey: 'BOOKING:9', destinationKey: 'FBA:ONT8', packageCount: 12 }], blockReasons: [] }
let guard: LeaveGuard
function render() { return mount(WorkDispatchForm, { props: { batchKeys: ['FBA_APPOINTMENT:1'], canWrite: true }, global: { provide: { 'appointment-work-leave-guard': (value: LeaveGuard) => { guard = value; return () => undefined } }, stubs: { ElButton: { props: ['disabled'], template: '<button :disabled="disabled"><slot /></button>' }, LoadErrorState: { props: ['message'], template: '<p>{{ message }}</p>' }, ApiErrorMeta: true, TripPreparationDialog: { name: 'TripPreparationDialog', props: ['warehouseId', 'dispatchNos'], template: '<div />' } } } }) }
function render() { return mount(WorkDispatchForm, { props: { batchKeys: ['FBA_APPOINTMENT:1'], canWrite: true }, global: { provide: { 'appointment-work-leave-guard': (value: LeaveGuard) => { guard = value; return () => undefined } }, stubs: { WorkSharedTripForm: { name: 'WorkSharedTripForm', props: ['dispatchNo', 'canWrite'], template: '<div />' }, ElButton: { props: ['disabled'], template: '<button :disabled="disabled"><slot /></button>' }, LoadErrorState: { props: ['message'], template: '<p>{{ message }}</p>' }, ApiErrorMeta: true, TripPreparationDialog: { name: 'TripPreparationDialog', props: ['warehouseId', 'dispatchNos'], template: '<div />' } } } }) }
function button(wrapper: ReturnType<typeof render>, text: string) { return wrapper.findAll('button').find(button => button.text() === text)! }
beforeEach(() => {
vi.clearAllMocks(); access.allowed = true
@@ -17,7 +17,7 @@ beforeEach(() => {
vi.mocked(listDispatchDrafts).mockResolvedValue([])
vi.mocked(createDispatchDraftContainer).mockResolvedValue({ id: 'container-1', capacity: 30, palletIds: [] })
vi.mocked(lockDispatchDraftPallet).mockResolvedValue(null)
vi.mocked(preArrangeDraftDispatch).mockResolvedValue([{ draftContainerId: 'container-1', dispatch: { id: 'internal-dispatch', dispatchNo: 'DS-001', overseasWarehouseId: 'origin-1', overseasWarehouseName: '测试起运仓' } }])
vi.mocked(preArrangeDraftDispatch).mockResolvedValue([{ draftContainerId: 'container-1', dispatch: { id: 'internal-dispatch', dispatchNo: 'DS-001', appointmentBatches: [], overseasWarehouseId: 'origin-1', overseasWarehouseName: '测试起运仓' } }])
})
it('copies exact server allocations into a real draft group and continues into original trip preparation', async () => {
const wrapper = render(); await flushPromises(); await wrapper.get('input[type=checkbox]').setValue(true)
@@ -29,6 +29,23 @@ it('copies exact server allocations into a real draft group and continues into o
prepare.vm.$emit('saved', { trip: { tripNo: 'TR-001' } }); expect(wrapper.emitted('external')).toEqual([['/overseas-master-data/trips/TR-001']])
wrapper.unmount()
})
it('opens quantity splitting for only the current batch without locking physical cargo or creating a new full-source appointment', async () => {
const wrapper = render(); await flushPromises()
await button(wrapper, '按当前批次箱数分批').trigger('click')
expect(wrapper.emitted('batch')).toEqual([['FBA_APPOINTMENT:1']])
expect(lockDispatchDraftPallet).not.toHaveBeenCalled(); expect(preArrangeDraftDispatch).not.toHaveBeenCalled(); wrapper.unmount()
})
it('preselects only eligible physical cargo of the entered batch, never unrelated allocations or unknown quantity', async () => {
vi.mocked(getBatchDispatchCandidates).mockResolvedValue({ batchKey: 'FBA_APPOINTMENT:1', version: 4, blockReasons: [], candidates: [candidate, { ...candidate, planPalletId: 'other-batch', allocations: [{ ...candidate.allocations[0]!, batchKey: 'FBA_APPOINTMENT:999' }] }, { ...candidate, planPalletId: 'unknown', packageCount: null }] })
const wrapper = render(); await flushPromises()
const inputs = wrapper.findAll('input[type=checkbox]')
expect(inputs.map(input => (input.element as HTMLInputElement).checked)).toEqual([true, false, false])
expect(inputs[1]!.attributes('disabled')).toBeDefined()
await button(wrapper, '创建本客户排车单').trigger('click'); await flushPromises()
expect(vi.mocked(preArrangeDraftDispatch).mock.calls[0]![0].groups[0]!.planPalletIds).toEqual([candidate.planPalletId])
expect(vi.mocked(preArrangeDraftDispatch).mock.calls[0]![0].groups[0]!.batchAllocations).toEqual(candidate.allocations)
wrapper.unmount()
})
it('replays a submitted draft without re-locking already dispatched pallets after an unknown response', async () => {
vi.mocked(preArrangeDraftDispatch).mockRejectedValueOnce(new Error('lost response'))
const wrapper = render(); await flushPromises(); await wrapper.get('input[type=checkbox]').setValue(true)
@@ -49,7 +66,7 @@ it('recovers a draft container from the same token when its creation response wa
expect(createDispatchDraftContainer).toHaveBeenCalledTimes(1); expect(preArrangeDraftDispatch).toHaveBeenCalledTimes(1); wrapper.unmount()
})
it('shows server blockers and prevents mixing customers or selecting blocked physical cargo', async () => {
vi.mocked(getBatchDispatchCandidates).mockResolvedValue({ batchKey: 'FBA_APPOINTMENT:1', version: 4, blockReasons: [], candidates: [candidate, { ...candidate, planPalletId: '2', customerId: 'customer-b' }, { ...candidate, planPalletId: '3', blockReasons: ['本托货量超过本批剩余可排量'] }] })
vi.mocked(getBatchDispatchCandidates).mockResolvedValue({ batchKey: 'FBA_APPOINTMENT:1', version: 4, blockReasons: [], candidates: [candidate, { ...candidate, planPalletId: '2', customerId: 'customer-b', allocations: [{ ...candidate.allocations[0]!, customerId: 'customer-b', planPalletId: '2' }] }, { ...candidate, planPalletId: '3', blockReasons: ['本托货量超过本批剩余可排量'] }] })
const wrapper = render(); await flushPromises(); const inputs = wrapper.findAll('input[type=checkbox]')
expect(inputs[2]!.attributes('disabled')).toBeDefined(); expect(wrapper.text()).toContain('本托货量超过本批剩余可排量')
await inputs[0]!.setValue(true); await inputs[1]!.setValue(true)
@@ -61,3 +78,17 @@ it('does not read or write scoped cargo without all original permissions', async
access.allowed = false; const wrapper = render(); await flushPromises()
expect(getBatchDispatchCandidates).not.toHaveBeenCalled(); expect(preArrangeDraftDispatch).not.toHaveBeenCalled(); wrapper.unmount()
})
it('continues the actual later 60-box dispatch through the shared-trip entry without re-creating or reallocating cargo', async () => {
const sixty = { ...candidate, packageCount: 60, allocations: [{ ...candidate.allocations[0]!, packageCount: 60 }] }
vi.mocked(getBatchDispatchCandidates).mockResolvedValue({ batchKey: 'FBA_APPOINTMENT:1', version: 4, candidates: [sixty], blockReasons: [] })
vi.mocked(preArrangeDraftDispatch).mockResolvedValue([{ draftContainerId: 'container-1', dispatch: { id: 'internal-later', dispatchNo: 'DS-60', appointmentBatches: [], overseasWarehouseId: 'origin-1', packageCount: 60 } }])
const wrapper = render(); await flushPromises(); await button(wrapper, '创建本客户排车单').trigger('click'); await flushPromises()
await button(wrapper, '与同仓其他排车单共车').trigger('click'); await flushPromises()
const shared = wrapper.getComponent({ name: 'WorkSharedTripForm' })
expect(shared.props()).toMatchObject({ dispatchNo: 'DS-60', canWrite: true })
expect(preArrangeDraftDispatch).toHaveBeenCalledTimes(1); expect(vi.mocked(preArrangeDraftDispatch).mock.calls[0]![0].groups[0]!.batchAllocations).toEqual(sixty.allocations)
shared.vm.$emit('busy', true); await flushPromises(); expect(button(wrapper, '继续安排其他实物').attributes('disabled')).toBeDefined()
shared.vm.$emit('external', '/overseas-master-data/trips/TR-100'); expect(wrapper.emitted('external')).toEqual([['/overseas-master-data/trips/TR-100']])
wrapper.unmount()
})
@@ -7,32 +7,41 @@ import { TripPreparationDialog } from '@/modules/overseas-master-data'
import LoadErrorState from '@/shared/components/LoadErrorState.vue'
import ApiErrorMeta from '@/shared/components/ApiErrorMeta.vue'
import { getApiErrorDetails, type ApiErrorDetails } from '@/shared/api/http'
import WorkSharedTripForm from './WorkSharedTripForm.vue'
import { rejectedCommand, useWorkDraft } from './useWorkDraft'
const props = defineProps<{ batchKeys: string[]; canWrite: boolean }>()
const emit = defineEmits<{ updated: []; external: [path: string] }>()
const emit = defineEmits<{ updated: []; external: [path: string]; batch: [key: string] }>()
const access = useAccessPreviewStore(), contexts = ref<BatchDispatchCandidates[]>([]), selected = ref<string[]>([])
const loading = ref(false), saving = ref(false), error = ref<ApiErrorDetails | null>(null), saveError = ref<ApiErrorDetails | null>(null)
const capacity = ref(30), result = ref<DispatchSummaryDto | null>(null), prepareOpen = ref(false), rejected = ref(false)
const sharedTripOpen = ref(false), sharedTripBusy = ref(false)
const selectionBaseline = ref('[]')
const pending = ref<{ token: string; capacity: number; rows: BatchDispatchCandidate[]; containerId: string | null; lockedIds: string[]; submitting: boolean } | null>(null)
const readable = computed(() => ['platform:appointment:list', 'platform:overseas-warehouse:last-mile-order:list', 'platform:overseas-warehouse:inbound-order:list'].every(permission => access.can(permission)))
const writable = computed(() => props.canWrite && readable.value && access.can('platform:overseas-warehouse:inbound-order:smart-dispatch'))
const rows = computed(() => contexts.value.flatMap(context => context.candidates.map(row => ({ ...row, blockReasons: [...context.blockReasons, ...row.blockReasons] }))))
function reasons(row: BatchDispatchCandidate) {
const duplicates = rows.value.filter(other => other.planPalletId === row.planPalletId).length > 1
return [...row.blockReasons, ...(!row.allocations.length ? ['缺少逐来源批次分配'] : []), ...(duplicates ? ['同一实物出现在多个批次,请核对分批范围'] : [])]
return [...row.blockReasons, ...(row.packageCount == null || row.packageCount <= 0 ? ['实物箱数待核实'] : []), ...(!row.allocations.length ? ['缺少逐来源批次分配'] : []), ...(row.allocations.some(allocation => !props.batchKeys.includes(allocation.batchKey) || allocation.customerId !== row.customerId) ? ['候选不属于当前批次和客户范围'] : []), ...(duplicates ? ['同一实物出现在多个批次,请核对分批范围'] : [])]
}
const chosen = computed(() => rows.value.filter(row => selected.value.includes(row.planPalletId)))
useWorkDraft(computed(() => selected.value.length > 0 && !result.value), computed(() => saving.value || !!pending.value))
useWorkDraft(computed(() => JSON.stringify(selected.value) !== selectionBaseline.value && !result.value), computed(() => saving.value || !!pending.value))
async function load() {
if (!readable.value || pending.value) return
loading.value = true; error.value = null
try { contexts.value = await Promise.all([...new Set(props.batchKeys)].map(getBatchDispatchCandidates)) }
try {
contexts.value = await Promise.all([...new Set(props.batchKeys)].map(getBatchDispatchCandidates))
const eligible = rows.value.filter(row => !reasons(row).length && row.packageCount != null && row.packageCount > 0)
selected.value = props.batchKeys.length === 1 && eligible.length <= capacity.value && new Set(eligible.map(row => row.customerId)).size === 1 ? eligible.map(row => row.planPalletId) : []
selectionBaseline.value = JSON.stringify(selected.value)
}
catch (cause) { error.value = getApiErrorDetails(cause, '批次可排实物读取失败') }
finally { loading.value = false }
}
function select(row: BatchDispatchCandidate, checked: boolean) {
if (!writable.value || pending.value || saving.value || loading.value || error.value || reasons(row).length) return
if (!checked) { selected.value = selected.value.filter(id => id !== row.planPalletId); return }
if (selected.value.includes(row.planPalletId)) return
if (chosen.value.some(current => current.customerId !== row.customerId)) { ElMessage.warning('一张排车单只选择同一客户实物;其余客户可继续分别安排'); return }
if (selected.value.length >= capacity.value) { ElMessage.warning('已达到所选车型托位上限'); return }
selected.value = [...selected.value, row.planPalletId]
@@ -72,16 +81,17 @@ async function refreshRejected() {
finally { saving.value = false }
}
function tripSaved(value: { trip: { tripNo: string } }) { prepareOpen.value = false; emit('updated'); emit('external', `/overseas-master-data/trips/${encodeURIComponent(value.trip.tripNo)}`) }
async function continueArranging() { if (!pending.value && !saving.value) { result.value = null; await load() } }
async function continueArranging() { if (!pending.value && !saving.value && !sharedTripBusy.value) { sharedTripOpen.value = false; result.value = null; await load() } }
onMounted(load)
</script>
<template>
<section class="work-form" aria-label="按预约批次排车">
<h3>按批次选择真实托盘</h3><p>每次选择同一客户的实物创建排车单,再安排车辆和司机;逐来源数量由服务端候选确定。</p>
<h3>按批次选择真实托盘</h3><p>单客户单批入口仅预选本批当前合格实物;每次选择同一客户创建排车单,再安排车辆和司机。逐来源数量由服务端候选确定。</p>
<el-button v-if="batchKeys.length === 1 && !result" :disabled="loading || saving || !!pending" @click="emit('batch', batchKeys[0]!)">按当前批次箱数分批</el-button><p v-if="batchKeys.length === 1 && !result">只安排部分箱数时,先核对本批逐来源数量并分批;新的当前批次继续使用原排车资格。若箱数无法对应完整实物,请先在原库存作业中完成拆托;不把整票重新选入。</p>
<p v-if="!readable">读取批次实物需要预约、尾程订单和入仓单列表权限。</p>
<LoadErrorState v-if="error" title="批次可排实物读取失败" :message="error.message" :loading="loading" @retry="load"><template #details><ApiErrorMeta :details="error" /></template></LoadErrorState>
<p v-if="loading">正在核对批次、客户与实物来源…</p>
<template v-if="result"><p>已创建排车单:{{ result.dispatchNo }}</p><el-button v-if="result.overseasWarehouseId && access.can('platform:fleet:trip:list') && access.can('platform:fleet:trip:edit')" type="primary" @click="prepareOpen = true">安排车次、车辆与司机</el-button><p v-if="!result.overseasWarehouseId">排车结果未提供起运仓,需在原排车单核对。</p><el-button v-if="access.can('platform:overseas-warehouse:dispatch:list')" @click="emit('external', `/overseas-warehouse/dispatches?dispatchNo=${encodeURIComponent(result.dispatchNo)}`)">查看原排车单</el-button><el-button @click="continueArranging">继续安排其他实物</el-button></template>
<template v-if="result"><p>已创建排车单:{{ result.dispatchNo }}</p><el-button v-if="result.overseasWarehouseId && access.can('platform:fleet:trip:list') && access.can('platform:fleet:trip:edit')" type="primary" :disabled="sharedTripBusy" @click="prepareOpen = true">继续安排本批车辆</el-button><el-button v-if="access.can('platform:overseas-warehouse:dispatch:list') && access.can('platform:fleet:trip:list') && access.can('platform:fleet:trip:edit')" @click="sharedTripOpen = true">与同仓其他排车单共车</el-button><WorkSharedTripForm v-if="sharedTripOpen" :dispatch-no="result.dispatchNo" :can-write="canWrite" @busy="sharedTripBusy = $event" @updated="emit('updated')" @external="path => emit('external', path)" /><p v-if="!result.overseasWarehouseId">排车结果未提供起运仓,需在原排车单核对。</p><el-button v-if="access.can('platform:overseas-warehouse:dispatch:list')" @click="emit('external', `/overseas-warehouse/dispatches?dispatchNo=${encodeURIComponent(result.dispatchNo)}`)">查看原排车单</el-button><el-button :disabled="sharedTripBusy" @click="continueArranging">继续安排其他实物</el-button></template>
<template v-else-if="readable"><p v-for="reason in contexts.flatMap(context => context.blockReasons)" :key="reason">{{ reason }}</p><label>预排车型<select v-model.number="capacity" :disabled="saving || !!pending || !writable"><option v-for="spec in dispatchVehicleSpecs" :key="spec.value" :value="spec.capacity">{{ spec.label }}</option></select></label>
<table class="density-table"><thead><tr><th>选择</th><th>托盘码</th><th>入库单号</th><th>来源</th><th>箱数</th><th>不可选择原因</th></tr></thead><tbody><tr v-for="(row, index) in rows" :key="`${row.planPalletId}:${index}`"><td><input type="checkbox" :checked="selected.includes(row.planPalletId)" :disabled="!writable || loading || saving || !!pending || !!error || !!reasons(row).length" @change="changeSelection(row, $event)"></td><td>{{ row.palletNo || '—' }}</td><td>{{ row.planNo || '—' }}</td><td>{{ row.sourceStage === 'RECEIVED' ? '已收货实物' : row.sourceStage === 'PLAN' ? '计划托盘' : '原业务来源' }}</td><td>{{ row.packageCount ?? '待核实' }}</td><td>{{ reasons(row).join(';') || '可选' }}</td></tr></tbody></table>
<p v-if="!loading && !error && !rows.length">当前批次尚无可排实物。</p><el-button type="primary" :disabled="!writable || loading || !!error" :loading="saving" @click="save">{{ pending ? '重试本次预排' : '创建本客户排车单' }}</el-button>
@@ -6,22 +6,22 @@ const state = vi.hoisted(() => ({ allowed: true }))
vi.mock('@/core/access/accessPreview', () => ({ useAccessPreviewStore: () => ({ can: () => state.allowed }) }))
vi.mock('@/modules/overseas-warehouse', async original => ({ ...await original<typeof import('@/modules/overseas-warehouse')>(), getDispatch: vi.fn() }))
function render() { return mount(WorkExistingDispatchForm, { props: { dispatches: [{ batchKey: 'DISPATCH:9007199254740999', dispatchNo: 'DS-ORIGINAL' }], canWrite: true }, global: { stubs: { ElButton: { props: ['disabled'], template: '<button :disabled="disabled"><slot /></button>' }, LoadErrorState: { props: ['message'], template: '<p>{{ message }}</p>' }, ApiErrorMeta: true, TripPreparationDialog: { name: 'TripPreparationDialog', props: ['warehouseId', 'dispatchNos'], template: '<div />' } } } }) }
beforeEach(() => { vi.clearAllMocks(); state.allowed = true; vi.mocked(getDispatch).mockResolvedValue({ id: '9007199254740999', dispatchNo: 'DS-ORIGINAL', overseasWarehouseId: 'origin-1', overseasWarehouseName: '原起运仓', status: 'PENDING_DEPARTURE', packageCount: 12 }) })
beforeEach(() => { vi.clearAllMocks(); state.allowed = true; vi.mocked(getDispatch).mockResolvedValue({ id: '9007199254740999', dispatchNo: 'DS-ORIGINAL', appointmentBatches: [], overseasWarehouseId: 'origin-1', overseasWarehouseName: '原起运仓', status: 'PENDING_DEPARTURE', packageCount: 12 }) })
it('reads the original dispatch and passes its existing cargo and origin to trip preparation', async () => {
const wrapper = render(); await flushPromises()
expect(getDispatch).toHaveBeenCalledExactlyOnceWith('DS-ORIGINAL')
await wrapper.findAll('button').find(button => button.text() === '安排原排车单车次')!.trigger('click')
await wrapper.findAll('button').find(button => button.text() === '继续安排本批车辆')!.trigger('click')
const dialog = wrapper.getComponent({ name: 'TripPreparationDialog' }); expect(dialog.props()).toMatchObject({ warehouseId: 'origin-1', dispatchNos: ['DS-ORIGINAL'] })
dialog.vm.$emit('saved', { trip: { tripNo: 'TR/001' } }); expect(wrapper.emitted('external')).toEqual([['/overseas-master-data/trips/TR%2F001']])
expect(wrapper.text()).not.toContain('9007199254740999'); wrapper.unmount()
})
it('rejects mismatched dispatch identity instead of arranging unrelated cargo', async () => {
vi.mocked(getDispatch).mockResolvedValue({ id: '9007199254740998', dispatchNo: 'DS-ORIGINAL', status: 'PENDING_DEPARTURE' })
vi.mocked(getDispatch).mockResolvedValue({ id: '9007199254740998', dispatchNo: 'DS-ORIGINAL', appointmentBatches: [], status: 'PENDING_DEPARTURE' })
const wrapper = render(); await flushPromises(); expect(wrapper.text()).toContain('排车单与工作批次关联不一致'); expect(wrapper.find('table').exists()).toBe(false); wrapper.unmount()
})
it('opens an already bound real trip instead of preparing another one', async () => {
vi.mocked(getDispatch).mockResolvedValue({ id: '9007199254740999', dispatchNo: 'DS-ORIGINAL', workflow: { tripNo: 'TR-EXISTING', dispatchReview: { status: 'PENDING', reason: null, reviewedAt: null }, loadingReview: { status: 'PENDING', reason: null, reviewedAt: null } } })
const wrapper = render(); await flushPromises(); expect(wrapper.text()).not.toContain('安排原排车单车次')
vi.mocked(getDispatch).mockResolvedValue({ id: '9007199254740999', dispatchNo: 'DS-ORIGINAL', appointmentBatches: [], workflow: { tripNo: 'TR-EXISTING', dispatchReview: { status: 'PENDING', reason: null, reviewedAt: null }, loadingReview: { status: 'PENDING', reason: null, reviewedAt: null } } })
const wrapper = render(); await flushPromises(); expect(wrapper.text()).not.toContain('继续安排本批车辆')
await wrapper.findAll('button').find(button => button.text() === 'TR-EXISTING')!.trigger('click'); expect(wrapper.emitted('external')).toEqual([['/overseas-master-data/trips/TR-EXISTING']]); wrapper.unmount()
})
it('does not read the dispatch without its original list permission', async () => {
@@ -32,7 +32,7 @@ onMounted(load)
<section aria-label="原排车单安排用车"><h3>原排车单安排用车</h3><p>客户仓批次沿用已选实物和原排车单,确认起运仓后安排车次、车辆与司机。</p>
<p v-if="!readable">查看原排车单需要排车列表权限。</p><p v-if="loading">正在核对原排车单与批次…</p>
<LoadErrorState v-if="error" title="原排车单读取失败" :message="error.message" :loading="loading" @retry="load"><template #details><ApiErrorMeta :details="error" /></template></LoadErrorState>
<table v-if="!loading && !error && readable" class="density-table"><thead><tr><th>操作</th><th>排车单号</th><th>起运仓</th><th>箱数</th><th>车次</th></tr></thead><tbody><tr v-for="row in rows" :key="row.dispatchNo"><td><el-button v-if="!row.workflow" :disabled="!writable || row.status !== 'PENDING_DEPARTURE' || !row.overseasWarehouseId" @click="prepare(row)">安排原排车单车次</el-button><el-button @click="emit('external', `/overseas-warehouse/dispatches?dispatchNo=${encodeURIComponent(row.dispatchNo)}`)">查看原排车单</el-button></td><td>{{ row.dispatchNo }}</td><td>{{ row.overseasWarehouseName || '起运仓待核实' }}</td><td>{{ row.packageCount ?? '待核实' }}</td><td><el-button v-if="row.workflow?.tripNo && access.can('platform:fleet:trip:list')" @click="emit('external', `/overseas-master-data/trips/${encodeURIComponent(row.workflow.tripNo)}`)">{{ row.workflow.tripNo }}</el-button><span v-else>尚未关联车次</span></td></tr></tbody></table>
<table v-if="!loading && !error && readable" class="density-table"><thead><tr><th>操作</th><th>排车单号</th><th>起运仓</th><th>箱数</th><th>车次</th></tr></thead><tbody><tr v-for="row in rows" :key="row.dispatchNo"><td><el-button v-if="!row.workflow" :disabled="!writable || row.status !== 'PENDING_DEPARTURE' || !row.overseasWarehouseId" @click="prepare(row)">继续安排本批车辆</el-button><el-button @click="emit('external', `/overseas-warehouse/dispatches?dispatchNo=${encodeURIComponent(row.dispatchNo)}`)">查看原排车单</el-button></td><td>{{ row.dispatchNo }}</td><td>{{ row.overseasWarehouseName || '起运仓待核实' }}</td><td>{{ row.packageCount ?? '待核实' }}</td><td><el-button v-if="row.workflow?.tripNo && access.can('platform:fleet:trip:list')" @click="emit('external', `/overseas-master-data/trips/${encodeURIComponent(row.workflow.tripNo)}`)">{{ row.workflow.tripNo }}</el-button><span v-else>尚未关联车次</span></td></tr></tbody></table>
<TripPreparationDialog v-if="selected?.overseasWarehouseId" v-model="prepareOpen" :warehouse-id="selected.overseasWarehouseId" :warehouse-name="selected.overseasWarehouseName || '起运仓待核实'" :dispatch-nos="[selected.dispatchNo]" @saved="saved" />
</section>
</template>
@@ -0,0 +1,510 @@
import { flushPromises, mount } from '@vue/test-utils'
import { beforeEach, expect, it, vi } from 'vitest'
import { ElMessageBox } from 'element-plus'
import { createAppointmentForm, appointmentPayload } from '@/modules/overseas-warehouse'
import { ApiResponseError } from '@/shared/api/http'
import WorkReceivingPanel from './WorkReceivingPanel.vue'
import { batchContext } from './batch.test-support'
import * as api from './receivingApi'
import { getCargoVerification, saveCargoVerification, type CargoVerificationContext } from './cargoVerificationApi'
import type { LeaveGuard } from './useWorkDraft'
const access = vi.hoisted(() => ({ denied: [] as string[] }))
vi.mock('@/core/auth/auth', () => ({ useAuthStore: () => ({ user: { id: 'owner-current', name: '当前本人' } }) }))
vi.mock('@/core/access/accessPreview', () => ({ useAccessPreviewStore: () => ({ can: (permission: string) => !access.denied.includes(permission) }) }))
vi.mock('element-plus', () => ({ ElMessage: { warning: vi.fn() }, ElMessageBox: { confirm: vi.fn().mockResolvedValue(true) } }))
vi.mock('./cargoVerificationApi', () => ({ getCargoVerification: vi.fn(), saveCargoVerification: vi.fn() }))
vi.mock('./receivingApi', async original => ({ ...await original<typeof import('./receivingApi')>(), getReceivingContext: vi.fn(), getReceivingGroup: vi.fn(), proposeReceivingChange: vi.fn(), resolveReceivingChange: vi.fn(), bookReceiving: vi.fn(), changeReceivingGroup: vi.fn(), refreshReceivingCargo: vi.fn(), saveReceivingPlan: vi.fn(), getReceivingExecutionScope: vi.fn() }))
let guard: LeaveGuard
const detail = () => appointmentPayload({ ...createAppointmentForm(), appointmentStatus: 'SUCCESS', confirmationNo: 'EXT-OLD', appointmentAt: '2026-10-20T10:00:00' })
function context(): api.ReceivingContext {
const batch = batchContext().appointment
batch.items = batch.items.map(item => ({ ...item, sourceVersion: 'source-v3', cargoVerificationVersion: 2 }))
return { batch, executionScope: { version: 'execution-v1', members: batch.items.map(item => ({ member: { batchKey: batch.batchKey!, customerId: item.customerId }, completed: false, canRebook: true, reason: null })) }, agreements: [], pendingChanges: [], plans: [], allowedActions: ['PROPOSE_CUSTOMER_CHANGE', 'BOOK_RECEIVING', 'PLAN_RECEIVING', 'REFRESH_CARGO'], blockReasons: [], transport: { version: 'transport-v1', vehicles: [], blockReasons: [] } }
}
function members(): api.ReceivingMember[] { const c = context(); return c.batch.items.map(item => ({ batchKey: c.batch.batchKey!, appointmentNo: c.batch.appointmentNo, batchVersion: c.batch.version, customerId: item.customerId, customerName: null, sources: [{ sourceKey: item.sourceKey, inboundCode: item.inboundCode || null, destinationKey: item.destinationKey!, packageCount: item.packageCount!, sourceVersion: item.sourceVersion!, verificationVersion: item.cargoVerificationVersion! }] })) }
function agreement(status = 'ACTIVE'): api.ReceivingAgreement { return { agreementKey: 'GROUP-1', version: 4, status, destinationKey: 'FBA:ONT8', details: detail(), timezone: 'America/Los_Angeles', members: members(), warehouseEvidence: '原仓库确认' } }
function pendingChange(): api.ReceivingPending { return { changeKey: 'CHANGE-1', version: 1, status: 'WAITING', intent: { batchKey: 'FBA_APPOINTMENT:1', batchVersion: 3, customerId: 'customer-a', quantities: [{ sourceKey: 'ORDER:1', destinationKey: 'FBA:ONT8', retainedPackages: 0, expectedSourceVersion: 'source-v3', expectedVerificationVersion: 2 }], laterDate: null, ownerId: 'owner-related', nextFollowupDate: '2026-10-21', reason: '本客户后送', transportVersion: 'transport-v1' }, originalMembers: [members()[0]!], originalAgreements: [agreement()], followup: { ownerId: 'owner-related', ownerName: '已核实负责人', nextFollowupDate: '2026-10-21' } } }
function result(status = 'APPLIED'): api.ReceivingResult { return { changeKey: null, status, batches: [context().batch], agreements: [], steps: [{ step: 'BOOK_RECEIVING', status: 'SUCCESS', targetKey: 'GROUP-1', message: '已保存真实预约' }], nextActions: ['REVIEW_TRANSPORT'] } }
function render() { return mount(WorkReceivingPanel, { props: { batchKey: 'FBA_APPOINTMENT:1', canWrite: true, owners: [{ id: 'owner-related', name: '关联负责人' }] }, global: { provide: { 'appointment-work-leave-guard': (value: LeaveGuard) => { guard = value; return () => undefined } }, stubs: {
ElButton: { props: ['disabled', 'nativeType'], template: '<button :disabled="disabled" :type="nativeType || \'button\'"><slot /></button>' },
FbaAppointmentFields: { name: 'FbaAppointmentFields', props: ['model', 'disabled'], template: '<div data-booking-fields />' },
LoadErrorState: { props: ['message', 'showRetry'], template: '<section role="alert">{{ message }}<button v-if="showRetry !== false" @click="$emit(\'retry\')">重试读取</button></section>' }, ApiErrorMeta: true,
} } }) }
function button(wrapper: ReturnType<typeof render>, label: string) { return wrapper.findAll('button').find(row => row.text() === label)! }
beforeEach(() => { vi.clearAllMocks(); access.denied = []; vi.mocked(api.getReceivingExecutionScope).mockImplementation(async members => ({ version: 'execution-v1', members: members.map(member => ({ member, completed: false, canRebook: true, reason: null })) })); vi.mocked(api.getReceivingContext).mockResolvedValue(context()); vi.mocked(api.proposeReceivingChange).mockResolvedValue(result('WAITING')); vi.mocked(api.resolveReceivingChange).mockResolvedValue(result()); vi.mocked(api.bookReceiving).mockResolvedValue(result()); vi.mocked(api.refreshReceivingCargo).mockResolvedValue({ ...result(), steps: [], nextActions: [] }); vi.mocked(api.saveReceivingPlan).mockResolvedValue({ ...result(), steps: [], nextActions: [] }); vi.mocked(api.changeReceivingGroup).mockResolvedValue(result()); vi.mocked(api.getReceivingGroup).mockResolvedValue({ agreement: agreement(), eligibleMembers: members(), excludedMembers: [], transport: context().transport, executionScope: context().executionScope }) })
async function prepareAdjustment(wrapper: ReturnType<typeof render>, quantity = 0) {
await flushPromises(); await button(wrapper, '调整本客户先送 / 后送').trigger('click'); await flushPromises()
await wrapper.get('[aria-label="本次先送箱数"]').setValue(quantity)
await wrapper.get('[aria-label="调整负责人"]').setValue('owner-related')
await wrapper.get('[aria-label="调整原因"]').setValue('本客户后送')
await wrapper.get('[aria-label="确认当前范围"]').setValue(true)
}
it('allows zero retained quantity for one customer and only persists a waiting change with all original versions', async () => {
const wrapper = render(); await prepareAdjustment(wrapper)
await wrapper.get('form').trigger('submit'); await flushPromises()
expect(api.proposeReceivingChange).toHaveBeenCalledWith(expect.objectContaining({ intent: expect.objectContaining({ batchKey: 'FBA_APPOINTMENT:1', batchVersion: 3, customerId: 'customer-a', ownerId: 'owner-related', laterDate: null, transportVersion: 'transport-v1', quantities: [{ sourceKey: 'ORDER:1', destinationKey: 'FBA:ONT8', retainedPackages: 0, expectedSourceVersion: 'source-v3', expectedVerificationVersion: 2 }] }) }))
expect(wrapper.text()).toContain('原安排尚未改变'); expect(api.resolveReceivingChange).not.toHaveBeenCalled(); expect(api.bookReceiving).not.toHaveBeenCalled()
expect(wrapper.emitted('updated')).toHaveLength(1); wrapper.unmount()
})
it('rejects unchanged, fractional or excessive retained quantities without creating empty later batches', async () => {
const wrapper = render(); await prepareAdjustment(wrapper, 70)
await wrapper.get('form').trigger('submit'); await flushPromises(); expect(wrapper.text()).toContain('本次先送量未改变')
for (const quantity of [71, -1, 0.5]) { await wrapper.get('[aria-label="本次先送箱数"]').setValue(quantity); await wrapper.get('form').trigger('submit'); await flushPromises() }
expect(api.proposeReceivingChange).not.toHaveBeenCalled(); wrapper.unmount()
})
it('locks unknown outcomes and retries the identical change command without applying or recreating cargo', async () => {
vi.mocked(api.proposeReceivingChange).mockRejectedValueOnce(new Error('network timeout'))
const wrapper = render(); await prepareAdjustment(wrapper, 30); await wrapper.get('form').trigger('submit'); await flushPromises()
const first = vi.mocked(api.proposeReceivingChange).mock.calls[0]![0]
expect(await guard()).toBe(false); expect(wrapper.get('fieldset').attributes('disabled')).toBeDefined()
await wrapper.get('form').trigger('submit'); await flushPromises()
expect(api.proposeReceivingChange).toHaveBeenNthCalledWith(2, first); expect(api.resolveReceivingChange).not.toHaveBeenCalled(); wrapper.unmount()
})
it('resumes persisted waiting input, requires warehouse evidence and sends the current change and transport versions', async () => {
const c = context(); c.pendingChanges = [pendingChange()]; c.transport.version = 'transport-v2'; c.allowedActions = []
vi.mocked(api.getReceivingContext).mockResolvedValue(c)
const wrapper = render(); await flushPromises(); await button(wrapper, '继续本次变化').trigger('click'); await flushPromises()
expect(wrapper.text()).toContain('本次先送 0 箱'); expect(wrapper.text()).toContain('EXT-OLD')
await wrapper.get('[aria-label="确认当前范围"]').setValue(true); await wrapper.get('form').trigger('submit'); await flushPromises()
expect(api.resolveReceivingChange).not.toHaveBeenCalled()
await wrapper.get('[aria-label="仓库回复依据"]').setValue('仓库同意该客户全部后送,其他客户确认保留')
await wrapper.get('form').trigger('submit'); await flushPromises()
expect(api.resolveReceivingChange).toHaveBeenCalledWith('CHANGE-1', expect.objectContaining({ decision: 'CONFIRM', version: 1, transportVersion: 'transport-v2' }))
expect(api.proposeReceivingChange).not.toHaveBeenCalled(); wrapper.unmount()
})
it('withdraws only the persisted change without claiming a cancellation or requiring confirmation evidence', async () => {
const c = context(); c.pendingChanges = [pendingChange()]; vi.mocked(api.getReceivingContext).mockResolvedValue(c)
vi.mocked(api.resolveReceivingChange).mockResolvedValue(result('WITHDRAWN'))
const wrapper = render(); await flushPromises(); await button(wrapper, '继续本次变化').trigger('click'); await wrapper.get('[aria-label="确认当前范围"]').setValue(true)
await button(wrapper, '撤回变化并保留原安排').trigger('click'); await flushPromises()
expect(api.resolveReceivingChange).toHaveBeenCalledWith('CHANGE-1', expect.objectContaining({ decision: 'WITHDRAW', warehouseEvidence: null }))
expect(wrapper.text()).toContain('已撤回变化,原安排保留'); wrapper.unmount()
})
it('rebooks only eligible cancelled-group members and submits one shared booking with a new command identity', async () => {
const c = context(); c.agreements = [agreement('CANCELLED')]; vi.mocked(api.getReceivingContext).mockResolvedValue(c)
vi.mocked(api.getReceivingGroup).mockResolvedValue({ agreement: c.agreements[0]!, eligibleMembers: [members()[0]!], excludedMembers: [{ member: members()[1]!, reason: '已另行预约', currentAgreementKey: 'GROUP-OTHER' }], transport: c.transport, executionScope: c.executionScope })
const wrapper = render(); await flushPromises(); await button(wrapper, '重新预约这组货物').trigger('click'); await flushPromises()
expect(wrapper.text()).toContain('已另行预约'); expect(wrapper.text()).not.toContain('GROUP-OTHER')
Object.assign(wrapper.getComponent({ name: 'FbaAppointmentFields' }).props('model'), { confirmationNo: 'EXT-NEW', appointmentAt: '2026-10-23T11:00:00' })
await wrapper.get('[aria-label="预约覆盖依据"]').setValue('仓库确认当前剩余客户货量'); await wrapper.get('[aria-label="确认当前范围"]').setValue(true)
await wrapper.get('form').trigger('submit'); await flushPromises()
const request = vi.mocked(api.bookReceiving).mock.calls[0]![0]
expect(request.cancelledAgreementKey).toBe('GROUP-1'); expect(request.cancelledAgreementVersion).toBe(4)
expect(request.bookings).toHaveLength(1); expect(request.bookings[0]!.members).toEqual([{ batchKey: 'FBA_APPOINTMENT:1', batchVersion: 3, customerId: 'customer-a' }])
expect(request.bookings[0]!.details.confirmationNo).toBe('EXT-NEW'); wrapper.unmount()
})
it('preserves per-customer booking input on an old-number conflict and requires renewed scope confirmation', async () => {
vi.mocked(api.bookReceiving).mockRejectedValueOnce(new ApiResponseError('当前目的仓约号已使用', 'A0409', 409))
const wrapper = render(); await flushPromises(); await button(wrapper, '登记当前未覆盖货物的正式预约').trigger('click'); await flushPromises()
const model = wrapper.getComponent({ name: 'FbaAppointmentFields' }).props('model')
Object.assign(model, { confirmationNo: 'EXT-IN-USE', appointmentAt: '2026-10-23T11:00:00' })
await wrapper.get('[aria-label="预约覆盖依据"]').setValue('明确覆盖'); await wrapper.get('[aria-label="确认当前范围"]').setValue(true)
await wrapper.get('form').trigger('submit'); await flushPromises()
expect(model.confirmationNo).toBe('EXT-IN-USE'); expect(wrapper.text()).toContain('当前目的仓约号已使用')
expect(button(wrapper, '保存本次正式预约').attributes('disabled')).toBeDefined(); expect(wrapper.emitted('updated')).toBeUndefined()
wrapper.unmount()
})
it('requires explicit whole-scope cancellation confirmation and uses the group version and delete permission', async () => {
const c = context(); c.agreements = [agreement()]; vi.mocked(api.getReceivingContext).mockResolvedValue(c)
access.denied = ['platform:overseas-warehouse:inbound-order:fba-appointment']
const wrapper = render(); await flushPromises(); await button(wrapper, '核对整份取消范围').trigger('click'); await flushPromises()
await wrapper.get('[aria-label="整份回复依据"]').setValue('仓库确认整份取消'); await wrapper.get('[aria-label="确认当前范围"]').setValue(true)
await wrapper.get('form').trigger('submit'); await flushPromises()
expect(ElMessageBox.confirm).toHaveBeenCalled()
expect(api.changeReceivingGroup).toHaveBeenCalledWith('GROUP-1', expect.objectContaining({ action: 'CANCEL', version: 4, details: null, transportVersion: 'transport-v1' })); wrapper.unmount()
})
it('keeps a successful result when refresh fails and retries only reads', async () => {
const wrapper = render(); await prepareAdjustment(wrapper)
vi.mocked(api.getReceivingContext).mockRejectedValueOnce(new Error('读取暂不可用'))
await wrapper.get('form').trigger('submit'); await flushPromises()
expect(wrapper.text()).toContain('原安排尚未改变'); expect(wrapper.find('form').exists()).toBe(false)
await wrapper.get('[role="alert"] button').trigger('click'); await flushPromises()
expect(api.proposeReceivingChange).toHaveBeenCalledTimes(1); wrapper.unmount()
})
it('does not expose internal customer IDs or replace unknown cargo with zero or permit read-only writes', async () => {
const c = context(); c.batch.items[0]!.packageCount = null; vi.mocked(api.getReceivingContext).mockResolvedValue(c)
const wrapper = render(); await flushPromises()
expect(wrapper.text()).not.toContain('customer-a'); expect(wrapper.text()).toContain('箱数待核实')
await button(wrapper, '登记当前未覆盖货物的正式预约').trigger('click'); await flushPromises()
expect(wrapper.text()).toContain('货物数量或来源资料待核实'); expect(wrapper.find('[data-booking-fields]').exists()).toBe(false)
expect(button(wrapper, '保存本次正式预约').attributes('disabled')).toBeDefined()
await wrapper.setProps({ canWrite: false }); await wrapper.get('form').trigger('submit'); expect(api.bookReceiving).not.toHaveBeenCalled(); wrapper.unmount()
})
it('sends independent confirmations as distinct bookings while preserving original batch identities', async () => {
const wrapper = render(); await flushPromises(); await button(wrapper, '登记当前未覆盖货物的正式预约').trigger('click'); await flushPromises()
await wrapper.findAll('label').find(label => label.text().includes('所选客户分别登记预约'))!.get('input').setValue(true)
await flushPromises()
wrapper.findAllComponents({ name: 'FbaAppointmentFields' }).forEach((fields, index) => Object.assign(fields.props('model'), { confirmationNo: `EXT-${index}`, appointmentAt: `2026-10-${22 + index}T10:00:00` }))
for (const textarea of wrapper.findAll('[aria-label="预约覆盖依据"]')) await textarea.setValue('本客户仓库明确确认')
await wrapper.get('[aria-label="确认当前范围"]').setValue(true); await wrapper.get('form').trigger('submit'); await flushPromises()
const request = vi.mocked(api.bookReceiving).mock.calls[0]![0]
expect(request.bookings.map(row => row.members)).toEqual(members().map(({ batchKey, batchVersion, customerId }) => [{ batchKey, batchVersion, customerId }]))
expect(request.bookings.map(row => row.details.confirmationNo)).toEqual(['EXT-0', 'EXT-1'])
expect(request.cancelledAgreementKey).toBeNull(); wrapper.unmount()
})
it('does not apply existing booking inputs to different members after a range conflict', async () => {
const original = context(); original.agreements = [agreement('CANCELLED')]
vi.mocked(api.getReceivingContext).mockResolvedValue(original)
vi.mocked(api.getReceivingGroup).mockResolvedValueOnce({ agreement: original.agreements[0]!, eligibleMembers: members(), excludedMembers: [], transport: original.transport, executionScope: original.executionScope }).mockResolvedValue({ agreement: original.agreements[0]!, eligibleMembers: [members()[1]!], excludedMembers: [{ member: members()[0]!, reason: '已另行预约', currentAgreementKey: 'OTHER' }], transport: original.transport, executionScope: original.executionScope })
vi.mocked(api.bookReceiving).mockRejectedValueOnce(new ApiResponseError('范围版本变化', 'A0409', 409))
const wrapper = render(); await flushPromises(); await button(wrapper, '重新预约这组货物').trigger('click'); await flushPromises()
Object.assign(wrapper.getComponent({ name: 'FbaAppointmentFields' }).props('model'), { confirmationNo: 'OLD-DRAFT', appointmentAt: '2026-10-22T10:00:00' })
await wrapper.get('[aria-label="预约覆盖依据"]').setValue('原范围依据'); await wrapper.get('[aria-label="确认当前范围"]').setValue(true)
await wrapper.get('form').trigger('submit'); await flushPromises()
expect(wrapper.text()).toContain('原输入不会自动套用给其他客户')
expect(wrapper.find('[data-booking-fields]').exists()).toBe(false)
expect(button(wrapper, '保存本次正式预约').attributes('disabled')).toBeDefined()
expect(api.bookReceiving).toHaveBeenCalledTimes(1); wrapper.unmount()
})
it('treats unchanged whole-group rescheduling as unchanged rather than a new successful mutation', async () => {
const c = context(); c.agreements = [agreement()]; vi.mocked(api.getReceivingContext).mockResolvedValue(c)
vi.mocked(api.changeReceivingGroup).mockResolvedValue({ ...result('UNCHANGED'), steps: [] })
const wrapper = render(); await flushPromises(); await button(wrapper, '核对整份改期范围').trigger('click'); await flushPromises()
expect(wrapper.getComponent({ name: 'FbaAppointmentFields' }).props('model').confirmationNo).toBe('EXT-OLD')
await wrapper.get('[aria-label="整份回复依据"]').setValue('核对无变化'); await wrapper.get('[aria-label="确认当前范围"]').setValue(true)
await wrapper.get('form').trigger('submit'); await flushPromises()
expect(api.changeReceivingGroup).toHaveBeenCalledWith('GROUP-1', expect.objectContaining({ action: 'RESCHEDULE', details: detail() }))
expect(wrapper.text()).toContain('安排没有变化'); expect(wrapper.text()).not.toContain('已保存真实预约'); wrapper.unmount()
})
it('uses only the eligible B/D cross-batch transport scope after A booked separately', async () => {
const a = { ...members()[0]!, batchKey: 'FBA_APPOINTMENT:10', appointmentNo: 'AP-A' }
const b = { ...members()[1]!, batchKey: 'FBA_APPOINTMENT:20', appointmentNo: 'AP-B' }
const d = { ...members()[1]!, batchKey: 'FBA_APPOINTMENT:30', appointmentNo: 'AP-D', customerId: 'customer-d' }
const cancelled = { ...agreement('CANCELLED'), members: [a, b, d] }
const c = context(); c.agreements = [cancelled]; c.transport.version = 'old-A-B-D'
vi.mocked(api.getReceivingContext).mockResolvedValue(c)
vi.mocked(api.getReceivingGroup).mockResolvedValue({ agreement: cancelled, eligibleMembers: [b, d], excludedMembers: [{ member: a, reason: '已另行预约', currentAgreementKey: 'OTHER-A' }], transport: { version: 'current-B-D', vehicles: [], blockReasons: ['无关客户已完成运输'] }, executionScope: { version: 'execution-B-D', members: [b, d].map(member => ({ member, completed: false, canRebook: true, reason: null })) } })
const wrapper = render(); await flushPromises(); await button(wrapper, '重新预约这组货物').trigger('click'); await flushPromises()
Object.assign(wrapper.getComponent({ name: 'FbaAppointmentFields' }).props('model'), { confirmationNo: 'NEW-B-D', appointmentAt: '2026-10-22T10:00:00' })
await wrapper.get('[aria-label="预约覆盖依据"]').setValue('仅覆盖B/D'); await wrapper.get('[aria-label="确认当前范围"]').setValue(true)
await wrapper.get('form').trigger('submit'); await flushPromises()
const request = vi.mocked(api.bookReceiving).mock.calls[0]![0]
expect(api.getReceivingExecutionScope).toHaveBeenCalledWith([{ batchKey: b.batchKey, customerId: b.customerId }, { batchKey: d.batchKey, customerId: d.customerId }]); expect(request.executionVersion).toBe('execution-v1'); expect(request).not.toHaveProperty('transportVersion')
expect(request.bookings[0]!.members.map(member => member.batchKey)).toEqual(['FBA_APPOINTMENT:20', 'FBA_APPOINTMENT:30'])
expect(request.bookings[0]!.members.some(member => member.customerId === a.customerId)).toBe(false); wrapper.unmount()
})
it('uses verified owner candidates and renders authoritative pending followup names instead of account IDs', async () => {
const c = context(); c.pendingChanges = [pendingChange()]
vi.mocked(api.getReceivingContext).mockResolvedValue(c)
const wrapper = render(); await flushPromises()
expect(wrapper.text()).toContain('负责人 已核实负责人'); expect(wrapper.text()).not.toContain('owner-related')
await button(wrapper, '调整本客户先送 / 后送').trigger('click'); await flushPromises()
const owner = wrapper.get('[aria-label="调整负责人"]')
expect(owner.element.tagName).toBe('SELECT')
expect(owner.findAll('option').map(option => option.text())).toEqual(['请选择负责人', '关联负责人', '当前本人'])
await wrapper.get('[aria-label="本次先送箱数"]').setValue(0)
await owner.setValue('not-an-account'); await wrapper.get('[aria-label="调整原因"]').setValue('后送')
await wrapper.get('[aria-label="确认当前范围"]').setValue(true); await wrapper.get('form').trigger('submit'); await flushPromises()
expect(api.proposeReceivingChange).not.toHaveBeenCalled(); expect(wrapper.text()).toContain('请选择有效负责人')
await owner.setValue('owner-current'); await wrapper.get('form').trigger('submit'); await flushPromises()
expect(api.proposeReceivingChange).toHaveBeenCalledWith(expect.objectContaining({ intent: expect.objectContaining({ ownerId: 'owner-current' }) }))
expect(vi.mocked(api.proposeReceivingChange).mock.calls[0]![0].intent).not.toHaveProperty('owner')
wrapper.unmount()
})
it('books unfinished B using execution eligibility even when completed A blocks the shared transport and lacks cargo details', async () => {
const c = context()
c.executionScope.members[0] = { member: c.executionScope.members[0]!.member, completed: true, canRebook: false, reason: '本客户已完成,不再重约' }
c.batch.items[0]!.packageCount = null
c.transport.blockReasons = ['已完成客户禁止调整车辆']
vi.mocked(api.getReceivingContext).mockResolvedValue(c)
const wrapper = render(); await flushPromises(); await button(wrapper, '登记当前未覆盖货物的正式预约').trigger('click'); await flushPromises()
expect(wrapper.text()).toContain('本客户已完成,不再重约'); expect(wrapper.text()).not.toContain('货物数量或来源资料待核实')
Object.assign(wrapper.getComponent({ name: 'FbaAppointmentFields' }).props('model'), { confirmationNo: 'ONLY-B', appointmentAt: '2026-10-23T11:00:00' })
await wrapper.get('[aria-label="预约覆盖依据"]').setValue('仅当前未完成客户'); await wrapper.get('[aria-label="确认当前范围"]').setValue(true)
await wrapper.get('form').trigger('submit'); await flushPromises()
const command = vi.mocked(api.bookReceiving).mock.calls[0]![0]
expect(command.executionVersion).toBe('execution-v1'); expect(command).not.toHaveProperty('transportVersion')
expect(command.bookings[0]!.members.map(member => member.customerId)).toEqual(['customer-b'])
wrapper.unmount()
})
it('does not offer members missing execution eligibility or marked completed even if canRebook is true', async () => {
const c = context(); c.executionScope.members = [{ ...c.executionScope.members[0]!, completed: true, canRebook: true }]
vi.mocked(api.getReceivingContext).mockResolvedValue(c)
const wrapper = render(); await flushPromises(); await button(wrapper, '登记当前未覆盖货物的正式预约').trigger('click'); await flushPromises()
expect(wrapper.find('[data-booking-fields]').exists()).toBe(false)
await wrapper.get('[aria-label="确认当前范围"]').setValue(true); await wrapper.get('form').trigger('submit'); await flushPromises()
expect(api.bookReceiving).not.toHaveBeenCalled(); expect(button(wrapper, '保存本次正式预约').attributes('disabled')).toBeDefined()
wrapper.unmount()
})
function mixedPlans(): api.ReceivingContext {
const c = context()
c.batch.plannedDate = '2026-10-20'; c.batch.confirmationNo = 'A-CONFIRMED'; c.batch.appointmentStatus = 'SUCCESS'
c.agreements = [{ ...agreement(), members: [members()[0]!] }]
c.batch.items.push({ ...c.batch.items[1]!, id: 'item-d', customerId: 'customer-d', sourceKey: 'ORDER:D', inboundCode: 'IN-D' })
c.executionScope.members.push({ member: { batchKey: c.batch.batchKey!, customerId: 'customer-d' }, completed: false, canRebook: true, reason: null })
c.plans = [{ batchKey: c.batch.batchKey!, customerId: 'customer-b', timezone: 'America/Los_Angeles', details: appointmentPayload({ ...createAppointmentForm(), plannedDate: '2026-10-24', appointmentRemark: '等待仓库' }) }]
return c
}
async function enterBPlan(wrapper: ReturnType<typeof render>) {
await flushPromises()
const buttons = wrapper.findAll('button').filter(row => row.text() === '保存目标 / 未约成')
expect(buttons[0]!.attributes('disabled')).toBeDefined()
await buttons[1]!.trigger('click'); await flushPromises()
}
it('saves only B pending plan in the same stable batch where A is independently confirmed and D is still unbooked', async () => {
const c = mixedPlans(); vi.mocked(api.getReceivingContext).mockResolvedValue(c)
const wrapper = render(); await enterBPlan(wrapper)
expect((wrapper.get('[aria-label="客户计划日期"]').element as HTMLInputElement).value).toBe('2026-10-24')
expect(wrapper.findAll('[aria-label="客户计划状态"] option').map(row => row.attributes('value'))).toEqual(['PENDING', 'FAILED'])
await wrapper.get('[aria-label="客户计划日期"]').setValue('2026-10-26'); await wrapper.get('[aria-label="客户计划备注"]').setValue('乙等待回复')
await wrapper.get('[aria-label="确认当前范围"]').setValue(true); await wrapper.get('form').trigger('submit'); await flushPromises()
expect(api.saveReceivingPlan).toHaveBeenCalledWith(expect.objectContaining({ member: { batchKey: c.batch.batchKey, batchVersion: 3, customerId: 'customer-b' }, executionVersion: 'execution-v1', details: expect.objectContaining({ appointmentStatus: 'PENDING', plannedDate: '2026-10-26', appointmentRemark: '乙等待回复', confirmationNo: null, appointmentAt: null, appointmentEndAt: null }) }))
expect(api.bookReceiving).not.toHaveBeenCalled(); expect(api.proposeReceivingChange).not.toHaveBeenCalled(); expect(api.changeReceivingGroup).not.toHaveBeenCalled()
expect(c.agreements[0]!.details.confirmationNo).toBe('EXT-OLD'); expect(wrapper.emitted('updated')).toHaveLength(1)
wrapper.unmount()
})
it('requires a failed-plan reason and allows an explicitly cleared date without inheriting A or the old header date', async () => {
const c = mixedPlans(); c.plans[0]!.details.plannedDate = null; vi.mocked(api.getReceivingContext).mockResolvedValue(c)
const wrapper = render(); await enterBPlan(wrapper)
expect((wrapper.get('[aria-label="客户计划日期"]').element as HTMLInputElement).value).toBe('')
await wrapper.get('[aria-label="客户计划状态"]').setValue('FAILED'); await wrapper.get('[aria-label="客户计划备注"]').setValue('')
await wrapper.get('[aria-label="确认当前范围"]').setValue(true); await wrapper.get('form').trigger('submit'); await flushPromises()
expect(api.saveReceivingPlan).not.toHaveBeenCalled(); expect(wrapper.text()).toContain('请填写未约成的原因')
await wrapper.get('[aria-label="客户计划备注"]').setValue('仓库暂未提供时段'); await wrapper.get('form').trigger('submit'); await flushPromises()
expect(api.saveReceivingPlan).toHaveBeenCalledWith(expect.objectContaining({ details: expect.objectContaining({ plannedDate: null, plannedAt: null, plannedEndAt: null, appointmentStatus: 'FAILED', appointmentRemark: '仓库暂未提供时段', confirmationNo: null, appointmentAt: null, appointmentEndAt: null }) }))
wrapper.unmount()
})
it('keeps customer plan drafts after a version conflict and resubmits explicitly with current batch and execution versions', async () => {
const c = mixedPlans(); vi.mocked(api.getReceivingContext).mockResolvedValue(c)
vi.mocked(api.saveReceivingPlan).mockRejectedValueOnce(new ApiResponseError('批次版本变化', 'A0409', 409))
const wrapper = render(); await enterBPlan(wrapper)
await wrapper.get('[aria-label="客户计划日期"]').setValue('2026-10-28'); await wrapper.get('[aria-label="客户计划备注"]').setValue('保留乙的输入')
const fresh = structuredClone(c); fresh.batch.version = 4; fresh.executionScope.version = 'execution-v2'; fresh.plans[0]!.details.plannedDate = '2026-10-25'
vi.mocked(api.getReceivingContext).mockResolvedValue(fresh)
await wrapper.get('[aria-label="确认当前范围"]').setValue(true); await wrapper.get('form').trigger('submit'); await flushPromises()
const first = vi.mocked(api.saveReceivingPlan).mock.calls[0]![0]
expect((wrapper.get('[aria-label="客户计划日期"]').element as HTMLInputElement).value).toBe('2026-10-28')
expect(button(wrapper, '保存本客户计划').attributes('disabled')).toBeDefined()
await wrapper.get('[aria-label="确认当前范围"]').setValue(true); await wrapper.get('form').trigger('submit'); await flushPromises()
const second = vi.mocked(api.saveReceivingPlan).mock.calls[1]![0]
expect(second.details).toEqual(first.details); expect(second.member.batchVersion).toBe(4); expect(second.executionVersion).toBe('execution-v2'); expect(second.idempotencyKey).not.toBe(first.idempotencyKey)
wrapper.unmount()
})
it('retries the identical unknown customer plan and shows unchanged without creating a confirmation', async () => {
vi.mocked(api.getReceivingContext).mockResolvedValue(mixedPlans())
vi.mocked(api.saveReceivingPlan).mockRejectedValueOnce(new Error('timeout')).mockResolvedValueOnce({ ...result('UNCHANGED'), steps: [], nextActions: [] })
const wrapper = render(); await enterBPlan(wrapper)
await wrapper.get('[aria-label="确认当前范围"]').setValue(true); await wrapper.get('form').trigger('submit'); await flushPromises()
const first = vi.mocked(api.saveReceivingPlan).mock.calls[0]![0]
expect(await guard()).toBe(false); expect(wrapper.get('fieldset').attributes('disabled')).toBeDefined()
await wrapper.get('form').trigger('submit'); await flushPromises()
expect(api.saveReceivingPlan).toHaveBeenNthCalledWith(2, first); expect(wrapper.text()).toContain('安排没有变化'); expect(api.bookReceiving).not.toHaveBeenCalled()
wrapper.unmount()
})
it('blocks plans for confirmed, waiting-change, completed and unauthorized customers', async () => {
const c = mixedPlans(); c.pendingChanges = [{ ...pendingChange(), intent: { ...pendingChange().intent, customerId: 'customer-b' } }]
c.executionScope.members.find(row => row.member.customerId === 'customer-d')!.completed = true
vi.mocked(api.getReceivingContext).mockResolvedValue(c)
const wrapper = render(); await flushPromises()
expect(wrapper.findAll('button').filter(row => row.text() === '保存目标 / 未约成').every(row => row.attributes('disabled') !== undefined)).toBe(true)
wrapper.unmount()
vi.mocked(api.getReceivingContext).mockResolvedValue(mixedPlans())
const readonly = render(); await enterBPlan(readonly); await readonly.setProps({ canWrite: false })
await readonly.get('[aria-label="确认当前范围"]').setValue(true); await readonly.get('form').trigger('submit'); await flushPromises()
expect(api.saveReceivingPlan).not.toHaveBeenCalled(); readonly.unmount()
})
it('starts D plan empty without copying confirmed A or another customer plan and clears an existing B date explicitly', async () => {
const c = mixedPlans(); vi.mocked(api.getReceivingContext).mockResolvedValue(c)
const wrapper = render(); await flushPromises()
await wrapper.findAll('button').filter(row => row.text() === '保存目标 / 未约成')[2]!.trigger('click'); await flushPromises()
expect((wrapper.get('[aria-label="客户计划日期"]').element as HTMLInputElement).value).toBe('')
await button(wrapper, '返回范围概览').trigger('click'); await flushPromises(); await enterBPlan(wrapper)
await wrapper.get('[aria-label="客户计划日期"]').setValue('')
await wrapper.get('[aria-label="确认当前范围"]').setValue(true); await wrapper.get('form').trigger('submit'); await flushPromises()
expect(api.saveReceivingPlan).toHaveBeenCalledWith(expect.objectContaining({ member: expect.objectContaining({ customerId: 'customer-b' }), details: expect.objectContaining({ plannedDate: null }) }))
wrapper.unmount()
})
it('preserves cross-day planned windows and explicit DST offsets in the customer plan without confirmation fields', async () => {
vi.mocked(api.getReceivingContext).mockResolvedValue(mixedPlans())
const wrapper = render(); await enterBPlan(wrapper)
await wrapper.get('[aria-label="客户计划日期"]').setValue('2026-10-31')
await wrapper.get('[aria-label="客户计划开始"]').setValue('2026-10-31T23:30:00')
await wrapper.get('[aria-label="客户计划结束"]').setValue('2026-11-01T01:30:00')
await wrapper.get('[aria-label="客户计划开始时差"]').setValue('-07:00')
await wrapper.get('[aria-label="客户计划结束时差"]').setValue('-08:00')
await wrapper.get('[aria-label="确认当前范围"]').setValue(true); await wrapper.get('form').trigger('submit'); await flushPromises()
expect(api.saveReceivingPlan).toHaveBeenCalledWith(expect.objectContaining({ details: expect.objectContaining({ plannedDate: '2026-10-31', plannedAt: expect.stringContaining('2026-10-31T23:30'), plannedEndAt: expect.stringContaining('2026-11-01T01:30'), startOffset: '-07:00', endOffset: '-08:00', appointmentAt: null, appointmentEndAt: null }) }))
wrapper.unmount()
})
it('blocks dated plans without authoritative timezone but permits undated failure notes without a browser timezone', async () => {
const c = mixedPlans(); c.plans[0]!.timezone = null
vi.mocked(api.getReceivingContext).mockResolvedValue(c)
const wrapper = render(); await enterBPlan(wrapper)
await wrapper.get('[aria-label="确认当前范围"]').setValue(true); await wrapper.get('form').trigger('submit'); await flushPromises()
expect(api.saveReceivingPlan).not.toHaveBeenCalled(); expect(wrapper.text()).toContain('目的仓时区待核实,请先补齐')
await wrapper.get('[aria-label="客户计划日期"]').setValue(''); await wrapper.get('[aria-label="客户计划状态"]').setValue('FAILED')
await wrapper.get('[aria-label="客户计划备注"]').setValue('待核实仓库地点')
await wrapper.get('form').trigger('submit'); await flushPromises()
expect(api.saveReceivingPlan).toHaveBeenCalledWith(expect.objectContaining({ details: expect.objectContaining({ plannedDate: null, appointmentStatus: 'FAILED', startOffset: null, endOffset: null }) }))
wrapper.unmount()
})
it('preserves a DST-rejected plan for correction and never copies it into a formal booking', async () => {
vi.mocked(api.getReceivingContext).mockResolvedValue(mixedPlans())
vi.mocked(api.saveReceivingPlan).mockRejectedValueOnce(new ApiResponseError('当地时刻存在歧义,请明确时差', 'A0400', 400))
const wrapper = render(); await enterBPlan(wrapper)
await wrapper.get('[aria-label="客户计划日期"]').setValue('2026-11-01'); await wrapper.get('[aria-label="客户计划开始"]').setValue('2026-11-01T01:30:00')
await wrapper.get('[aria-label="确认当前范围"]').setValue(true); await wrapper.get('form').trigger('submit'); await flushPromises()
expect(wrapper.text()).toContain('当地时刻存在歧义')
expect((wrapper.get('[aria-label="客户计划开始"]').element as HTMLInputElement).value).toContain('2026-11-01T01:30')
expect(button(wrapper, '保存本客户计划').attributes('disabled')).toBeDefined()
await wrapper.get('[aria-label="客户计划开始时差"]').setValue('-08:00'); await wrapper.get('[aria-label="确认当前范围"]').setValue(true)
await wrapper.get('form').trigger('submit'); await flushPromises()
expect(api.saveReceivingPlan).toHaveBeenCalledTimes(2); expect(api.bookReceiving).not.toHaveBeenCalled()
wrapper.unmount()
})
it('inherits unconfirmed legacy header plans only without active independent coverage and strips stale confirmation fields', async () => {
for (const status of ['PENDING', 'FAILED'] as const) {
const c = context(); Object.assign(c.batch, { timezone: 'America/Los_Angeles', plannedDate: '2026-10-27', plannedAt: '2026-10-27T10:00:00', appointmentStatus: status, appointmentRemark: '原联系原因', confirmationNo: 'STALE', appointmentAt: '2026-10-20T09:00:00' })
vi.mocked(api.getReceivingContext).mockResolvedValue(c)
const wrapper = render(); await flushPromises(); await button(wrapper, '保存目标 / 未约成').trigger('click'); await flushPromises()
expect((wrapper.get('[aria-label="客户计划日期"]').element as HTMLInputElement).value).toBe('2026-10-27')
expect((wrapper.get('[aria-label="客户计划备注"]').element as HTMLTextAreaElement).value).toBe('原联系原因')
await wrapper.get('[aria-label="确认当前范围"]').setValue(true); await wrapper.get('form').trigger('submit'); await flushPromises()
expect(api.saveReceivingPlan).toHaveBeenLastCalledWith(expect.objectContaining({ details: expect.objectContaining({ appointmentStatus: status, plannedDate: '2026-10-27', confirmationNo: null, appointmentAt: null, appointmentEndAt: null, startOffset: null, endOffset: null }) }))
wrapper.unmount()
}
})
it('never inherits cancelled targets and keeps an explicit empty customer plan ahead of a pending header', async () => {
for (const ownPlan of [false, true]) {
const c = context(); Object.assign(c.batch, { appointmentStatus: ownPlan ? 'PENDING' : 'CANCELLED', plannedDate: '2026-10-27', appointmentRemark: '旧批原因' })
if (ownPlan) c.plans = [{ batchKey: c.batch.batchKey!, customerId: 'customer-a', timezone: c.batch.timezone || null, details: appointmentPayload(createAppointmentForm()) }]
vi.mocked(api.getReceivingContext).mockResolvedValue(c)
const wrapper = render(); await flushPromises(); await button(wrapper, '保存目标 / 未约成').trigger('click'); await flushPromises()
expect((wrapper.get('[aria-label="客户计划日期"]').element as HTMLInputElement).value).toBe('')
expect((wrapper.get('[aria-label="客户计划备注"]').element as HTMLTextAreaElement).value).toBe('')
wrapper.unmount()
}
})
it('selects only A for independent rebooking from a cancelled group sharing one stable batch with B and D', async () => {
const c = mixedPlans(); c.agreements = [{ ...agreement('CANCELLED'), members: [...members(), { ...members()[1]!, customerId: 'customer-d', customerName: '丁' }] }]
vi.mocked(api.getReceivingContext).mockResolvedValue(c)
vi.mocked(api.getReceivingGroup).mockResolvedValue({ agreement: c.agreements[0]!, eligibleMembers: c.agreements[0]!.members, excludedMembers: [], transport: c.transport, executionScope: c.executionScope })
const wrapper = render(); await flushPromises(); await button(wrapper, '重新预约这组货物').trigger('click'); await flushPromises()
await wrapper.get('[aria-label="选择预约客户 2"]').setValue(false); await wrapper.get('[aria-label="选择预约客户 3"]').setValue(false)
Object.assign(wrapper.getComponent({ name: 'FbaAppointmentFields' }).props('model'), { confirmationNo: 'A-ONLY', appointmentAt: '2026-10-24T10:00:00' })
await wrapper.get('[aria-label="预约覆盖依据"]').setValue('仅甲取得确认'); await wrapper.get('[aria-label="确认当前范围"]').setValue(true)
await wrapper.get('form').trigger('submit'); await flushPromises()
const request = vi.mocked(api.bookReceiving).mock.calls[0]![0]
expect(request.bookings).toHaveLength(1); expect(request.bookings[0]!.members).toEqual([{ batchKey: c.batch.batchKey!, batchVersion: 3, customerId: 'customer-a' }])
expect(request.executionVersion).toBe(c.executionScope.version); expect(request.cancelledAgreementKey).toBe('GROUP-1')
wrapper.unmount()
})
it('keeps independent booking fields matched to the selected customer and blocks an empty selection', async () => {
const wrapper = render(); await flushPromises(); await button(wrapper, '登记当前未覆盖货物的正式预约').trigger('click'); await flushPromises()
await wrapper.findAll('label').find(label => label.text().includes('所选客户分别登记预约'))!.get('input').setValue(true)
wrapper.findAllComponents({ name: 'FbaAppointmentFields' }).forEach((fields, index) => Object.assign(fields.props('model'), { confirmationNo: `FOR-${index}`, appointmentAt: '2026-10-24T10:00:00' }))
await wrapper.get('[aria-label="选择预约客户 1"]').setValue(false)
expect(wrapper.getComponent({ name: 'FbaAppointmentFields' }).props('model').confirmationNo).toBe('FOR-1')
await wrapper.get('[aria-label="选择预约客户 2"]').setValue(false)
expect(wrapper.get('[aria-label="确认当前范围"]').attributes('disabled')).toBeDefined(); await wrapper.get('form').trigger('submit'); await flushPromises()
expect(api.bookReceiving).not.toHaveBeenCalled()
await wrapper.get('[aria-label="选择预约客户 2"]').setValue(true); await flushPromises(); await wrapper.get('[aria-label="确认当前范围"]').setValue(true); await wrapper.get('[aria-label="预约覆盖依据"]').setValue('仅乙确认')
await wrapper.get('form').trigger('submit'); await flushPromises()
expect(vi.mocked(api.bookReceiving).mock.calls[0]![0].bookings[0]).toEqual(expect.objectContaining({ members: [expect.objectContaining({ customerId: 'customer-b' })], details: expect.objectContaining({ confirmationNo: 'FOR-1' }) }))
wrapper.unmount()
})
it('reads an exact cross-batch subset execution token without changing the visible batch or cancelled-group versions', async () => {
const c = context(); const a = members()[0]!, b = { ...members()[1]!, batchKey: 'FBA_APPOINTMENT:2', batchVersion: 7, appointmentNo: 'AP-B' }
c.agreements = [{ ...agreement('CANCELLED'), members: [a, b] }]
vi.mocked(api.getReceivingContext).mockResolvedValue(c)
vi.mocked(api.getReceivingGroup).mockResolvedValue({ agreement: c.agreements[0]!, eligibleMembers: [a, b], excludedMembers: [], transport: c.transport, executionScope: { ...c.executionScope, version: 'whole-A-B' } })
vi.mocked(api.getReceivingExecutionScope).mockImplementation(async selected => ({ version: selected.length === 1 ? 'only-B-current' : 'whole-A-B-current', members: selected.map(member => ({ member, completed: false, canRebook: true, reason: null })) }))
const wrapper = render(); await flushPromises(); await button(wrapper, '重新预约这组货物').trigger('click'); await flushPromises()
await wrapper.get('[aria-label="确认当前范围"]').setValue(true)
await wrapper.get('[aria-label="选择预约客户 1"]').setValue(false); await flushPromises()
expect((wrapper.get('[aria-label="确认当前范围"]').element as HTMLInputElement).checked).toBe(false)
expect(api.getReceivingExecutionScope).toHaveBeenLastCalledWith([{ batchKey: b.batchKey, customerId: b.customerId }])
Object.assign(wrapper.getComponent({ name: 'FbaAppointmentFields' }).props('model'), { confirmationNo: 'B-ONLY', appointmentAt: '2026-10-24T10:00:00' })
await wrapper.get('[aria-label="预约覆盖依据"]').setValue('仅乙当前批确认'); await wrapper.get('[aria-label="确认当前范围"]').setValue(true)
await wrapper.get('form').trigger('submit'); await flushPromises()
expect(api.bookReceiving).toHaveBeenCalledWith(expect.objectContaining({ executionVersion: 'only-B-current', cancelledAgreementVersion: 4, bookings: [expect.objectContaining({ members: [{ batchKey: b.batchKey, batchVersion: 7, customerId: b.customerId }] })] }))
wrapper.unmount()
})
it('blocks submission after a selected execution-scope read failure and retries only that read', async () => {
const wrapper = render(); await flushPromises(); await button(wrapper, '登记当前未覆盖货物的正式预约').trigger('click'); await flushPromises()
vi.mocked(api.getReceivingExecutionScope).mockRejectedValueOnce(new Error('执行资格暂不可用'))
await wrapper.get('[aria-label="选择预约客户 1"]').setValue(false); await flushPromises()
expect(wrapper.get('[aria-label="确认当前范围"]').attributes('disabled')).toBeDefined(); await wrapper.get('form').trigger('submit'); await flushPromises()
expect(api.bookReceiving).not.toHaveBeenCalled(); expect(button(wrapper, '保存本次正式预约').attributes('disabled')).toBeDefined()
await button(wrapper, '重试读取').trigger('click'); await flushPromises()
expect(api.getReceivingExecutionScope).toHaveBeenLastCalledWith([{ batchKey: 'FBA_APPOINTMENT:1', customerId: 'customer-b' }])
expect((wrapper.get('[aria-label="确认当前范围"]').element as HTMLInputElement).checked).toBe(false)
expect(api.bookReceiving).not.toHaveBeenCalled(); wrapper.unmount()
})
it('shows authoritative subset blockers and ignores a late response for a previous selection', async () => {
const wrapper = render(); await flushPromises(); await button(wrapper, '登记当前未覆盖货物的正式预约').trigger('click'); await flushPromises()
let resolveOld!: (scope: api.ReceivingExecutionScope) => void
vi.mocked(api.getReceivingExecutionScope).mockImplementationOnce(() => new Promise(resolve => { resolveOld = resolve }))
await wrapper.get('[aria-label="选择预约客户 1"]').setValue(false)
vi.mocked(api.getReceivingExecutionScope).mockImplementationOnce(async selected => ({ version: 'new-blocked', members: selected.map(member => ({ member, completed: true, canRebook: false, reason: '本客户已执行,不能重约' })) }))
await wrapper.get('[aria-label="选择预约客户 1"]').setValue(true); await flushPromises()
resolveOld({ version: 'stale-allowed', members: [{ member: { batchKey: 'FBA_APPOINTMENT:1', customerId: 'customer-b' }, completed: false, canRebook: true, reason: null }] }); await flushPromises()
expect(wrapper.text()).toContain('本客户已执行,不能重约')
await wrapper.get('[aria-label="确认当前范围"]').setValue(true); await wrapper.get('form').trigger('submit'); await flushPromises()
expect(api.bookReceiving).not.toHaveBeenCalled(); expect(button(wrapper, '保存本次正式预约').attributes('disabled')).toBeDefined(); wrapper.unmount()
})
function verifiedCargo(): CargoVerificationContext {
return { source: { sourceKey: 'BOOKING:2', customerId: 'customer-b', orderId: null, inboundCode: 'IN-B', bookingNo: null, containerNo: null, originWarehouseId: 'origin-1', originWarehouseName: '本仓', destinationKey: 'FBA:ONT8', destinationWarehouseCode: 'ONT8', packages: 40, sourceVersion: 'source-latest', canFollowup: true, blockReasons: [] }, verification: { version: 2, sourceVersion: 'source-latest', destinationKey: 'FBA:ONT8', sourcePackages: 40, packageCount: 40, shipmentReferences: ['FBA-NEW-B'], remark: null, operatorName: '核实人员', verifiedAt: '2026-10-16T10:00:00Z' }, allocatedPackages: 30, unknownAllocationCount: 0, effectivePackages: 40, availablePackages: 10, sourceChanged: false, allowedActions: ['VERIFY_CARGO'], blockReasons: [] }
}
async function enterRefresh(wrapper: ReturnType<typeof render>) {
await flushPromises(); await wrapper.findAll('button').filter(row => row.text() === '核对并采用本客户最新货物资料')[1]!.trigger('click'); await flushPromises()
}
it('explicitly adopts only B latest source and verification snapshots beside independently confirmed A without changing quantities or saving verification', async () => {
vi.mocked(api.getReceivingContext).mockResolvedValue(mixedPlans()); vi.mocked(getCargoVerification).mockResolvedValue(verifiedCargo())
const wrapper = render(); await enterRefresh(wrapper)
expect(getCargoVerification).toHaveBeenCalledExactlyOnceWith({ sourceKey: 'BOOKING:2', customerId: 'customer-b', destinationKey: 'FBA:ONT8' })
expect(wrapper.text()).toContain('本批 30 箱'); expect(wrapper.text()).toContain('最新核实 40 箱'); expect(wrapper.text()).toContain('FBA-NEW-B')
expect(api.refreshReceivingCargo).not.toHaveBeenCalled()
await wrapper.get('[aria-label="确认当前范围"]').setValue(true); await wrapper.get('form').trigger('submit'); await flushPromises()
expect(api.refreshReceivingCargo).toHaveBeenCalledWith(expect.objectContaining({ member: { batchKey: 'FBA_APPOINTMENT:1', batchVersion: 3, customerId: 'customer-b' }, executionVersion: 'execution-v1', sources: [{ sourceKey: 'BOOKING:2', destinationKey: 'FBA:ONT8', expectedSourceVersion: 'source-latest', expectedVerificationVersion: 2 }] }))
expect(saveCargoVerification).not.toHaveBeenCalled(); expect(api.proposeReceivingChange).not.toHaveBeenCalled(); expect(api.bookReceiving).not.toHaveBeenCalled()
await button(wrapper, '继续本客户目标 / 未约成').trigger('click'); await flushPromises()
expect(wrapper.find('[aria-label="客户计划日期"]').exists()).toBe(true)
wrapper.unmount()
})
it('fails closed for unknown, changed, overallocated, mismatched or unavailable latest cargo', async () => {
const cases: Array<Partial<CargoVerificationContext>> = [
{ sourceChanged: true }, { effectivePackages: null, availablePackages: null }, { unknownAllocationCount: 1 }, { allocatedPackages: 41 },
{ source: { ...verifiedCargo().source, customerId: 'customer-other' } }, { source: { ...verifiedCargo().source, destinationKey: 'FBA:OTHER' } },
{ source: { ...verifiedCargo().source, sourceVersion: null } }, { verification: { ...verifiedCargo().verification!, sourceVersion: 'stale' } }, { blockReasons: ['来源暂不可用'] },
]
for (const change of cases) {
vi.mocked(api.getReceivingContext).mockResolvedValue(mixedPlans()); vi.mocked(getCargoVerification).mockResolvedValue({ ...verifiedCargo(), ...change })
const wrapper = render(); await enterRefresh(wrapper)
expect(button(wrapper, '确认采用本客户最新资料').attributes('disabled')).toBeDefined()
await wrapper.get('form').trigger('submit'); await flushPromises(); expect(api.refreshReceivingCargo).not.toHaveBeenCalled(); wrapper.unmount()
}
vi.mocked(getCargoVerification).mockRejectedValueOnce(new Error('核实来源读取失败'))
const wrapper = render(); await enterRefresh(wrapper)
expect(button(wrapper, '确认采用本客户最新资料').attributes('disabled')).toBeDefined(); expect(wrapper.text()).toContain('最新货物核实资料读取失败'); wrapper.unmount()
})
it('refreshes rejected adoption versions for explicit reconfirmation and retries unknown adoption with the identical key', async () => {
const c = mixedPlans(); vi.mocked(api.getReceivingContext).mockResolvedValue(c); vi.mocked(getCargoVerification).mockResolvedValue(verifiedCargo())
vi.mocked(api.refreshReceivingCargo).mockRejectedValueOnce(new ApiResponseError('资料版本变化', 'A0409', 409)).mockRejectedValueOnce(new Error('timeout'))
const wrapper = render(); await enterRefresh(wrapper)
const fresh = structuredClone(c); fresh.batch.version = 4; fresh.executionScope.version = 'exec-new'
vi.mocked(api.getReceivingContext).mockResolvedValue(fresh); vi.mocked(getCargoVerification).mockResolvedValue({ ...verifiedCargo(), verification: { ...verifiedCargo().verification!, version: 3 } })
await wrapper.get('[aria-label="确认当前范围"]').setValue(true); await wrapper.get('form').trigger('submit'); await flushPromises()
expect(button(wrapper, '确认采用本客户最新资料').attributes('disabled')).toBeDefined()
await wrapper.get('[aria-label="确认当前范围"]').setValue(true); await wrapper.get('form').trigger('submit'); await flushPromises()
const second = vi.mocked(api.refreshReceivingCargo).mock.calls[1]![0]
expect(second.member.batchVersion).toBe(4); expect(second.sources[0]!.expectedVerificationVersion).toBe(3); expect(second.executionVersion).toBe('exec-new'); expect(await guard()).toBe(false)
await wrapper.get('form').trigger('submit'); await flushPromises()
expect(api.refreshReceivingCargo).toHaveBeenNthCalledWith(3, second); expect(saveCargoVerification).not.toHaveBeenCalled(); wrapper.unmount()
})
it('requires original source read permissions and blocks adoption for confirmed or waiting-change customers', async () => {
const c = mixedPlans(); c.pendingChanges = [{ ...pendingChange(), intent: { ...pendingChange().intent, customerId: 'customer-b' } }]
vi.mocked(api.getReceivingContext).mockResolvedValue(c)
const wrapper = render(); await flushPromises()
const buttons = wrapper.findAll('button').filter(row => row.text() === '核对并采用本客户最新货物资料')
expect(buttons[0]!.attributes('disabled')).toBeDefined(); expect(buttons[1]!.attributes('disabled')).toBeDefined(); wrapper.unmount()
access.denied = ['platform:overseas-warehouse:last-mile-order:list']; vi.mocked(api.getReceivingContext).mockResolvedValue(mixedPlans())
const denied = render(); await enterRefresh(denied)
expect(getCargoVerification).not.toHaveBeenCalled(); expect(api.refreshReceivingCargo).not.toHaveBeenCalled(); denied.unmount()
})
@@ -0,0 +1,302 @@
<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, reactive, ref } from 'vue'
import { ElMessageBox } from 'element-plus'
import { useAuthStore } from '@/core/auth/auth'
import { useAccessPreviewStore } from '@/core/access/accessPreview'
import { createAppointmentForm, appointmentPayload, appointmentFormError, FbaAppointmentFields } from '@/modules/overseas-warehouse'
import { getApiErrorDetails, type ApiErrorDetails } from '@/shared/api/http'
import LoadErrorState from '@/shared/components/LoadErrorState.vue'
import ApiErrorMeta from '@/shared/components/ApiErrorMeta.vue'
import { getCargoVerification, type CargoVerificationContext } from './cargoVerificationApi'
import ReceivingScope from './ReceivingScope.vue'
import { rejectedCommand, useWorkDraft } from './useWorkDraft'
import { refreshReceivingCargo, type ReceivingCargoRefresh, getReceivingExecutionScope, type ReceivingExecutionScope, saveReceivingPlan, type ReceivingPlan, getReceivingContext, getReceivingGroup, proposeReceivingChange, resolveReceivingChange, bookReceiving, changeReceivingGroup, type ReceivingContext, type ReceivingGroup, type ReceivingMember, type ReceivingPending, type ReceivingResult, type ReceivingPropose, type ReceivingResolve, type ReceivingBook, type ReceivingGroupChange } from './receivingApi'
const props = defineProps<{ batchKey: string; canWrite: boolean; initialCustomerId?: string; owners?: Array<{ id: string; name: string }> }>()
const emit = defineEmits<{ updated: []; appointment: [number: string]; batch: [key: string]; external: [path: string] }>()
const auth = useAuthStore()
const owners = computed(() => [...new Map([...(props.owners || []), ...(auth.user ? [{ id: auth.user.id, name: auth.user.name }] : [])].filter(person => person.id).map(person => [person.id, person])).values()])
const access = useAccessPreviewStore(), context = ref<ReceivingContext | null>(null), group = ref<ReceivingGroup | null>(null)
const loading = ref(false), saving = ref(false), error = ref<ApiErrorDetails | null>(null), saveError = ref<ApiErrorDetails | null>(null), result = ref<ReceivingResult | null>(null)
const confirming = ref(false)
const mode = ref<'refresh' | 'plan' | 'overview' | 'customer' | 'resolve' | 'book' | 'reschedule' | 'cancel'>('overview')
const customer = ref(''), change = ref<ReceivingPending | null>(null), groupKey = ref<string | null>(null)
const adjustment = reactive({ retained: {} as Record<string, number | string>, laterDate: '', ownerId: '', followup: '', reason: '' })
const evidence = ref(''), separate = ref(false), confirmedScope = ref(false)
const bookingForms = ref<Array<ReturnType<typeof createAppointmentForm>>>([]), bookingEvidence = ref<string[]>([])
const bookingMemberKeys = ref<string[]>([]), selectedMemberKeys = ref<string[]>([])
const selectedExecution = ref<ReceivingExecutionScope | null>(null), scopeLoading = ref(false), scopeError = ref<ApiErrorDetails | null>(null)
const cargoContexts = ref<CargoVerificationContext[]>([]), cargoLoading = ref(false), cargoError = ref<ApiErrorDetails | null>(null)
let cargoGeneration = 0
let scopeGeneration = 0
let initializedGroup: string | null = null
const planForm = reactive(createAppointmentForm())
const groupForm = reactive(createAppointmentForm())
const state = () => JSON.stringify({ selectedMemberKeys: selectedMemberKeys.value, planForm, adjustment, evidence: evidence.value, separate: separate.value, bookingForms: bookingForms.value, bookingEvidence: bookingEvidence.value, groupForm })
const baseline = ref(state())
type Command = { kind: 'refresh'; request: ReceivingCargoRefresh } | { kind: 'plan'; request: ReceivingPlan } | { kind: 'propose'; request: ReceivingPropose } | { kind: 'resolve'; key: string; request: ReceivingResolve } | { kind: 'book'; request: ReceivingBook } | { kind: 'group'; key: string; request: ReceivingGroupChange }
const pending = ref<Command | null>(null)
const canLeave = useWorkDraft(computed(() => state() !== baseline.value), computed(() => saving.value || confirming.value || !!pending.value))
const readable = computed(() => access.can('platform:appointment:list'))
const edit = computed(() => props.canWrite && access.can('platform:overseas-warehouse:inbound-order:fba-appointment'))
const remove = computed(() => props.canWrite && access.can('platform:appointment:delete'))
const formWritable = computed(() => mode.value === 'cancel' ? remove.value : ['customer', 'resolve'].includes(mode.value) ? edit.value && remove.value : edit.value)
const locked = computed(() => loading.value || saving.value || confirming.value || !!error.value || !!pending.value)
const sourceKey = (source: { sourceKey: string; destinationKey: string }) => JSON.stringify([source.sourceKey, source.destinationKey])
const customerItems = computed(() => context.value?.batch.items.filter(item => item.customerId === customer.value) || [])
const customers = computed(() => [...new Set(context.value?.batch.items.map(item => item.customerId) || [])])
function customerName(id: string) { return context.value?.agreements.flatMap(row => row.members).find(member => member.customerId === id)?.customerName || context.value?.pendingChanges.flatMap(row => row.originalMembers).find(member => member.customerId === id)?.customerName || null }
const eligibleCustomers = computed(() => customers.value.filter(id => context.value?.executionScope.members.some(row => row.member.batchKey === context.value?.batch.batchKey && row.member.customerId === id && row.canRebook && !row.completed)))
const uncoveredCustomers = computed(() => eligibleCustomers.value.filter(id => !context.value!.agreements.some(a => a.status === 'ACTIVE' && a.members.some(m => m.batchKey === props.batchKey && m.customerId === id)) && !context.value!.pendingChanges.some(c => c.status === 'WAITING' && c.intent.batchKey === props.batchKey && c.intent.customerId === id)))
const refreshReadable = computed(() => readable.value && access.can('platform:overseas-warehouse:last-mile-order:list'))
const refreshEligible = (id: string) => refreshReadable.value && !!context.value?.allowedActions.includes('REFRESH_CARGO') && uncoveredCustomers.value.includes(id)
const planEligible = (id: string) => !!context.value?.allowedActions.includes('PLAN_RECEIVING') && uncoveredCustomers.value.includes(id)
const customerPlan = (id: string) => context.value?.plans.find(plan => plan.batchKey === props.batchKey && plan.customerId === id)
const planTimezone = computed(() => { const saved = customerPlan(customer.value); return saved ? saved.timezone : context.value?.batch.timezone })
const cargoIncomplete = computed(() => !!context.value?.batch.items.filter(item => eligibleCustomers.value.includes(item.customerId)).some(item => item.packageCount == null || !item.destinationKey || !item.sourceVersion))
const bookMembers = computed<ReceivingMember[]>(() => {
if (group.value) return group.value.eligibleMembers
const batch = context.value?.batch
if (!batch?.batchKey || cargoIncomplete.value) return []
return eligibleCustomers.value.filter(id => !context.value!.agreements.some(a => a.status === 'ACTIVE' && a.members.some(m => m.batchKey === batch.batchKey && m.customerId === id)) && !context.value!.pendingChanges.some(c => c.status === 'WAITING' && c.intent.customerId === id)).map(id => ({ batchKey: batch.batchKey!, appointmentNo: batch.appointmentNo, batchVersion: batch.version, customerId: id, customerName: customerName(id), sources: batch.items.filter(item => item.customerId === id).map(item => ({ sourceKey: item.sourceKey, inboundCode: item.inboundCode || null, destinationKey: item.destinationKey!, packageCount: item.packageCount!, sourceVersion: item.sourceVersion!, verificationVersion: item.cargoVerificationVersion ?? null })) }))
})
const cargoProblems = computed(() => {
const problems: string[] = []
if (!customerItems.value.length || customerItems.value.length > 100 || cargoContexts.value.length !== customerItems.value.length) return ['本客户来源范围未完整读取']
if (new Set(customerItems.value.map(item => JSON.stringify([item.sourceKey, item.destinationKey]))).size !== customerItems.value.length) problems.push('本客户存在重复来源,请核对原批次')
customerItems.value.forEach((item, index) => {
const row = cargoContexts.value[index]!, source = row.source, record = row.verification
if (source.sourceKey !== item.sourceKey || source.customerId !== customer.value || source.destinationKey !== item.destinationKey || source.originWarehouseId !== context.value?.batch.originWarehouseId || record && record.destinationKey !== item.destinationKey) problems.push('货物身份、起运仓或目的地与本批不一致')
if (row.sourceChanged || record && record.sourceVersion !== source.sourceVersion) problems.push('原货源已变化,请先重新核实资料')
if (!source.sourceVersion || record && (!Number.isSafeInteger(record.version) || record.version < 1)) problems.push('最新货物资料版本不完整')
if (item.packageCount == null || item.packageCount <= 0 || row.effectivePackages == null || !Number.isSafeInteger(row.effectivePackages) || row.effectivePackages <= 0 || row.availablePackages == null || row.availablePackages < 0 || row.unknownAllocationCount !== 0 || !Number.isSafeInteger(row.allocatedPackages) || row.allocatedPackages < 0) problems.push('本批箱数、最新核实量或分配量待核实')
if (row.effectivePackages != null && (row.allocatedPackages > row.effectivePackages || (item.packageCount ?? 0) > row.effectivePackages)) problems.push('已分配量或本批箱数超过最新核实量')
problems.push(...row.blockReasons, ...source.blockReasons)
})
return [...new Set(problems)]
})
const memberKey = (member: Pick<ReceivingMember, 'batchKey' | 'customerId'>) => JSON.stringify([member.batchKey, member.customerId])
const selectedBookMembers = computed(() => bookMembers.value.filter(member => selectedMemberKeys.value.includes(memberKey(member))))
const bookingRows = computed(() => !selectedBookMembers.value.length ? [] : separate.value ? selectedBookMembers.value.map(member => ({ member, index: bookMembers.value.findIndex(row => memberKey(row) === memberKey(member)) })) : [{ member: null, index: 0 }])
const selectedExecutionAllowed = computed(() => !!selectedExecution.value?.version && selectedBookMembers.value.every(member => selectedExecution.value!.members.some(row => memberKey(row.member) === memberKey(member) && row.canRebook && !row.completed)))
const bookingScopeChanged = computed(() => JSON.stringify(bookingMemberKeys.value) !== JSON.stringify(bookMembers.value.map(memberKey)))
const currentTrips = computed(() => [...new Set((group.value?.transport || context.value?.transport)?.vehicles.map(vehicle => vehicle.tripNo).filter((number): number is string => !!number) || [])])
const laterBatch = computed(() => result.value?.batches.find(batch => result.value?.steps.some(step => step.step === 'ALLOCATE_CARGO' && step.status === 'SUCCESS' && step.targetKey === batch.batchKey)))
const canSubmit = computed(() => {
if (loading.value || error.value || saving.value || confirming.value || result.value || !context.value) return false
if (pending.value) return pending.value.kind === 'group' && pending.value.request.action === 'CANCEL' ? remove.value : pending.value.kind === 'propose' || pending.value.kind === 'resolve' ? edit.value && remove.value : edit.value
if (!confirmedScope.value) return false
if (mode.value === 'refresh') return edit.value && refreshEligible(customer.value) && !cargoLoading.value && !cargoError.value && !cargoProblems.value.length
if (mode.value === 'plan') return edit.value && planEligible(customer.value)
if (mode.value === 'customer') return edit.value && remove.value && context.value.allowedActions.includes('PROPOSE_CUSTOMER_CHANGE')
if (mode.value === 'resolve') return edit.value && remove.value && change.value?.status === 'WAITING'
if (mode.value === 'cancel') return remove.value && group.value?.agreement.status === 'ACTIVE' && !group.value.transport.blockReasons.length
if (mode.value === 'reschedule') return edit.value && group.value?.agreement.status === 'ACTIVE' && !group.value.transport.blockReasons.length
return mode.value === 'book' && edit.value && !!selectedBookMembers.value.length && !bookingScopeChanged.value && !scopeLoading.value && !scopeError.value && selectedExecutionAllowed.value && (group.value ? group.value.agreement.status === 'CANCELLED' : context.value.allowedActions.includes('BOOK_RECEIVING'))
})
async function load() {
if (!readable.value) return
loading.value = true; error.value = null
try {
const next = await getReceivingContext(props.batchKey)
const nextGroup = groupKey.value ? await getReceivingGroup(groupKey.value) : null
context.value = next; group.value = nextGroup
if (nextGroup && initializedGroup !== nextGroup.agreement.agreementKey) {
Object.assign(groupForm, createAppointmentForm(), Object.fromEntries(Object.entries(nextGroup.agreement.details).map(([key, value]) => [key, value ?? ''])))
if (mode.value === 'book') initializeBookings()
initializedGroup = nextGroup.agreement.agreementKey; baseline.value = state()
}
if (change.value) change.value = next.pendingChanges.find(row => row.changeKey === change.value?.changeKey) || null
if (mode.value === 'book' && !result.value) await refreshSelectedScope()
if (mode.value === 'refresh' && !result.value) await loadCargo()
} catch (cause) { error.value = getApiErrorDetails(cause, '预约覆盖范围读取失败') }
finally { loading.value = false }
}
function resetForm() { ++cargoGeneration; cargoLoading.value = false; cargoContexts.value = []; cargoError.value = null; ++scopeGeneration; selectedExecution.value = null; scopeLoading.value = false; scopeError.value = null; evidence.value = ''; confirmedScope.value = false; result.value = null; saveError.value = null; separate.value = false }
async function overview() { if (!await canLeave()) return; mode.value = 'overview'; groupKey.value = null; group.value = null; change.value = null; resetForm(); baseline.value = state(); await load() }
async function adjust(id: string) {
if (locked.value || !await canLeave()) return
resetForm(); groupKey.value = null; group.value = null; customer.value = id; mode.value = 'customer'
adjustment.retained = Object.fromEntries(customerItems.value.filter(item => item.destinationKey).map(item => [sourceKey({ sourceKey: item.sourceKey, destinationKey: item.destinationKey! }), item.packageCount == null ? '' : item.packageCount]))
adjustment.laterDate = ''; adjustment.ownerId = owners.value[0]?.id || ''; adjustment.followup = ''; adjustment.reason = ''; baseline.value = state()
}
async function openCargoRefresh(id: string) {
if (locked.value || !refreshEligible(id) || !await canLeave()) return
resetForm(); groupKey.value = null; group.value = null; customer.value = id; mode.value = 'refresh'; baseline.value = state(); await loadCargo()
}
async function loadCargo() {
const generation = ++cargoGeneration; confirmedScope.value = false; cargoContexts.value = []; cargoError.value = null; cargoLoading.value = false
if (!refreshReadable.value || pending.value) return
if (!customerItems.value.length || customerItems.value.length > 100 || customerItems.value.some(item => !item.destinationKey)) { cargoError.value = { message: '本客户来源或目的地不完整,不能采用资料' }; return }
cargoLoading.value = true
try {
const rows = await Promise.all(customerItems.value.map(item => getCargoVerification({ sourceKey: item.sourceKey, customerId: customer.value, destinationKey: item.destinationKey! })))
if (generation === cargoGeneration) cargoContexts.value = rows
} catch (cause) { if (generation === cargoGeneration) cargoError.value = getApiErrorDetails(cause, '最新货物核实资料读取失败') }
finally { if (generation === cargoGeneration) cargoLoading.value = false }
}
async function openPlan(id: string) {
if (locked.value || !planEligible(id) || !await canLeave()) return
resetForm(); groupKey.value = null; group.value = null; customer.value = id; mode.value = 'plan'
const saved = customerPlan(id)
const header = context.value!.batch
const inherited = !context.value!.agreements.some(agreement => agreement.status === 'ACTIVE') && ['PENDING', 'FAILED'].includes(header.appointmentStatus || '') ? createAppointmentForm(header) : createAppointmentForm()
Object.assign(planForm, createAppointmentForm(), saved ? Object.fromEntries(Object.entries(saved.details).map(([key, value]) => [key, value ?? ''])) : { ...inherited, confirmationNo: '', appointmentAt: '', appointmentEndAt: '', startOffset: '', endOffset: '' })
baseline.value = state()
}
async function resume(pendingChange: ReceivingPending) { if (locked.value || !await canLeave()) return; resetForm(); change.value = pendingChange; mode.value = 'resolve'; baseline.value = state() }
function initializeBookings() { bookingMemberKeys.value = bookMembers.value.map(memberKey); selectedMemberKeys.value = [...bookingMemberKeys.value]; bookingForms.value = bookMembers.value.map(() => ({ ...createAppointmentForm(), appointmentStatus: 'SUCCESS' })); bookingEvidence.value = bookMembers.value.map(() => ''); confirmedScope.value = false; baseline.value = state() }
async function resetBookingScope() { if (await canLeave()) { initializeBookings(); await refreshSelectedScope() } }
async function openGroup(key: string, next: 'book' | 'reschedule' | 'cancel') {
if (locked.value || !await canLeave()) return
resetForm(); groupKey.value = key; group.value = null; initializedGroup = null; mode.value = next; await load()
baseline.value = state()
}
async function newBooking() { if (locked.value || !await canLeave()) return; resetForm(); groupKey.value = null; group.value = null; mode.value = 'book'; initializeBookings(); await refreshSelectedScope() }
async function refreshSelectedScope() {
const generation = ++scopeGeneration
confirmedScope.value = false; selectedExecution.value = null; scopeError.value = null; scopeLoading.value = false
if (mode.value !== 'book' || !readable.value || !selectedBookMembers.value.length || bookingScopeChanged.value) return
const members = selectedBookMembers.value.map(({ batchKey, customerId }) => ({ batchKey, customerId }))
scopeLoading.value = true
try {
const scope = await getReceivingExecutionScope(members)
if (generation === scopeGeneration) selectedExecution.value = scope
} catch (cause) { if (generation === scopeGeneration) scopeError.value = getApiErrorDetails(cause, '所选客户执行资格读取失败') }
finally { if (generation === scopeGeneration) scopeLoading.value = false }
}
onBeforeUnmount(() => { ++scopeGeneration; ++cargoGeneration })
function validation(message: string): never { throw new Error(message) }
function confirmedDetails(form: ReturnType<typeof createAppointmentForm>) { const invalid = appointmentFormError(form); if (invalid) validation(invalid); if (form.appointmentStatus !== 'SUCCESS') validation('此处登记仓库正式确认;尚未确认请使用本客户的“保存目标 / 未约成”入口'); return appointmentPayload(form) }
function buildCommand(decision: 'CONFIRM' | 'WITHDRAW'): Command {
const current = context.value!, idempotencyKey = crypto.randomUUID()
if (mode.value === 'refresh') {
return { kind: 'refresh', request: { idempotencyKey, member: { batchKey: props.batchKey, batchVersion: current.batch.version, customerId: customer.value }, executionVersion: current.executionScope.version, sources: cargoContexts.value.map(row => ({ sourceKey: row.source.sourceKey, destinationKey: row.source.destinationKey, expectedSourceVersion: row.source.sourceVersion!, expectedVerificationVersion: row.verification?.version ?? null })) } }
}
if (mode.value === 'plan') {
if (!['PENDING', 'FAILED'].includes(planForm.appointmentStatus)) validation('客户计划只能保存等待确认或未约成')
if (planForm.confirmationNo || planForm.appointmentAt || planForm.appointmentEndAt) validation('客户计划不能写入正式确认')
if ((planForm.plannedDate || planForm.plannedAt || planForm.plannedEndAt) && !planTimezone.value) validation('目的仓时区待核实,请先补齐;日期未定时可保存联系结果')
if (planForm.plannedEndAt && !planForm.plannedAt) validation('填写结束时段前请填写计划开始时段')
if (planForm.startOffset && !planForm.plannedAt || planForm.endOffset && !planForm.plannedEndAt) validation('仅填写对应计划时段时才可填写时差;仅日期或未定日期请清空时差')
for (const offset of [planForm.startOffset, planForm.endOffset]) if (offset.trim() && !/^[+-](?:0\d|1[0-7]):[0-5]\d$|^[+-]18:00$/.test(offset.trim())) validation('计划时差请按 +08:00 或 -07:00 格式填写')
const invalid = appointmentFormError(planForm); if (invalid) validation(invalid)
return { kind: 'plan', request: { idempotencyKey, member: { batchKey: props.batchKey, batchVersion: current.batch.version, customerId: customer.value }, details: appointmentPayload(planForm), executionVersion: current.executionScope.version } }
}
if (mode.value === 'customer') {
if (!owners.value.some(person => person.id === adjustment.ownerId) || !adjustment.reason.trim()) validation('请选择有效负责人并填写调整原因')
const quantities = customerItems.value.map(item => {
if (!item.destinationKey || !item.sourceVersion || item.packageCount == null) validation('本票数量或来源版本待核实,请先核实货物')
const raw = adjustment.retained[sourceKey({ sourceKey: item.sourceKey, destinationKey: item.destinationKey! })]
if (raw === '' || raw == null) validation('请填写每票本次先送箱数,全部移出可填 0')
const retainedPackages = Number(raw)
if (!Number.isSafeInteger(retainedPackages) || retainedPackages < 0 || retainedPackages > item.packageCount!) validation('先送箱数须为 0 至本票当前箱数之间的整数')
return { sourceKey: item.sourceKey, destinationKey: item.destinationKey!, retainedPackages, expectedSourceVersion: item.sourceVersion!, expectedVerificationVersion: item.cargoVerificationVersion ?? null }
})
if (quantities.every((q, index) => q.retainedPackages === customerItems.value[index]!.packageCount)) validation('本次先送量未改变,无需提交调整')
return { kind: 'propose', request: { idempotencyKey, intent: { batchKey: props.batchKey, batchVersion: current.batch.version, customerId: customer.value, quantities, laterDate: adjustment.laterDate || null, ownerId: adjustment.ownerId, nextFollowupDate: adjustment.followup || null, reason: adjustment.reason.trim(), transportVersion: current.transport.version } } }
}
if (mode.value === 'resolve') {
if (!change.value) validation('待确认记录已变化,请刷新后核对')
if (decision === 'CONFIRM' && !evidence.value.trim()) validation('请填写仓库同意本次保留量和移出量的回复依据')
return { kind: 'resolve', key: change.value!.changeKey, request: { idempotencyKey, version: change.value!.version, decision, warehouseEvidence: evidence.value.trim() || null, transportVersion: current.transport.version } }
}
if (mode.value === 'book') {
const selected = selectedBookMembers.value
const groups = separate.value ? selected.map(member => [member]) : [selected]
return { kind: 'book', request: { idempotencyKey, cancelledAgreementKey: group.value?.agreement.agreementKey || null, cancelledAgreementVersion: group.value?.agreement.version ?? null, executionVersion: selectedExecution.value!.version, bookings: groups.map((members, index) => {
const formIndex = bookingRows.value[index]!.index
const note = bookingEvidence.value[formIndex]?.trim(); if (!note) validation('请逐份填写仓库确认覆盖客户和货量的依据')
return { members: members.map(({ batchKey, batchVersion, customerId }) => ({ batchKey, batchVersion, customerId })), details: confirmedDetails(bookingForms.value[formIndex]!), warehouseEvidence: note! }
}) } }
}
if (!group.value || !evidence.value.trim()) validation('请核对共同预约范围并填写仓库回复依据')
return { kind: 'group', key: group.value!.agreement.agreementKey, request: { idempotencyKey, version: group.value!.agreement.version, action: mode.value === 'cancel' ? 'CANCEL' : 'RESCHEDULE', details: mode.value === 'cancel' ? null : confirmedDetails(groupForm), warehouseEvidence: evidence.value.trim(), transportVersion: group.value!.transport.version } }
}
async function save(decision: 'CONFIRM' | 'WITHDRAW' = 'CONFIRM') {
if (!canSubmit.value) return
if (!pending.value) {
try {
const command = buildCommand(decision)
if (command.kind === 'group' && command.request.action === 'CANCEL') {
confirming.value = true
try { await ElMessageBox.confirm('确认取消当前展示的整份预约?货物需求与批次保留,车辆需重新核对。', '取消整份预约', { customClass: 'admin-density-confirm', confirmButtonText: '确认取消', cancelButtonText: '返回核对' }) } catch { return } finally { confirming.value = false }
}
pending.value = command
} catch (cause) { saveError.value = { message: cause instanceof Error ? cause.message : '请核对本次范围' }; return }
}
saving.value = true; saveError.value = null
try {
const command = pending.value
result.value = command.kind === 'refresh' ? await refreshReceivingCargo(command.request) : command.kind === 'plan' ? await saveReceivingPlan(command.request) : command.kind === 'propose' ? await proposeReceivingChange(command.request) : command.kind === 'resolve' ? await resolveReceivingChange(command.key, command.request) : command.kind === 'book' ? await bookReceiving(command.request) : await changeReceivingGroup(command.key, command.request)
pending.value = null; baseline.value = state(); confirmedScope.value = false; emit('updated'); await load()
} catch (cause) { saveError.value = getApiErrorDetails(cause, '结果待确认,请重试本次提交'); if (rejectedCommand(cause)) { pending.value = null; confirmedScope.value = false; await load() } }
finally { saving.value = false }
}
async function openBatch(key: string) { if (await canLeave()) emit('batch', key) }
onMounted(async () => { await load(); if (props.initialCustomerId && customers.value.includes(props.initialCustomerId)) await adjust(props.initialCustomerId) })
</script>
<template>
<section class="work-form" aria-label="客户调整与共同预约">
<h3>{{ context?.batch.appointmentNo || '预约批次' }} · 客户调整与共同预约</h3>
<p v-if="!readable">当前账号没有预约列表读取权限。</p>
<LoadErrorState v-if="error" title="预约覆盖范围读取失败" :message="error.message" :loading="loading" @retry="load"><template #details><ApiErrorMeta :details="error" /></template></LoadErrorState>
<p v-if="loading">正在核对货物、预约覆盖与车辆…</p>
<template v-if="context">
<el-button v-if="mode !== 'overview' || result" :disabled="locked" @click="overview">返回范围概览</el-button>
<p v-for="reason in context.blockReasons" :key="reason" role="status">{{ reason }}</p>
<section v-if="result" aria-label="本次处理结果">
<h4>{{ result.status === 'WAITING' ? '已保存待确认,原安排尚未改变' : result.status === 'UNCHANGED' ? '安排没有变化' : result.status === 'WITHDRAWN' ? '已撤回变化,原安排保留' : '本次处理已保存' }}</h4>
<p v-for="(step, index) in result.steps" :key="index">{{ step.message }}</p>
<p v-if="result.nextActions.includes('REVIEW_TRANSPORT')">下一步:核对当前收货时段及车辆安排;本次保存不代表可以发车。</p>
<el-button v-if="result.nextActions.includes('BOOK_LATER_BATCH') && laterBatch" :type="result.nextActions[0] === 'BOOK_LATER_BATCH' ? 'primary' : 'default'" :disabled="locked" @click="emit('appointment', laterBatch.appointmentNo)">继续给后送批次约仓</el-button>
<template v-if="result.nextActions.includes('REVIEW_TRANSPORT')"><el-button v-for="(number, index) in currentTrips" :key="number" :type="index === 0 && result.nextActions[0] === 'REVIEW_TRANSPORT' ? 'primary' : 'default'" :disabled="locked || !access.can('platform:fleet:trip:list')" @click="emit('external', `/overseas-master-data/trips/${encodeURIComponent(number)}`)">核对本车发车安排 · {{ number }}</el-button></template>
<el-button v-if="result.status === 'WAITING' && context.pendingChanges.find(row => row.changeKey === result?.changeKey)" type="primary" :disabled="locked" @click="resume(context.pendingChanges.find(row => row.changeKey === result?.changeKey)!)">继续登记仓库回复</el-button>
<template v-if="mode === 'refresh'"><p>本客户资料已处理,可继续保存本客户计划或登记正式预约。</p><el-button :disabled="locked || !planEligible(customer)" @click="openPlan(customer)">继续本客户目标 / 未约成</el-button><el-button :disabled="locked || !edit || !context.allowedActions.includes('BOOK_RECEIVING')" @click="newBooking">核对未确认客户并登记正式预约</el-button></template><p v-if="mode === 'plan'">本客户计划已处理。可返回范围概览核对客户计划,或在本客户事项继续记录回复与跟进。</p><div v-for="batch in (['plan', 'refresh'].includes(mode) ? [] : result.batches).filter(row => row.items.some(item => item.packageCount == null || item.packageCount > 0))" :key="batch.batchKey"><p>{{ batch.appointmentNo }} · {{ batch.plannedDate || '日期未定' }}</p><el-button v-if="batch.batchKey" :disabled="locked" @click="openBatch(batch.batchKey)">查看本批当前去向</el-button><el-button :disabled="locked" @click="emit('appointment', batch.appointmentNo)">继续本批预约</el-button></div>
<el-button v-for="(agreement, index) in result.agreements.filter(row => row.status === 'CANCELLED')" :key="agreement.agreementKey" :type="index === 0 && result.nextActions[0] === 'REBOOK_GROUP' ? 'primary' : 'default'" :disabled="locked" @click="openGroup(agreement.agreementKey, 'book')">重新预约这组货物</el-button>
</section>
<template v-else-if="mode === 'overview'">
<h4>各客户计划与货物调整</h4><p>先保存待确认变化,收到仓库明确回复后再生效;本次先送量允许为 0。</p>
<div v-for="(id, index) in customers" :key="id"><b>{{ customerName(id) || '—' }} · 客户范围 {{ index + 1 }}</b><p v-for="item in context.batch.items.filter(row => row.customerId === id)" :key="item.id">{{ item.inboundCode || '原票业务号未提供' }} · {{ item.packageCount ?? '箱数待核实' }}<span v-if="item.packageCount != null"> 箱</span></p><p v-if="customerPlan(id)">本客户计划:{{ customerPlan(id)!.details.plannedDate || '日期未定' }} · {{ customerPlan(id)!.details.appointmentStatus === 'FAILED' ? '未约成' : '等待确认' }} · {{ customerPlan(id)!.details.appointmentRemark || '—' }}</p><el-button :disabled="locked || !edit || !refreshEligible(id)" @click="openCargoRefresh(id)">核对并采用本客户最新货物资料</el-button><el-button :disabled="locked || !edit || !planEligible(id)" @click="openPlan(id)">保存目标 / 未约成</el-button><el-button :disabled="locked || !edit || !remove || !context.allowedActions.includes('PROPOSE_CUSTOMER_CHANGE')" @click="adjust(id)">调整本客户先送 / 后送</el-button></div>
<h4>待仓库回复</h4><div v-for="pendingChange in context.pendingChanges.filter(row => row.status === 'WAITING')" :key="pendingChange.changeKey"><p>{{ pendingChange.intent.reason }} · 负责人 {{ pendingChange.followup.ownerName || '—' }} · 跟进 {{ pendingChange.followup.nextFollowupDate || '待安排' }}</p><el-button :disabled="locked" @click="resume(pendingChange)">继续本次变化</el-button></div>
<h4>整份预约范围</h4><div v-for="agreement in context.agreements" :key="agreement.agreementKey"><p>{{ agreement.details.confirmationNo || '约号未提供' }} · {{ agreement.status === 'ACTIVE' ? '有效' : agreement.status === 'CANCELLED' ? '已取消' : '历史' }} · {{ agreement.details.appointmentAt || '时段未定' }} → {{ agreement.details.appointmentEndAt || '结束未定' }} · {{ agreement.timezone || '时区待核实' }}</p><ReceivingScope :members="agreement.members" /><el-button v-if="agreement.status === 'ACTIVE'" :disabled="locked" @click="openGroup(agreement.agreementKey, 'reschedule')">核对整份改期范围</el-button><el-button v-if="agreement.status === 'ACTIVE'" :disabled="locked" @click="openGroup(agreement.agreementKey, 'cancel')">核对整份取消范围</el-button><el-button v-if="agreement.status === 'CANCELLED'" :disabled="locked" @click="openGroup(agreement.agreementKey, 'book')">重新预约这组货物</el-button></div>
<ReceivingScope :members="[]" :transport="context.transport" />
<el-button :disabled="locked || !edit || !context.allowedActions.includes('BOOK_RECEIVING')" @click="newBooking">登记当前未覆盖货物的正式预约</el-button>
</template>
<form v-else @submit.prevent="save()">
<fieldset :disabled="locked || !formWritable">
<template v-if="mode === 'refresh'">
<h4>{{ customerName(customer) || '—' }} · 核对本客户最新货物资料</h4><p>采用后仅更新本客户的资料快照,本批箱数和其他客户的确认保持不变;保存核实资料不会自动执行采用。</p>
<p v-if="cargoLoading">正在读取本客户各票最新核实资料…</p>
<LoadErrorState v-if="cargoError" title="最新货物核实资料读取失败" :message="cargoError.message" :loading="cargoLoading" @retry="loadCargo" />
<div v-for="(row, index) in cargoContexts" :key="index"><b>{{ row.source.inboundCode || row.source.bookingNo || '—' }}</b><p>本批 {{ customerItems[index]?.packageCount ?? '待核实' }} 箱 · 最新核实 {{ row.verification?.packageCount ?? '待核实' }} 箱 · 当前有效 {{ row.effectivePackages ?? '待核实' }} 箱 · 已分配 {{ row.allocatedPackages }} 箱</p><p>最新货件号:{{ row.verification?.shipmentReferences.join('、') || '—' }}</p></div>
<p v-for="problem in cargoProblems" :key="problem" role="status">{{ problem }}</p>
<el-button :disabled="locked || cargoLoading" @click="loadCargo">重新读取最新资料</el-button>
</template>
<template v-if="mode === 'plan'">
<h4>{{ customerName(customer) || '—' }} · 本客户普通计划</h4>
<p v-for="item in customerItems" :key="item.id">{{ item.inboundCode || '—' }} · {{ item.packageCount ?? '箱数待核实' }}</p>
<p>{{ planTimezone || '目的仓时区待核实' }} · 只保存本客户计划,其他客户的确认保持不变。</p>
<p v-if="!planEligible(customer)" role="status">本客户资格已变化,暂不能保存普通计划,请返回范围概览核对。</p>
<label>目标送仓日期<input v-model="planForm.plannedDate" type="date" aria-label="客户计划日期"></label>
<label>计划开始时段<input v-model="planForm.plannedAt" @change="planForm.startOffset = ''" type="datetime-local" step="1" aria-label="客户计划开始"></label>
<label>计划结束时段<input v-model="planForm.plannedEndAt" @change="planForm.endOffset = ''" type="datetime-local" step="1" aria-label="客户计划结束"></label>
<details><summary>计划时段的夏令时信息</summary><p>当地时钟回拨导致时刻重复时,请按仓库确认填写对应时差。跳时期间不存在的当地时刻不可用,请选择有效时间。</p><label>计划开始时差<input v-model="planForm.startOffset" aria-label="客户计划开始时差" placeholder="如 -07:00"></label><label>计划结束时差<input v-model="planForm.endOffset" aria-label="客户计划结束时差" placeholder="如 -08:00"></label></details>
<label>本次联系结果<select v-model="planForm.appointmentStatus" aria-label="客户计划状态"><option value="PENDING">等待对方确认</option><option value="FAILED">未约成</option></select></label>
<label>{{ planForm.appointmentStatus === 'FAILED' ? '未约成原因' : '联系备注' }}<textarea v-model="planForm.appointmentRemark" maxlength="1000" aria-label="客户计划备注" /></label>
<p>目标日期可留空;清空日期和时段会清除本客户目标,不取消货物需求。负责人及下次跟进请在本客户事项的“记录回复与跟进”维护。</p>
</template>
<template v-if="mode === 'customer'"><h4>仅本客户调整,其他客户保持原安排</h4><div v-for="item in customerItems" :key="item.id"><p>{{ item.inboundCode || '原票业务号未提供' }} · 当前 {{ item.packageCount ?? '待核实' }} 箱</p><label v-if="item.destinationKey">本次先送箱数<input v-model="adjustment.retained[sourceKey({ sourceKey: item.sourceKey, destinationKey: item.destinationKey })]" type="number" min="0" :max="item.packageCount ?? undefined" step="1" aria-label="本次先送箱数"></label></div><label>后送目标日期<input v-model="adjustment.laterDate" type="date"></label><label>负责人<select v-model="adjustment.ownerId" required aria-label="调整负责人"><option value="" disabled>请选择负责人</option><option v-for="person in owners" :key="person.id" :value="person.id">{{ person.name }}</option></select></label><label>下一次跟进日期<input v-model="adjustment.followup" type="date"></label><label>调整原因<textarea v-model="adjustment.reason" maxlength="1000" aria-label="调整原因" /></label><p>保存仅登记待确认变化,原箱数与原确认仍保留,相关发车暂受阻。</p></template>
<template v-if="mode === 'resolve' && change"><h4>仓库回复:本次客户调整</h4><ReceivingScope :members="change.originalMembers" :transport="context.transport" /><p v-for="(quantity, index) in change.intent.quantities" :key="sourceKey(quantity)">货物 {{ index + 1 }} · 本次先送 {{ quantity.retainedPackages }} 箱</p><p>负责人 {{ change.followup.ownerName || '—' }} · 跟进 {{ change.followup.nextFollowupDate || '待安排' }}</p><p>后送日期 {{ change.intent.laterDate || '未定' }} · {{ change.intent.reason }}</p><p v-for="agreement in change.originalAgreements" :key="agreement.agreementKey">原约号 {{ agreement.details.confirmationNo || '—' }} · {{ agreement.details.appointmentAt || '时段未定' }} · {{ agreement.timezone || '时区待核实' }}</p><label>仓库同意保留量和移出量的回复依据<textarea v-model="evidence" maxlength="1000" aria-label="仓库回复依据" /></label></template>
<template v-if="group"><h4>{{ mode === 'book' ? '整组重约当前范围' : '整份预约当前范围' }}</h4><ReceivingScope :members="mode === 'book' ? selectedBookMembers : group.agreement.members" :transport="group.transport" /><div v-for="(excluded, index) in group.excludedMembers" :key="`${excluded.member.batchKey}:${excluded.member.customerId}`" role="status">排除范围 {{ index + 1 }} · {{ excluded.member.appointmentNo }}:{{ excluded.reason }}</div></template>
<template v-if="mode === 'book'"><p>未取得确认时,可先按客户保存目标或未约成原因。</p><el-button v-for="member in bookMembers.filter(row => row.batchKey === batchKey && planEligible(row.customerId))" :key="member.customerId" :disabled="locked || !edit" @click="openPlan(member.customerId)">{{ member.customerName || member.sources.map(source => source.inboundCode || '—').join('、') }} · 保存目标 / 未约成</el-button><p v-if="!group && cargoIncomplete" role="status">货物数量或来源资料待核实,当前不能登记正式预约。</p><p v-if="bookingScopeChanged" role="status">当前成员范围已变化,请核对上方范围后重新填写预约,原输入不会自动套用给其他客户。<el-button :disabled="locked" @click="resetBookingScope">按当前范围重新填写</el-button></p><template v-if="!group"><p v-for="(excluded, index) in context.executionScope.members.filter(row => row.completed || !row.canRebook)" :key="`${excluded.member.batchKey}:${excluded.member.customerId}`" role="status">排除客户范围 {{ index + 1 }}:{{ excluded.reason || (excluded.completed ? '已完成' : '当前不可重新预约') }}</p></template><ReceivingScope v-if="!group" :members="selectedBookMembers" :transport="context.transport" /><LoadErrorState v-if="scopeError" title="所选客户执行资格读取失败" :message="scopeError.message" :loading="scopeLoading" @retry="refreshSelectedScope" /><p v-if="scopeLoading">正在核对所选客户执行资格…</p><p v-if="!scopeLoading && !scopeError && selectedBookMembers.length && !selectedExecutionAllowed" role="status">所选客户执行资格不完整或不可办理,请核对后重新选择。</p><p v-for="(eligibility, index) in selectedExecution?.members.filter(row => row.completed || !row.canRebook) || []" :key="index" role="status">所选范围 {{ index + 1 }}:{{ eligibility.reason || '当前不可重新预约' }}</p><div aria-label="本次预约客户"><h4>选择本次取得确认的客户</h4><label v-for="(member, index) in bookMembers" :key="memberKey(member)"><input v-model="selectedMemberKeys" @change="refreshSelectedScope" :value="memberKey(member)" type="checkbox" :aria-label="`选择预约客户 ${index + 1}`">{{ member.appointmentNo }} · {{ member.customerName || member.sources.map(source => source.inboundCode || '—').join('、') }}</label><p v-if="!selectedBookMembers.length">请至少选择一个客户。</p></div><label><input v-model="separate" type="checkbox">所选客户分别登记预约</label><p>共同预约须由仓库明确确认覆盖当前全部所选客户和货量;重复填写同一约号不能代替共同预约。</p><template v-for="(row, index) in (bookingScopeChanged ? [] : bookingRows)" :key="index"><h4>{{ separate ? `${row.member?.appointmentNo} · ${row.member?.customerName || '—'} · 客户范围 ${index + 1}` : '一份共同预约' }}</h4><FbaAppointmentFields :model="bookingForms[row.index]!" :timezone="group?.agreement.timezone || context.batch.timezone" :disabled="locked || !edit" /><label>仓库确认覆盖依据<textarea v-model="bookingEvidence[row.index]" maxlength="1000" aria-label="预约覆盖依据" /></label></template></template>
<template v-if="mode === 'reschedule' || mode === 'cancel'"><FbaAppointmentFields v-if="mode === 'reschedule'" :model="groupForm" :timezone="group?.agreement.timezone" :disabled="locked || !edit" /><p v-else>整份取消会清除活动确认及失效目标,保留历史、批次数量和车辆关系;后续仍须重新约仓并核对车辆。</p><label>仓库回复依据<textarea v-model="evidence" maxlength="1000" aria-label="整份回复依据" /></label></template>
<label><input v-model="confirmedScope" type="checkbox" :disabled="mode === 'book' && (scopeLoading || !!scopeError || !selectedExecutionAllowed) || mode === 'refresh' && (cargoLoading || !!cargoError || !!cargoProblems.length)" aria-label="确认当前范围">已核对上述客户货物、当前预约与车辆范围</label>
</fieldset>
<el-button type="primary" native-type="submit" :disabled="!canSubmit" :loading="saving">{{ pending ? '重试本次提交' : mode === 'refresh' ? '确认采用本客户最新资料' : mode === 'plan' ? '保存本客户计划' : mode === 'customer' ? '保存待仓库确认' : mode === 'resolve' ? '确认回复并应用本次调整' : mode === 'cancel' ? '确认整份取消' : mode === 'reschedule' ? '保存整份改期' : '保存本次正式预约' }}</el-button>
<el-button v-if="mode === 'resolve' && !pending" :disabled="!canSubmit" @click="save('WITHDRAW')">撤回变化并保留原安排</el-button>
</form>
<LoadErrorState v-if="saveError" title="本次提交尚未完成" :message="saveError.message" :show-retry="false"><template #details><ApiErrorMeta :details="saveError" /></template></LoadErrorState>
</template>
</section>
</template>
@@ -0,0 +1,48 @@
import { flushPromises, mount } from '@vue/test-utils'
import { beforeEach, expect, it, vi } from 'vitest'
import WorkSharedTripForm from './WorkSharedTripForm.vue'
import { getDispatch } from '@/modules/overseas-warehouse'
import type { LeaveGuard } from './useWorkDraft'
const access = vi.hoisted(() => ({ allowed: true }))
vi.mock('@/core/access/accessPreview', () => ({ useAccessPreviewStore: () => ({ can: () => access.allowed }) }))
vi.mock('@/modules/overseas-warehouse', async original => ({ ...await original<typeof import('@/modules/overseas-warehouse')>(), getDispatch: vi.fn() }))
vi.mock('element-plus', () => ({ ElMessage: { warning: vi.fn() } }))
let guard: LeaveGuard
function render() { return mount(WorkSharedTripForm, { props: { dispatchNo: 'DS-60', canWrite: true }, global: { provide: { 'appointment-work-leave-guard': (value: LeaveGuard) => { guard = value; return () => undefined } }, stubs: {
ElButton: { props: ['disabled'], template: '<button :disabled="disabled"><slot /></button>' },
TripPreparationDialog: { name: 'TripPreparationDialog', props: ['modelValue', 'warehouseId', 'dispatchNos'], template: '<div />' },
LoadErrorState: { props: ['message'], template: '<p role="alert">{{ message }}</p>' }, ApiErrorMeta: true,
} } }) }
beforeEach(() => { vi.clearAllMocks(); access.allowed = true; vi.mocked(getDispatch).mockImplementation(async number => ({ id: `internal-${number}`, dispatchNo: number, appointmentBatches: [], customerId: number === 'DS-60' ? 'customer-b' : 'customer-d', overseasWarehouseId: 'warehouse-real', overseasWarehouseName: '实际起运仓', packageCount: number === 'DS-60' ? 60 : 40, status: 'PENDING_DEPARTURE' })) })
it('checks exact 60 and 40 dispatch business numbers and passes both to the existing Fleet preparation before navigating to its real trip', async () => {
const wrapper = render()
expect(getDispatch).not.toHaveBeenCalled()
await wrapper.get('input').setValue('DS-40'); await wrapper.get('button').trigger('click'); await flushPromises()
expect(vi.mocked(getDispatch).mock.calls.map(call => call[0])).toEqual(['DS-60', 'DS-40'])
const prepare = wrapper.getComponent({ name: 'TripPreparationDialog' })
expect(prepare.props()).toMatchObject({ modelValue: true, warehouseId: 'warehouse-real', dispatchNos: ['DS-60', 'DS-40'] })
expect(wrapper.text()).toContain('60 箱'); expect(wrapper.text()).toContain('40 箱'); expect(wrapper.text()).not.toContain('internal-')
expect(await guard()).toBe(false)
prepare.vm.$emit('saved', { trip: { tripNo: 'TR-SHARED' } }); await flushPromises()
expect(wrapper.emitted('external')).toEqual([['/overseas-master-data/trips/TR-SHARED']]); expect(wrapper.emitted('updated')).toHaveLength(1)
wrapper.unmount()
})
it('rejects duplicate, cross-warehouse, already-bound and mismatched dispatches without opening Fleet preparation', async () => {
const wrapper = render(); await wrapper.get('input').setValue('DS-60'); await wrapper.get('button').trigger('click'); await flushPromises()
expect(getDispatch).not.toHaveBeenCalled()
for (const change of [{ overseasWarehouseId: 'another-warehouse' }, { workflow: { tripNo: 'TR-OTHER', dispatchReview: { status: 'PENDING' as const, reason: null, reviewedAt: null }, loadingReview: { status: 'PENDING' as const, reason: null, reviewedAt: null } } }, { status: 'SHIPPED' }, { dispatchNo: 'WRONG' }]) {
vi.mocked(getDispatch).mockResolvedValueOnce({ id: 'a', dispatchNo: 'DS-60', appointmentBatches: [], overseasWarehouseId: 'warehouse-real', status: 'PENDING_DEPARTURE' }).mockResolvedValueOnce({ id: 'b', dispatchNo: 'DS-40', appointmentBatches: [], overseasWarehouseId: 'warehouse-real', status: 'PENDING_DEPARTURE', ...change })
await wrapper.get('input').setValue('DS-40'); await wrapper.get('button').trigger('click'); await flushPromises()
expect(wrapper.findComponent({ name: 'TripPreparationDialog' }).exists()).toBe(false); expect(wrapper.find('[role="alert"]').exists()).toBe(true)
}
wrapper.unmount()
})
it('keeps a failed lookup retry read-only and respects original permissions', async () => {
const wrapper = render(); vi.mocked(getDispatch).mockRejectedValueOnce(new Error('读取失败'))
await wrapper.get('input').setValue('DS-40'); await wrapper.get('button').trigger('click'); await flushPromises()
expect(wrapper.findComponent({ name: 'TripPreparationDialog' }).exists()).toBe(false)
await wrapper.get('button').trigger('click'); await flushPromises()
expect(getDispatch).toHaveBeenCalledTimes(4); expect(wrapper.getComponent({ name: 'TripPreparationDialog' }).props('dispatchNos')).toEqual(['DS-60', 'DS-40'])
wrapper.unmount(); access.allowed = false
const readonly = render(); await readonly.get('button').trigger('click'); expect(getDispatch).toHaveBeenCalledTimes(4); readonly.unmount()
})
@@ -0,0 +1,50 @@
<script setup lang="ts">
import { computed, onBeforeUnmount, ref, watch } from 'vue'
import { useAccessPreviewStore } from '@/core/access/accessPreview'
import { getDispatch, type DispatchSummaryDto } from '@/modules/overseas-warehouse'
import { TripPreparationDialog } from '@/modules/overseas-master-data'
import { getApiErrorDetails, type ApiErrorDetails } from '@/shared/api/http'
import LoadErrorState from '@/shared/components/LoadErrorState.vue'
import ApiErrorMeta from '@/shared/components/ApiErrorMeta.vue'
import { useWorkDraft } from './useWorkDraft'
const props = defineProps<{ dispatchNo: string; canWrite: boolean }>()
const emit = defineEmits<{ updated: []; busy: [value: boolean]; external: [path: string] }>()
const access = useAccessPreviewStore(), otherNo = ref(''), rows = ref<DispatchSummaryDto[]>([])
const loading = ref(false), error = ref<ApiErrorDetails | null>(null), prepareOpen = ref(false)
const allowed = computed(() => props.canWrite && ['platform:overseas-warehouse:dispatch:list', 'platform:fleet:trip:list', 'platform:fleet:trip:edit'].every(permission => access.can(permission)))
watch(prepareOpen, value => emit('busy', value))
useWorkDraft(computed(() => false), prepareOpen)
let generation = 0
function changed() { ++generation; loading.value = false; rows.value = []; error.value = null }
async function prepare() {
if (!allowed.value || loading.value || prepareOpen.value) return
rows.value = []; error.value = null
const other = otherNo.value.trim()
if (!other || other === props.dispatchNo) { error.value = { message: '请填写另一张已备好的排车单业务号,不能重复选择本单。' }; return }
const current = ++generation; loading.value = true
try {
const numbers = [props.dispatchNo, other]
const details = await Promise.all(numbers.map(getDispatch))
if (current !== generation) return
if (details.some((row, index) => row.dispatchNo !== numbers[index])) throw new Error('返回的排车单与所选业务号不一致,请重新核对。')
if (details.some(row => row.status !== 'PENDING_DEPARTURE' || row.workflow)) throw new Error('请选择尚未关联车次的待发运排车单;已关联的货物请从原车次继续处理。')
if (!details[0]!.overseasWarehouseId || details.some(row => row.overseasWarehouseId !== details[0]!.overseasWarehouseId)) throw new Error('两张排车单必须有明确且相同的起运仓。')
rows.value = details; prepareOpen.value = true
} catch (cause) { if (current === generation) error.value = getApiErrorDetails(cause, '共车排车单核对失败') }
finally { if (current === generation) loading.value = false }
}
function saved(value: { trip: { tripNo: string } }) { prepareOpen.value = false; emit('updated'); emit('external', `/overseas-master-data/trips/${encodeURIComponent(value.trip.tripNo)}`) }
onBeforeUnmount(() => { ++generation; emit('busy', false) })
</script>
<template>
<section class="work-form" aria-label="与同仓其他排车单共车">
<h4>与同仓其他排车单共车</h4>
<p>本批排车单:{{ dispatchNo }}。请先按各客户实际托盘分别备好排车单,再核对同仓两单并安排同一车次。</p>
<p>所需箱数无法对应完整实物时,请先在原库存作业中完成拆托,再返回核对;分批计划不会代替实物拆托。</p>
<label>另一张排车单号<input v-model="otherNo" aria-label="共车排车单号" maxlength="64" :disabled="loading || prepareOpen || !allowed" @input="changed" @keydown.enter.prevent="prepare"></label>
<el-button :disabled="!allowed || prepareOpen" :loading="loading" @click="prepare">核对两单并安排共车</el-button>
<LoadErrorState v-if="error" title="共车排车单核对失败" :message="error.message" :show-retry="false"><template #details><ApiErrorMeta :details="error" /></template></LoadErrorState>
<p v-for="row in rows" :key="row.dispatchNo">{{ row.dispatchNo }} · {{ row.overseasWarehouseName || '起运仓名称待核实' }} · {{ row.packageCount ?? '箱数待核实' }}<span v-if="row.packageCount != null"> 箱</span></p>
<TripPreparationDialog v-if="rows[0]?.overseasWarehouseId" v-model="prepareOpen" :warehouse-id="rows[0].overseasWarehouseId" :warehouse-name="rows[0].overseasWarehouseName || '起运仓名称待核实'" :dispatch-nos="rows.map(row => row.dispatchNo)" @saved="saved" />
</section>
</template>
@@ -1,9 +1,10 @@
import type { FbaAppointmentBatchContext } from './batchApi'
export function batchContext(number = 'AP-001', key = 'FBA_APPOINTMENT:1'): FbaAppointmentBatchContext {
return { appointment: { id: '1', appointmentNo: number, batchKey: key, version: 3, appointmentStatus: 'PENDING', originWarehouseId: 'origin-1', fbaWarehouseCode: 'ONT8', selectedCount: 2, replacementAppointmentNos: [], replacementBatchKeys: [], items: [
{ id: 'item-1', customerId: 'customer-a', sourceKey: 'ORDER:1', inboundCode: 'IN-A', fbaWarehouseCode: 'ONT8', packageCount: 70, shipmentReferences: ['FBA-A'] },
{ id: 'item-2', customerId: 'customer-b', sourceKey: 'BOOKING:2', inboundCode: 'IN-B', fbaWarehouseCode: 'ONT8', packageCount: 30, shipmentReferences: ['FBA-B'] },
] }, sources: [
const appointment: FbaAppointmentBatchContext['appointment'] = { id: '1', appointmentNo: number, batchKey: key, version: 3, appointmentStatus: 'PENDING', originWarehouseId: 'origin-1', fbaWarehouseCode: 'ONT8', selectedCount: 2, replacementAppointmentNos: [], replacementBatchKeys: [], items: [
{ id: 'item-1', customerId: 'customer-a', sourceKey: 'ORDER:1', destinationKey: 'FBA:ONT8', inboundCode: 'IN-A', fbaWarehouseCode: 'ONT8', packageCount: 70, shipmentReferences: ['FBA-A'] },
{ id: 'item-2', customerId: 'customer-b', sourceKey: 'BOOKING:2', destinationKey: 'FBA:ONT8', inboundCode: 'IN-B', fbaWarehouseCode: 'ONT8', packageCount: 30, shipmentReferences: ['FBA-B'] },
] }
return { appointment, originalSourceRefs: appointment.items.map(item => ({ customerId: item.customerId, sourceKey: item.sourceKey, destinationKey: item.destinationKey! })), currentBatches: [appointment], sources: [
{ customerId: 'customer-a', sourceKey: 'ORDER:1', destinationKey: 'FBA:ONT8', packageCount: 70, originalPackages: 100, sourceVersion: 'source-a-v2', cargoVerificationVersion: 4, shipmentReferences: ['FBA-A'] },
{ customerId: 'customer-b', sourceKey: 'BOOKING:2', destinationKey: 'FBA:ONT8', packageCount: 30, originalPackages: null, sourceVersion: null, cargoVerificationVersion: 2, shipmentReferences: ['FBA-B'] },
], allowedActions: ['VERIFY_CARGO', 'SPLIT', 'MERGE'], blockReasons: [] }
+1 -1
View File
@@ -4,7 +4,7 @@ export interface BatchSourceAllocation {
customerId: string; sourceKey: string; destinationKey: string; packageCount: number | null
originalPackages: number | null; sourceVersion: string | null; cargoVerificationVersion: number | null; shipmentReferences: string[]
}
export interface FbaAppointmentBatchContext { appointment: FbaAppointmentDto; sources: BatchSourceAllocation[]; allowedActions: Array<'VERIFY_CARGO' | 'SPLIT' | 'MERGE'>; blockReasons: string[] }
export interface FbaAppointmentBatchContext { appointment: FbaAppointmentDto; originalSourceRefs: Array<{ customerId: string; sourceKey: string; destinationKey: string }>; currentBatches: FbaAppointmentDto[]; sources: BatchSourceAllocation[]; allowedActions: Array<'VERIFY_CARGO' | 'SPLIT' | 'MERGE'>; blockReasons: string[] }
export interface BatchAllocation { customerId: string; sourceKey: string; packageCount: number; expectedSourceVersion: string | null; expectedVerificationVersion: number | null }
export interface RepartitionFbaAppointmentsRequest {
originals: Array<{ appointmentNo: string; version: number }>
@@ -1 +1,2 @@
export { appointmentReturnTarget, appointmentReturnQuery } from './workNavigation'
export { default as TripAppointmentPanel } from './TripAppointmentPanel.vue'
@@ -0,0 +1,44 @@
import { beforeEach, expect, it, vi } from 'vitest'
import { http } from '@/shared/api/http'
import { refreshReceivingCargo, getReceivingExecutionScope, saveReceivingPlan, getReceivingContext, getReceivingGroup, proposeReceivingChange, resolveReceivingChange, bookReceiving, changeReceivingGroup } from './receivingApi'
vi.mock('@/shared/api/http', () => ({ http: { get: vi.fn(), post: vi.fn() }, unwrapApiResponse: <T>(value: { data: T }) => value.data }))
beforeEach(() => { vi.clearAllMocks(); vi.mocked(http.get).mockResolvedValue({ data: {} }); vi.mocked(http.post).mockResolvedValue({ data: {} }) })
it('uses the producer receiving paths and encodes opaque stable identities', async () => {
await getReceivingContext('FBA_APPOINTMENT:1'); await getReceivingGroup('GROUP/1')
expect(http.get).toHaveBeenNthCalledWith(1, '/platform/v1/last-leg/appointment-receiving/batches/FBA_APPOINTMENT%3A1')
expect(http.get).toHaveBeenNthCalledWith(2, '/platform/v1/last-leg/appointment-receiving/agreements/GROUP%2F1')
const propose = { idempotencyKey: 'unchanged-key', intent: { batchKey: 'FBA_APPOINTMENT:1', batchVersion: 3, customerId: 'customer-a', quantities: [{ sourceKey: 'ORDER:1', destinationKey: 'FBA:ONT8', retainedPackages: 0, expectedSourceVersion: 'v1', expectedVerificationVersion: 1 }], laterDate: null, ownerId: 'account-owner', nextFollowupDate: null, reason: '全部后送', transportVersion: 'scope-v1' } }
await proposeReceivingChange(propose)
expect(http.post).toHaveBeenLastCalledWith('/platform/v1/last-leg/appointment-receiving/changes', propose)
const resolve = { idempotencyKey: 'resolve-key', version: 0, decision: 'CONFIRM' as const, warehouseEvidence: '明确回复', transportVersion: 'scope-v2' }
await resolveReceivingChange('CH/1', resolve)
expect(http.post).toHaveBeenLastCalledWith('/platform/v1/last-leg/appointment-receiving/changes/CH%2F1/resolve', resolve)
const book = { idempotencyKey: 'book-key', bookings: [], cancelledAgreementKey: 'GROUP/1', cancelledAgreementVersion: 2, executionVersion: 'scope-v2' }
await bookReceiving(book)
expect(http.post).toHaveBeenLastCalledWith('/platform/v1/last-leg/appointment-receiving/bookings', book)
const cancel = { idempotencyKey: 'cancel-key', version: 3, action: 'CANCEL' as const, details: null, warehouseEvidence: '取消依据', transportVersion: 'scope-v3' }
await changeReceivingGroup('GROUP/1', cancel)
expect(http.post).toHaveBeenLastCalledWith('/platform/v1/last-leg/appointment-receiving/agreements/GROUP%2F1/cancel', cancel)
await changeReceivingGroup('GROUP/1', { ...cancel, action: 'RESCHEDULE' })
expect(http.post).toHaveBeenLastCalledWith('/platform/v1/last-leg/appointment-receiving/agreements/GROUP%2F1/reschedule', expect.objectContaining({ action: 'RESCHEDULE' }))
})
it('posts a customer-scoped ordinary plan with execution version and no formal confirmation', async () => {
const request = { idempotencyKey: 'plan-1', member: { batchKey: 'FBA_APPOINTMENT:1', batchVersion: 4, customerId: 'customer-b' }, executionVersion: 'exec-2', details: { plannedDate: null, plannedAt: null, plannedEndAt: null, appointmentStatus: 'FAILED' as const, appointmentRemark: '没有时段', confirmationNo: null, appointmentAt: null, appointmentEndAt: null, startOffset: null, endOffset: null } }
await saveReceivingPlan(request)
expect(http.post).toHaveBeenCalledWith('/platform/v1/last-leg/appointment-receiving/plans', request)
})
it('reads execution eligibility for the explicitly selected members without including guessed versions', async () => {
const members = [{ batchKey: 'FBA_APPOINTMENT:2', customerId: 'customer-b' }]
const scope = { version: 'only-B', members: [] }
vi.mocked(http.post).mockResolvedValueOnce({ data: scope })
expect(await getReceivingExecutionScope(members)).toEqual(scope)
expect(http.post).toHaveBeenCalledWith('/platform/v1/last-leg/appointment-receiving/execution-scope', { members })
})
it('adopts latest customer cargo versions without including quantity mutations or confirmation fields', async () => {
const request = { idempotencyKey: 'adopt-b', member: { batchKey: 'FBA_APPOINTMENT:1', batchVersion: 4, customerId: 'customer-b' }, executionVersion: 'exec-current', sources: [{ sourceKey: 'BOOKING:2', destinationKey: 'FBA:ONT8', expectedSourceVersion: 'latest', expectedVerificationVersion: 2 }] }
await refreshReceivingCargo(request)
expect(http.post).toHaveBeenCalledWith('/platform/v1/last-leg/appointment-receiving/cargo-refresh', request)
})
@@ -0,0 +1,36 @@
import { http, unwrapApiResponse, type ApiEnvelope } from '@/shared/api/http'
import type { FbaAppointmentDetailsPayload, FbaAppointmentDto } from '@/modules/overseas-warehouse'
export interface ReceivingSource { sourceKey: string; destinationKey: string; packageCount: number; sourceVersion: string; verificationVersion: number | null; inboundCode: string | null }
export interface ReceivingMember { batchKey: string; appointmentNo: string; batchVersion: number; customerId: string; sources: ReceivingSource[]; customerName: string | null }
export interface ReceivingAgreement { agreementKey: string; version: number; status: string; destinationKey: string; details: FbaAppointmentDetailsPayload; timezone: string | null; members: ReceivingMember[]; warehouseEvidence: string }
export interface ReceivingTransport { version: string; vehicles: Array<{ tripNo: string | null; version: number | null; dispatchNo: string | null; customerId: string; batchKey: string; status: string; packageCount: number }>; blockReasons: string[] }
export interface ReceivingQuantity { sourceKey: string; destinationKey: string; retainedPackages: number; expectedSourceVersion: string; expectedVerificationVersion: number | null }
export interface ReceivingIntent { batchKey: string; batchVersion: number; customerId: string; quantities: ReceivingQuantity[]; laterDate: string | null; ownerId: string; nextFollowupDate: string | null; reason: string; transportVersion: string }
export interface ReceivingExecutionScope { version: string; members: Array<{ member: { batchKey: string; customerId: string }; completed: boolean; canRebook: boolean; reason: string | null }> }
export interface ReceivingPending { changeKey: string; version: number; status: string; intent: ReceivingIntent; originalMembers: ReceivingMember[]; originalAgreements: ReceivingAgreement[]; followup: { ownerId: string; ownerName: string | null; nextFollowupDate: string | null } }
export interface ReceivingCustomerPlan { batchKey: string; customerId: string; details: FbaAppointmentDetailsPayload; timezone: string | null }
export interface ReceivingCargoRefresh { idempotencyKey: string; member: Pick<ReceivingMember, 'batchKey' | 'batchVersion' | 'customerId'>; sources: Array<{ sourceKey: string; destinationKey: string; expectedSourceVersion: string; expectedVerificationVersion: number | null }>; executionVersion: string }
export interface ReceivingPlan { idempotencyKey: string; member: Pick<ReceivingMember, 'batchKey' | 'batchVersion' | 'customerId'>; details: FbaAppointmentDetailsPayload; executionVersion: string }
export interface ReceivingContext { batch: FbaAppointmentDto; plans: ReceivingCustomerPlan[]; agreements: ReceivingAgreement[]; pendingChanges: ReceivingPending[]; transport: ReceivingTransport; executionScope: ReceivingExecutionScope; allowedActions: string[]; blockReasons: string[] }
export interface ReceivingGroup { agreement: ReceivingAgreement; eligibleMembers: ReceivingMember[]; excludedMembers: Array<{ member: ReceivingMember; reason: string; currentAgreementKey: string | null }>; transport: ReceivingTransport; executionScope: ReceivingExecutionScope }
export interface ReceivingResult { changeKey: string | null; status: string; batches: FbaAppointmentDto[]; agreements: ReceivingAgreement[]; steps: Array<{ step: string; status: string; targetKey: string; message: string }>; nextActions: string[] }
export interface ReceivingPropose { idempotencyKey: string; intent: ReceivingIntent }
export interface ReceivingResolve { idempotencyKey: string; version: number; decision: 'CONFIRM' | 'WITHDRAW'; warehouseEvidence: string | null; transportVersion: string }
export interface ReceivingBooking { members: Array<Pick<ReceivingMember, 'batchKey' | 'batchVersion' | 'customerId'>>; details: FbaAppointmentDetailsPayload; warehouseEvidence: string }
export interface ReceivingBook { idempotencyKey: string; bookings: ReceivingBooking[]; cancelledAgreementKey: string | null; cancelledAgreementVersion: number | null; executionVersion: string }
export interface ReceivingGroupChange { idempotencyKey: string; version: number; action: 'RESCHEDULE' | 'CANCEL'; details: FbaAppointmentDetailsPayload | null; warehouseEvidence: string; transportVersion: string }
const base = '/platform/v1/last-leg/appointment-receiving'
export async function getReceivingContext(batchKey: string) { return unwrapApiResponse(await http.get<ApiEnvelope<ReceivingContext>, ApiEnvelope<ReceivingContext>>(`${base}/batches/${encodeURIComponent(batchKey)}`)) }
export async function getReceivingGroup(agreementKey: string) { return unwrapApiResponse(await http.get<ApiEnvelope<ReceivingGroup>, ApiEnvelope<ReceivingGroup>>(`${base}/agreements/${encodeURIComponent(agreementKey)}`)) }
async function post(path: string, request: ReceivingCargoRefresh | ReceivingPlan | ReceivingPropose | ReceivingResolve | ReceivingBook | ReceivingGroupChange) { return unwrapApiResponse(await http.post<ApiEnvelope<ReceivingResult>, ApiEnvelope<ReceivingResult>>(`${base}${path}`, request)) }
export const proposeReceivingChange = (request: ReceivingPropose) => post('/changes', request)
export const resolveReceivingChange = (changeKey: string, request: ReceivingResolve) => post(`/changes/${encodeURIComponent(changeKey)}/resolve`, request)
export const bookReceiving = (request: ReceivingBook) => post('/bookings', request)
export const changeReceivingGroup = (agreementKey: string, request: ReceivingGroupChange) => post(`/agreements/${encodeURIComponent(agreementKey)}/${request.action === 'CANCEL' ? 'cancel' : 'reschedule'}`, request)
export const saveReceivingPlan = (request: ReceivingPlan) => post('/plans', request)
export async function getReceivingExecutionScope(members: Array<{ batchKey: string; customerId: string }>) { return unwrapApiResponse(await http.post<ApiEnvelope<ReceivingExecutionScope>, ApiEnvelope<ReceivingExecutionScope>>(`${base}/execution-scope`, { members })) }
export const refreshReceivingCargo = (request: ReceivingCargoRefresh) => post('/cargo-refresh', request)
@@ -1,10 +1,16 @@
import { beforeEach, expect, it, vi } from 'vitest'
import { http } from '@/shared/api/http'
import { getWorkCalendar, getWorkSummary, getWorkItems, getWorkDetail, submitWorkCommand } from './workApi'
import { getWorkCalendar, getWorkSummary, getWorkItems, getWorkDetail, submitWorkCommand, resolveBatchWork } from './workApi'
import { getCargoVerification, saveCargoVerification } from './cargoVerificationApi'
import { workCalendar, workDetail, workItem, workSummary } from './work.test-support'
vi.mock('@/shared/api/http', () => ({ http: { get: vi.fn(), post: vi.fn() }, unwrapApiResponse: <T>(value: { data: T }) => value.data }))
beforeEach(() => vi.clearAllMocks())
it('resolves a real batch and optional customer without manufacturing a work key', async () => {
const resolved = { batchKey: 'FBA_APPOINTMENT:40', customerId: '9007199254740999', detail: workDetail(), candidates: [] }
vi.mocked(http.get).mockResolvedValue({ data: resolved })
expect(await resolveBatchWork(resolved.batchKey, resolved.customerId)).toEqual(resolved)
expect(http.get).toHaveBeenCalledWith('/platform/v1/last-leg/appointment-work/items/resolve', { params: { batchKey: resolved.batchKey, customerId: resolved.customerId }, signal: undefined })
})
it('uses inclusive calendar dates and repeated type parameters with no duplicate API prefix', async () => {
vi.mocked(http.get).mockResolvedValue({ data: workCalendar })
const signal = new AbortController().signal
@@ -58,6 +58,7 @@ export type WorkCommandPayload =
| { command: 'ACCEPT_RETURN'; payload: { handoffVersion: number; note: string | null } }
export type WorkCommand = WorkCommandPayload & { expectedVersion: number; idempotencyKey: string }
export interface WorkCommandResult { item: WorkItem; affectedWorkItemKeys: string[] }
export interface BatchWorkResolution { batchKey: string; customerId: string | null; detail: WorkDetail | null; candidates: Array<{ customerId: string; workItemKey: string; batchNo: string | null }> }
const base = '/platform/v1/last-leg/appointment-work'
// Repeated types parameters are part of v1; Axios' default types[] syntax is not.
@@ -83,6 +84,9 @@ export async function getWorkItems(query: WorkItemsQuery, signal?: AbortSignal)
export async function getWorkDetail(key: string, signal?: AbortSignal) {
return unwrapApiResponse(await http.get<ApiEnvelope<WorkDetail>, ApiEnvelope<WorkDetail>>(`${base}/items/${encodeURIComponent(key)}`, { signal }))
}
export async function resolveBatchWork(batchKey: string, customerId?: string, signal?: AbortSignal) {
return unwrapApiResponse(await http.get<ApiEnvelope<BatchWorkResolution>, ApiEnvelope<BatchWorkResolution>>(`${base}/items/resolve`, { params: { batchKey, customerId }, signal }))
}
export async function submitWorkCommand(key: string, command: WorkCommand) {
return unwrapApiResponse(await http.post<ApiEnvelope<WorkCommandResult>, ApiEnvelope<WorkCommandResult>>(`${base}/items/${encodeURIComponent(key)}/commands`, command))
}
@@ -1,7 +1,7 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { ApiResponseError, http } from '@/shared/api/http'
import {
listTrips, getTrip, createTrip, updateTripPlan, assignTrip, bindTripDispatch, unbindTripDispatch, cancelTrip,
prepareTrip, listTrips, getTrip, createTrip, updateTripPlan, assignTrip, bindTripDispatch, unbindTripDispatch, cancelTrip,
getTripLoading, confirmTripLoading, getTripCompletion, completeTrip, releaseTripResource, listTripHistory, reviewTripDispatch, reviewTripLoading, getTripCapacityPlan, confirmTripCapacityPlan,
} from './trips'
@@ -14,7 +14,7 @@ const trip = { tripNo: 'TR/TEST', status: 'PLANNED', warehouseId: longId, wareho
plannedDepartureAt: '2026-10-02T10:00:00Z', expectedDriverEndAt: '2026-10-03T10:00:00Z', departedAt: null, completedAt: null,
stops: [{ name: '起运仓' }, { name: 'ONT8', destinationKey: 'FBA:ONT8' }], remark: null, updatedAt: '2026-10-02T08:00:00Z', vehicleRelease: null, driverRelease: null }
const reviewState = { status: 'PENDING', reason: null, reviewerId: null, reviewedAt: null, recordVersion: null }
const detail = { trip, driverQualification: null, loadingReview: reviewState, dispatches: [{ dispatchNo: 'DP-1', customerId: longId, packageCount: '12', boundBy: longId, boundAt: trip.updatedAt, review: reviewState }] }
const detail = { trip, driverQualification: null, previousDispatches: [], appointmentHistoryUnavailableReason: null, loadingReview: reviewState, dispatches: [{ appointmentBatches: [], dispatchNo: 'DP-1', customerId: longId, packageCount: '12', boundBy: longId, boundAt: trip.updatedAt, review: reviewState }] }
const cargo = { dispatchNo: 'DP-1', customerId: longId, dispatchItemId: longId, warehousePalletId: longId, palletNo: 'PALLET-1', packages: '12', destinationKey: 'FBA:ONT8', destinationLabel: 'ONT8' }
const load = { palletSpaces: '1', weightKg: '100.125', volumeCbm: '1.005' }
const confirmed = { manifestHash: 'a'.repeat(64), cargo: [cargo], pallets: [{ ...load, warehousePalletId: longId, deliveryIndex: '1' }],
@@ -113,3 +113,28 @@ describe('fleet trip API contract', () => {
await expect(cancelTrip(trip.tripNo, { recordVersion: 0, reason: '取消' })).rejects.toBe(conflict)
})
})
it('prepares the same trip from two real customer dispatches without issuing cargo creation or separate bind commands', async () => {
vi.mocked(http.post).mockResolvedValueOnce(envelope({ ...detail, dispatches: [{ ...detail.dispatches[0]!, dispatchNo: 'DS-60', customerId: 'customer-b', packageCount: '60' }, { ...detail.dispatches[0]!, dispatchNo: 'DS-40', customerId: 'customer-d', packageCount: '40' }] }))
const request = { tripNo: trip.tripNo, recordVersion: 4, plan: null, vehicleId: null, driverId: null, dispatchNos: ['DS-60', 'DS-40'], idempotencyKey: 'same-share-key' }
const value = await prepareTrip(request)
expect(http.post).toHaveBeenCalledExactlyOnceWith(`${base}/prepare`, request)
expect(value.dispatches.map(row => [row.dispatchNo, row.customerId, row.packageCount])).toEqual([['DS-60', 'customer-b', 60], ['DS-40', 'customer-d', 40]])
expect(http.get).not.toHaveBeenCalled()
})
it('preserves current and previous stable batch identities and normalizes only their numeric fields', async () => {
const reference = { batchKey: 'FBA_APPOINTMENT:9223372036854775801', batchNo: null, customerId: longId, sources: [{ sourceKey: 'ORDER:9223372036854775801', destinationKey: 'FBA:ONT8', packageCount: '40' }] }
vi.mocked(http.get).mockResolvedValueOnce(envelope({ ...detail, dispatches: [{ ...detail.dispatches[0]!, appointmentBatches: [reference] }], previousDispatches: [{ dispatchNo: 'DS-REMOVED', customerId: longId, recordVersion: '7', recordedAt: trip.updatedAt, appointmentBatches: [reference] }], appointmentHistoryUnavailableReason: '缺少部分历史来源' }))
const result = await getTrip(trip.tripNo)
expect(result.dispatches[0]!.appointmentBatches).toEqual([{ ...reference, sources: [{ ...reference.sources[0], packageCount: 40 }] }])
expect(result.previousDispatches[0]).toMatchObject({ dispatchNo: 'DS-REMOVED', customerId: longId, recordVersion: 7, appointmentBatches: result.dispatches[0]!.appointmentBatches })
expect(result.appointmentHistoryUnavailableReason).toBe('缺少部分历史来源')
})
it('rejects missing stable-reference arrays instead of silently falling back to legacy appointment numbers', async () => {
for (const invalid of [{ ...detail, previousDispatches: undefined }, { ...detail, dispatches: [{ ...detail.dispatches[0]!, appointmentBatches: undefined, fbaAppointmentNo: 'AP-OLD' }] }]) {
vi.mocked(http.get).mockResolvedValueOnce(envelope(invalid))
await expect(getTrip(trip.tripNo)).rejects.toThrow()
}
})
@@ -2,7 +2,7 @@ import { http, unwrapApiResponse, type ApiEnvelope } from '@/shared/api/http'
import { normalizeBooking, type WireBooking } from './tripBookings'
import type { PageResult } from './overseasMasterData'
import type {
FleetTrip, TripStatus, TripDetail, TripDraft, TripPlan, TripAssignment, TripBindingCommand, TripBinding,
TripPreviousDispatch, FleetTrip, TripStatus, TripDetail, TripDraft, TripPlan, TripAssignment, TripBindingCommand, TripBinding,
TripCargo, TripLoad, TripMeasurement, TripConfirmedLoad, TripLoading, TripLoadConfirmation,
TripOutcome, TripCompletionInspection, TripComplete, TripResourceRelease, TripHistory, TripReviewState, TripReviewCommand, TripCapacityPlanning,
} from '../tripTypes'
@@ -15,7 +15,8 @@ type WireTrip = Omit<FleetTrip, 'recordVersion' | 'maxPalletSpaces' | 'maxLoadKg
}
type WireReview = Omit<TripReviewState, 'recordVersion'> & { recordVersion: Numeric | null }
type WireBinding = Omit<TripBinding, 'packageCount' | 'review'> & { packageCount: Numeric; review: WireReview }
type WireDetail = Omit<TripDetail, 'trip' | 'dispatches' | 'loadingReview'> & { trip: WireTrip; dispatches: WireBinding[]; loadingReview: WireReview }
type WirePreviousDispatch = Omit<TripPreviousDispatch, 'recordVersion'> & { recordVersion: Numeric }
type WireDetail = Omit<TripDetail, 'trip' | 'dispatches' | 'loadingReview' | 'previousDispatches'> & { trip: WireTrip; dispatches: WireBinding[]; loadingReview: WireReview; previousDispatches: WirePreviousDispatch[] }
type WirePage<T> = { records: T[]; page: Numeric; size: Numeric; total: Numeric; pages: Numeric }
type WireCargo = Omit<TripCargo, 'packages'> & { packages: Numeric }
type WireLoad = { [K in keyof TripLoad]: Numeric }
@@ -49,8 +50,9 @@ const trip = (value: WireTrip): FleetTrip => ({ ...value, recordVersion: integer
maxPalletSpaces: value.maxPalletSpaces == null ? null : integer(value.maxPalletSpaces),
maxLoadKg: value.maxLoadKg == null ? null : number(value.maxLoadKg), maxVolumeCbm: value.maxVolumeCbm == null ? null : number(value.maxVolumeCbm) })
const review = (value: WireReview): TripReviewState => ({ ...value, recordVersion: value.recordVersion == null ? null : integer(value.recordVersion) })
const binding = (value: WireBinding): TripBinding => ({ ...value, packageCount: integer(value.packageCount), review: review(value.review) })
const detail = (value: WireDetail): TripDetail => ({ ...value, trip: trip(value.trip), dispatches: value.dispatches.map(binding), loadingReview: review(value.loadingReview) })
const batchReferences = (values: TripBinding['appointmentBatches']) => values.map(reference => ({ ...reference, sources: reference.sources.map(source => ({ ...source, packageCount: integer(source.packageCount) })) }))
const binding = (value: WireBinding): TripBinding => ({ ...value, packageCount: integer(value.packageCount), appointmentBatches: batchReferences(value.appointmentBatches), review: review(value.review) })
const detail = (value: WireDetail): TripDetail => ({ ...value, trip: trip(value.trip), dispatches: value.dispatches.map(binding), previousDispatches: value.previousDispatches.map(row => ({ ...row, recordVersion: integer(row.recordVersion), appointmentBatches: batchReferences(row.appointmentBatches) })), loadingReview: review(value.loadingReview) })
const cargo = (value: WireCargo): TripCargo => ({ ...value, packages: integer(value.packages) })
const outcome = (value: WireOutcome): TripOutcome => ({ ...value, packages: integer(value.packages),
signedPackages: integer(value.signedPackages), returnedPackages: integer(value.returnedPackages), remainingPackages: integer(value.remainingPackages) })
@@ -11,7 +11,7 @@ vi.mock('../api/tripHandovers', async original => ({ ...(await original<typeof a
vi.mock('../api/overseasMasterData', () => ({ listVehicles: vi.fn() }))
vi.mock('../api/drivers', () => ({ listDrivers: vi.fn() }))
const date = '2026-10-03T01:00:00Z'
const detail: TripDetail = { trip: { tripNo: 'TR-ONE', status: 'IN_TRANSIT', warehouseId: '1', warehouseCode: 'WH', warehouseName: '海外仓', vehicleId: '11', vehiclePlate: 'OLD-PLATE', driverId: '21', driverName: '原司机', driverPhone: 'phone', maxPalletSpaces: 2, maxLoadKg: 200, maxVolumeCbm: 4, plannedDepartureAt: date, expectedDriverEndAt: '2026-10-04T01:00:00Z', departedAt: date, completedAt: null, stops: [], remark: null, recordVersion: 7, updatedAt: date, vehicleRelease: null, driverRelease: null }, driverQualification: null, dispatches: [], loadingReview: { status: 'APPROVED', reason: null, reviewerId: null, reviewedAt: date, recordVersion: 7 } }
const detail: TripDetail = { trip: { tripNo: 'TR-ONE', status: 'IN_TRANSIT', warehouseId: '1', warehouseCode: 'WH', warehouseName: '海外仓', vehicleId: '11', vehiclePlate: 'OLD-PLATE', driverId: '21', driverName: '原司机', driverPhone: 'phone', maxPalletSpaces: 2, maxLoadKg: 200, maxVolumeCbm: 4, plannedDepartureAt: date, expectedDriverEndAt: '2026-10-04T01:00:00Z', departedAt: date, completedAt: null, stops: [], remark: null, recordVersion: 7, updatedAt: date, vehicleRelease: null, driverRelease: null }, driverQualification: null, previousDispatches: [], appointmentHistoryUnavailableReason: null, dispatches: [], loadingReview: { status: 'APPROVED', reason: null, reviewerId: null, reviewedAt: date, recordVersion: 7 } }
const previous = { vehicleId: '11', vehiclePlate: 'OLD-PLATE', driverId: '21', driverName: '原司机', driverPhone: 'phone' }
const replacement = { vehicleId: '12', vehiclePlate: 'NEW-PLATE', driverId: '22', driverName: '接替司机', driverPhone: 'phone' }
const load = { palletSpaces: 1, weightKg: 100, volumeCbm: 2 }
@@ -26,7 +26,7 @@ it('loads same-warehouse trips on demand and retries one immutable atomic prepar
select.vm.$emit('focus'); await flushPromises()
expect(listTrips).toHaveBeenCalledWith(expect.objectContaining({ warehouseId: '9007199254740993', status: 'PLANNED' }))
select.vm.$emit('update:modelValue', trip.tripNo); await flushPromises()
vi.mocked(prepareTrip).mockRejectedValueOnce(new Error('network')).mockResolvedValueOnce({ trip, dispatches: [], driverQualification: null, loadingReview: { status: 'PENDING', reason: null, reviewerId: null, reviewedAt: null, recordVersion: null } } as TripDetail)
vi.mocked(prepareTrip).mockRejectedValueOnce(new Error('network')).mockResolvedValueOnce({ trip, dispatches: [], driverQualification: null, previousDispatches: [], appointmentHistoryUnavailableReason: null, loadingReview: { status: 'PENDING', reason: null, reviewerId: null, reviewedAt: null, recordVersion: null } } as TripDetail)
const dialog=wrapper.findComponent({ name: 'AppDialog' })
dialog.vm.$emit('confirm'); await flushPromises()
const original=vi.mocked(prepareTrip).mock.calls[0]![0]
@@ -8,3 +8,5 @@ export { routeLocation, type RouteLocation } from './routeLocations'
export { default as TripPreparationDialog } from './components/TripPreparationDialog.vue'
export { default as TripDispatchSelector } from './components/TripDispatchSelector.vue'
export { listTripDispatchCandidates, prepareTrip, type TripPreparation, type DispatchCandidate } from './api/trips'
export type { TripPreviousDispatch } from './tripTypes'
@@ -1,6 +1,6 @@
<script setup lang="ts">
import '@/styles/adminDensity.css'
import { appointmentReturnTarget } from '@/modules/appointment-calendar'
import { appointmentReturnTarget, TripAppointmentPanel } from '@/modules/appointment-calendar'
import { inquiryReturnTarget } from '../inquiryNavigation'
import TripDispatchSelector from '../components/TripDispatchSelector.vue'
import { computed, onBeforeUnmount, ref, watch } from 'vue'
@@ -32,6 +32,8 @@ const route = useRoute(), router = useRouter(), access = useAccessPreviewStore()
const detail = ref<TripDetail | null>(null), loading = ref(false), error = ref<ApiErrorDetails | null>(null), operationError = ref<ApiErrorDetails | null>(null)
const activeTab = ref('overview'), editorOpen = ref(false), busy = ref(''), dispatchNo = ref('')
const offerSettingsOpen = ref(false)
const appointmentsOpen = ref(false)
const appointmentsPanel = ref<InstanceType<typeof TripAppointmentPanel> | null>(null)
const inspection = ref<TripCompletionInspection | null>(null), inspectionLoading = ref(false)
const history = ref<TripHistory[]>([]), historyPage = ref(1), historyTotal = ref(0), historyLoading = ref(false)
const resourceKind = ref<'VEHICLE' | 'DRIVER'>('VEHICLE'), actualEndAt = ref(new Date().toISOString()), endLocation = ref('')
@@ -65,9 +67,11 @@ function accept(value: TripDetail) {
if (value.trip.vehicleRelease && resourceKind.value === 'VEHICLE') resourceKind.value = 'DRIVER'
}
async function load() {
if (appointmentsPanel.value && !await appointmentsPanel.value.canLeave()) return
const current = ++generation; inspectionSequence++; historySequence++
loading.value = true; error.value = null; detail.value = null; operationError.value = null; activeTab.value = route.query.tab === 'loading' ? 'loading' : 'overview'
editorOpen.value = false; busy.value = ''; dispatchNo.value = ''; inspection.value = null; history.value = []; historyPage.value = 1
appointmentsOpen.value = false
completionRequest.value = null; releaseRequest.value = null; endLocation.value = ''
try { const result = await getTrip(String(route.params.tripNo)); if (current === generation) accept(result) }
catch (cause) { if (current === generation) error.value = getApiErrorDetails(cause, '车次详情加载失败') }
@@ -202,6 +206,10 @@ onBeforeUnmount(() => { generation++; inspectionSequence++; historySequence++ })
<DataTable :data="detail.dispatches" :columns="bindingsColumns" row-key="dispatchNo" empty-text="尚未关联排车单"><template #actions="{ row }"><div class="density-actions"><el-button v-if="access.can('platform:overseas-warehouse:dispatch:list')" class="density-action" @click="router.push({ name: 'overseas-dispatch-detail', params: { dispatchNo: row.dispatchNo } })">详情</el-button><el-button v-if="editable" class="density-action" data-tone="danger" :disabled="!!busy" @click="unbind(row.dispatchNo)">解除关联</el-button><el-button v-if="planned && access.can(permission.tripDispatchReview)" class="density-action" :disabled="!!busy || row.review.status === 'APPROVED'" @click="review('APPROVED', row.dispatchNo)">审核通过</el-button><el-button v-if="planned && access.can(permission.tripDispatchReview)" class="density-action" data-tone="danger" :disabled="!!busy" @click="review('REJECTED', row.dispatchNo)">打回</el-button></div></template><template #review="{ row }"><span>{{ tripReviewLabels[row.review.status as keyof typeof tripReviewLabels] }}</span><p v-if="row.review.reason">{{ row.review.reason }}</p><span v-if="row.review.reviewedAt">{{ time(row.review.reviewedAt) }}</span></template><template #boundAt="{ row }">{{ time(row.boundAt) }}</template></DataTable>
</FormSection>
</template>
<FormSection v-show="activeTab === 'overview'" v-if="access.can('platform:appointment:list')" class="density-form-section" title="客户预约与后送去向">
<el-button v-if="!appointmentsOpen" @click="appointmentsOpen = true">核对客户预约与后送去向</el-button>
<TripAppointmentPanel v-if="appointmentsOpen" ref="appointmentsPanel" :key="detail.trip.tripNo" :dispatches="detail.dispatches" :previous-dispatches="detail.previousDispatches" :history-unavailable-reason="detail.appointmentHistoryUnavailableReason" :can-write="planned && !busy" @updated="refreshLinked" @work="key => router.push({ path: '/appointment-calendar', query: { workItem: key } })" @external="path => router.push(path)" />
</FormSection>
<FormSection v-if="activeTab === 'bookings'" class="density-form-section" title="本车外接预订"><TripBookingPanel :key="detail.trip.tripNo" :trip="detail.trip" @changed="detail.trip.recordVersion = $event" @linked="refreshLinked" /></FormSection>
<FormSection v-if="activeTab === 'handovers'" class="density-form-section" title="在途车辆与司机交接"><TripHandoverPanel :key="detail.trip.tripNo" :detail="detail" @saved="refreshLinked" /></FormSection>
<FormSection v-if="activeTab === 'costs'" class="density-form-section" title="本趟直接成本"><TripCostPanel :key="detail.trip.tripNo" :trip-no="detail.trip.tripNo" /></FormSection>
@@ -22,7 +22,7 @@ const trip: FleetTrip = { tripNo: 'TR-TEST', status: 'PLANNED', warehouseId: '92
plannedDepartureAt: '2026-10-03T00:00:00Z', expectedDriverEndAt: '2026-10-04T00:00:00Z', departedAt: null, completedAt: null,
stops: [{ name: '起点' }, { name: 'ONT8', destinationKey: 'FBA:ONT8' }], remark: null, recordVersion: 3, updatedAt: '2026-10-02T00:00:00Z', vehicleRelease: null, driverRelease: null }
const reviewState = { status: 'PENDING' as const, reason: null, reviewerId: null, reviewedAt: null, recordVersion: null }
const detail: TripDetail = { trip, driverQualification: null, dispatches: [], loadingReview: reviewState }
const detail: TripDetail = { trip, driverQualification: null, previousDispatches: [], appointmentHistoryUnavailableReason: null, dispatches: [], loadingReview: reviewState }
const layout = { template: '<div><slot name="header"/><slot/></div>' }
const input = { name: 'ElInput', props: ['modelValue'], emits: ['update:modelValue'], template: '<input :value="modelValue" @input="$emit(\'update:modelValue\',$event.target.value)" />' }
const dialog = { name: 'AppDialog', props: ['modelValue'], emits: ['confirm'], template: '<div v-if="modelValue"><slot/><button @click="$emit(\'confirm\')">保存计划</button></div>' }
@@ -53,6 +53,18 @@ it('returns from a trip to the exact appointment work context and preserves it w
const page = mount(TripDetailView); await flushPromises(); await button(page, '返回预约工作').trigger('click')
expect(state.push).toHaveBeenLastCalledWith(tripQuery.appointmentReturn)
})
it('loads customer appointment cards only on request and navigates using a resolved work key', async () => {
const previousDispatches = [{ dispatchNo: 'DS-REMOVED', customerId: 'A', recordVersion: 2, recordedAt: trip.updatedAt, appointmentBatches: [] }]
vi.mocked(api.getTrip).mockResolvedValue({ ...structuredClone(detail), previousDispatches, appointmentHistoryUnavailableReason: '历史证据不完整' })
const page = mount(TripDetailView); await flushPromises()
expect(page.findComponent({ name: 'TripAppointmentPanel' }).exists()).toBe(false)
await button(page, '核对客户预约与后送去向').trigger('click'); await flushPromises()
const panel = page.getComponent({ name: 'TripAppointmentPanel' })
expect(panel.props()).toMatchObject({ previousDispatches, historyUnavailableReason: '历史证据不完整' })
expect(panel.props('dispatches')).toEqual([])
panel.vm.$emit('work', 'real-child-work'); await flushPromises()
expect(state.push).toHaveBeenLastCalledWith({ path: '/appointment-calendar', query: { workItem: 'real-child-work' } })
})
it('shows mixed signature and return quantities from one lazy completion read', async () => {
vi.mocked(api.getTrip).mockResolvedValue({ ...structuredClone(detail), trip: { ...trip, status: 'IN_TRANSIT' } })
@@ -129,7 +141,7 @@ it('counts a shared physical pallet once and submits only operator-entered measu
})
it('submits a specific dispatch review with optional approval notes and a reason when rejecting', async () => {
const pending: TripDetail = { ...structuredClone(detail), dispatches: [{ dispatchNo: 'DP-A', customerId: 'A', packageCount: 10, boundBy: '1', boundAt: trip.updatedAt, review: reviewState }] }
const pending: TripDetail = { ...structuredClone(detail), dispatches: [{ appointmentBatches: [], dispatchNo: 'DP-A', customerId: 'A', packageCount: 10, boundBy: '1', boundAt: trip.updatedAt, review: reviewState }] }
vi.mocked(api.getTrip).mockResolvedValue(pending)
vi.mocked(api.reviewTripDispatch).mockResolvedValue({ ...pending, trip: { ...trip, recordVersion: 4 } })
const wrapper = mount(TripDetailView); await flushPromises()
@@ -1,3 +1,4 @@
import type { DispatchBatchReference } from '@/modules/overseas-warehouse'
import type { TripBooking } from './bookingTypes'
import type { DriverQualification } from './driverTypes'
@@ -34,8 +35,9 @@ export interface FleetTrip {
export interface TripReviewState { status: 'PENDING' | 'APPROVED' | 'REJECTED'; reason: string | null; reviewerId: string | null; reviewedAt: string | null; recordVersion: number | null }
export interface TripReviewCommand { recordVersion: number; decision: 'APPROVED' | 'REJECTED'; reason?: string | null }
export const tripReviewLabels = { PENDING: '待审核', APPROVED: '已通过', REJECTED: '已打回' } as const
export interface TripBinding { dispatchNo: string; customerId: string; packageCount: number; boundBy: string; boundAt: string; review: TripReviewState }
export interface TripDetail { trip: FleetTrip; driverQualification: DriverQualification | null; dispatches: TripBinding[]; loadingReview: TripReviewState }
export interface TripPreviousDispatch { dispatchNo: string; customerId: string; recordVersion: number; recordedAt: string; appointmentBatches: DispatchBatchReference[] }
export interface TripBinding { appointmentBatches: DispatchBatchReference[]; dispatchNo: string; customerId: string; packageCount: number; boundBy: string; boundAt: string; review: TripReviewState }
export interface TripDetail { previousDispatches: TripPreviousDispatch[]; appointmentHistoryUnavailableReason: string | null; trip: FleetTrip; driverQualification: DriverQualification | null; dispatches: TripBinding[]; loadingReview: TripReviewState }
export interface TripDraft { warehouseId: string; plannedDepartureAt: string; expectedDriverEndAt: string; stops: TripStop[]; remark?: string | null; idempotencyKey: string }
export interface TripPlan { recordVersion: number; plannedDepartureAt: string; expectedDriverEndAt: string; stops: TripStop[]; remark?: string | null; reason: string }
export interface TripAssignment { recordVersion: number; vehicleId: string; driverId: string; reason: string }
@@ -97,7 +97,9 @@ export async function getBatchDispatchCandidates(batchKey: string) {
return unwrapApiResponse(await http.get<ApiEnvelope<BatchDispatchCandidates>, ApiEnvelope<BatchDispatchCandidates>>(`/platform/v1/last-leg/appointment-planning/batches/${encodeURIComponent(batchKey)}/dispatch-candidates`))
}
export interface DispatchBatchReference { batchKey: string; batchNo: string | null; customerId: string; sources: Array<{ sourceKey: string; destinationKey: string; packageCount: number }> }
export interface DispatchSummaryDto {
appointmentBatches: DispatchBatchReference[]
workflow?: DispatchWorkflow | null
id: string
dispatchNo: string
@@ -46,8 +46,8 @@ const expectedBatch = { draftToken: 'original-draft', groups: [
{ draftContainerId: 'container-1', planPalletIds: ['11', '13'], returnReceiptIds: [] },
{ draftContainerId: 'container-2', planPalletIds: ['14'], returnReceiptIds: ['22'] },
] }
const goodResult = [{ draftContainerId: 'container-2', dispatch: { id: '102', dispatchNo: 'DS-2' } },
{ draftContainerId: 'container-1', dispatch: { id: '101', dispatchNo: 'DS-1' } }]
const goodResult = [{ draftContainerId: 'container-2', dispatch: { id: '102', dispatchNo: 'DS-2', appointmentBatches: [] } },
{ draftContainerId: 'container-1', dispatch: { id: '101', dispatchNo: 'DS-1', appointmentBatches: [] } }]
async function submitDraft(wrapper: ReturnType<typeof mountDraft>) {
await wrapper.findAll('button').find(node => node.text() === '预排车')!.trigger('click')
await flushPromises()
@@ -70,7 +70,7 @@ it.each([
['foreign container', [{ ...goodResult[0], draftContainerId: 'foreign' }, goodResult[1]]],
['duplicate container', [goodResult[0], goodResult[0]]],
['duplicate dispatch', [goodResult[0], { ...goodResult[1], dispatch: goodResult[0].dispatch }]],
['missing business number', [goodResult[0], { ...goodResult[1], dispatch: { id: '101', dispatchNo: '' } }]],
['missing business number', [goodResult[0], { ...goodResult[1], dispatch: { id: '101', dispatchNo: '', appointmentBatches: [] } }]],
])('retains the original groups and token after %s', async (_label, result) => {
vi.mocked(listDispatchDrafts).mockResolvedValue([twoGroups])
vi.mocked(listDispatchCandidates).mockResolvedValue([plan, secondPlan, thirdPlan, returned])
@@ -115,7 +115,7 @@ it('submits relabel physical pallet identity without requiring an inbound plan p
{ id: 'container', capacity: 30, palletIds: ['101'] },
] }])
vi.mocked(listDispatchCandidates).mockResolvedValue([{ ...plan, planPalletId: null, sourceStage: 'RELABEL', orderRefs: 'RL-1' }])
vi.mocked(preArrangeDispatch).mockResolvedValue({ id: '1', dispatchNo: 'DS-1' })
vi.mocked(preArrangeDispatch).mockResolvedValue({ id: '1', dispatchNo: 'DS-1', appointmentBatches: [] })
const wrapper = mountDraft(); await flushPromises(); await submitDraft(wrapper)
expect(preArrangeDispatch).toHaveBeenCalledExactlyOnceWith({ planPalletIds: ['101'], returnReceiptIds: [], relabelNo: 'RL-1' })
expect(preArrangeDraftDispatch).not.toHaveBeenCalled()
@@ -197,7 +197,7 @@ it('keeps one complete relabel order on the single-dispatch endpoint', async ()
{ id: 'c1', capacity: 30, palletIds: ['11', '13'] },
] }])
vi.mocked(listDispatchCandidates).mockResolvedValue([plan, secondPlan].map(p => ({ ...p, sourceStage: 'RELABEL', orderRefs: 'RL-1' })))
vi.mocked(preArrangeDispatch).mockResolvedValue({ id: '1', dispatchNo: 'DS-RL' })
vi.mocked(preArrangeDispatch).mockResolvedValue({ id: '1', dispatchNo: 'DS-RL', appointmentBatches: [] })
const wrapper = mountDraft(); await flushPromises(); await submitDraft(wrapper)
expect(preArrangeDispatch).toHaveBeenCalledExactlyOnceWith({ planPalletIds: ['11', '13'], returnReceiptIds: [], relabelNo: 'RL-1' })
expect(preArrangeDraftDispatch).not.toHaveBeenCalled()
@@ -206,7 +206,7 @@ it('keeps one complete relabel order on the single-dispatch endpoint', async ()
})
it('retains every restored selection on candidate failure and submits both sources only after retry hydration', async () => {
vi.mocked(preArrangeDraftDispatch).mockResolvedValue([{ draftContainerId: 'container', dispatch: { id: '1', dispatchNo: 'DS-1' } }])
vi.mocked(preArrangeDraftDispatch).mockResolvedValue([{ draftContainerId: 'container', dispatch: { id: '1', dispatchNo: 'DS-1', appointmentBatches: [] } }])
vi.mocked(listDispatchDrafts).mockResolvedValue([{ draftToken: 'original-draft', containers: [{ id: 'container', capacity: 30, palletIds: ['11', 'RETURN:22'] }] }])
vi.mocked(listDispatchCandidates)
.mockResolvedValueOnce([plan])
+1 -1
View File
@@ -7,7 +7,7 @@ export { default as FbaAppointmentFields } from './components/FbaAppointmentFiel
export { createAppointmentForm, appointmentPayload, appointmentFormError } from './appointmentForm'
export { overseasWarehousePermissions } from './permissions'
export { getDispatch, getBatchDispatchCandidates, createDispatchDraftContainer, listDispatchDrafts, lockDispatchDraftPallet, preArrangeDraftDispatch, releaseDispatchDraft } from './api/dispatches'
export type { BatchDispatchCandidate, BatchDispatchCandidates, DispatchBatchAllocation, DispatchSummaryDto, PreArrangeDispatchDraftPayload } from './api/dispatches'
export type { DispatchBatchReference, BatchDispatchCandidate, BatchDispatchCandidates, DispatchBatchAllocation, DispatchSummaryDto, PreArrangeDispatchDraftPayload } from './api/dispatches'
export { dispatchVehicleSpecs } from './dispatchVehicleSpecs'
export { getContainerPlanProgress, getContainerInboundPlanPreview, convertLastMileContainerToInboundPlans } from './api/lastMileOrders'
export type { ContainerPlanProgressDetailDto, ContainerInboundPlanPreviewDto, ConvertContainerInboundPlanPayload } from './api/lastMileOrders'
@@ -15,7 +15,7 @@ describe('DispatchDetailView', () => {
routerPush.mockReset()
Object.keys(sourceQuery).forEach(key => delete sourceQuery[key])
vi.mocked(getDispatch).mockReset().mockResolvedValue({
id: '1', dispatchNo: 'PC/1', vehiclePlate: 'CA-100', driverName: '张师傅', status: 'PENDING_DEPARTURE',
id: '1', dispatchNo: 'PC/1', appointmentBatches: [], vehiclePlate: 'CA-100', driverName: '张师傅', status: 'PENDING_DEPARTURE',
route: 'LAX → ONT8', items: [{ id: '11', planPalletId: '20', orderNo: 'LM-1', warehousePalletId: '21', fbaWarehouseCode: 'ONT8', grossWeightKg: 88.5, volumeCbm: 1.25 }],
})
})
@@ -33,7 +33,7 @@ describe('DispatchDetailView', () => {
})
it('keeps related order weight unknown when one pallet lacks physical weight', async () => {
vi.mocked(getDispatch).mockResolvedValueOnce({ id: '1', dispatchNo: 'PC/1', status: 'PENDING_DEPARTURE', items: [
vi.mocked(getDispatch).mockResolvedValueOnce({ id: '1', dispatchNo: 'PC/1', appointmentBatches: [], status: 'PENDING_DEPARTURE', items: [
{ id: '11', planPalletId: '31', orderNo: 'LM-1', warehousePalletId: '21', grossWeightKg: 88.5, volumeCbm: 1 },
{ id: '12', planPalletId: '32', orderNo: 'LM-1', warehousePalletId: '22', grossWeightKg: null, volumeWeightKg: 999, volumeCbm: 1 },
] })
@@ -48,7 +48,7 @@ describe('DispatchesView', () => {
vi.stubGlobal('localStorage', memoryStorage())
vi.mocked(listDispatches).mockReset().mockResolvedValue({
records: [{
id: '190000000000000099', dispatchNo: 'PC-1', vehiclePlate: 'CA-100', driverName: '张师傅',
id: '190000000000000099', dispatchNo: 'PC-1', appointmentBatches: [], vehiclePlate: 'CA-100', driverName: '张师傅',
driverPhone: '555-0100', carrierName: 'Carrier A', orderNos: 'LM-1,LM-2', route: 'ONT8,LAX9',
overseasWarehouseId: '321', overseasWarehouseName: '洛杉矶仓', departAt: '2026-08-20T09:00:00', fbaAppointmentNo: 'FBA-1',
fbaAppointmentStatus: 'CONFIRMED', vehicleAppointmentStatus: 'BOOKED', estimatedArrivalAt: '2026-08-20T18:00:00',
@@ -219,7 +219,7 @@ describe('DispatchesView', () => {
it('keeps long dispatch identifiers as strings', async () => {
vi.mocked(listDispatches).mockResolvedValueOnce({
records: [{ id: '190000000000000099', dispatchNo: '190000000000000099' }],
records: [{ id: '190000000000000099', dispatchNo: '190000000000000099', appointmentBatches: [] }],
page: 1, size: 20, total: 1, pages: 1,
})
const wrapper = mount(DispatchesView, { global: { plugins: [createPinia(), ElementPlus] } })