WEB/src/views/order/waveOrder/component/PendingOrderListPanel.vue
2026-06-26 16:11:03 +08:00

639 lines
20 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<template>
<div class="pending-order-panel">
<scan-box
ref="scanBox"
width="250px"
:tree-props="{ children: 'children', label: 'label' }"
:auto-submit="false"
:initial-conditions="initialConditions"
:preset-tree="presetTree"
:available-fields="availableFieldsRef"
@condition-change="handleConditionChange"
@reset="handleConditionReset"
@condition-clear="handleConditionClear"
/>
<div class="pending-order-panel__main">
<div class="pending-order-panel__toolbar">
<div class="pending-order-panel__toolbar-left">
<span class="pending-order-panel__wave">当前波次:{{ waveNo }}</span>
<el-button
size="small"
type="danger"
plain
:disabled="!hasSelection"
:loading="removeFromWaveLoading"
@click="handleRemoveOrdersFromWave"
>
移出波次
</el-button>
<order-toolbar-button-group
:buttons="toolbarButtons"
:resolve-disabled="resolveButtonDisabled"
:resolve-loading="resolveButtonLoading"
:resolve-label="resolveButtonLabel"
:layout-key="toolbarLayoutKey"
@action="handleToolbarButtonClick"
/>
</div>
<div class="pending-order-panel__toolbar-right">
<el-input v-model="quickSearch" size="small" placeholder="搜索订单号" style="width: 220px" @keyup.enter="onQuickSearch" />
</div>
</div>
<upper-table
ref="upperTable"
title="待处理订单列表"
default-align="center"
:enable-column-config="true"
table-id="wave-pending-order-dialog"
:data="list"
:columns="columns"
:table-size="tableSize"
:pagination="pagination"
:show-index="true"
:show-selection="true"
:loading="loading"
:queryTime="queryTime"
@page-change="handlePageChange"
@page-size-change="handlePageSizeChange"
@refresh="loadData"
@selection-change="onSelectionChange"
>
<template #column-status="{ row }">
<el-tag :type="getTagType('status', row.status)" size="small">
{{ translateOrderField('status', row.status) }}
</el-tag>
</template>
<template #column-is_urgency="{ row }">
<el-tag :type="getTagType('is_urgency', row.is_urgency)" size="small">
{{ translateOrderField('is_urgency', row.is_urgency) }}
</el-tag>
</template>
<template #column-post_status="{ row }">
<el-tag :type="getTagType('post_status', row.post_status)" size="small">
{{ translateOrderField('post_status', row.post_status) }}
</el-tag>
</template>
<template #column-storage_status="{ row }">
<el-tag :type="getTagType('storage_status', row.storage_status)" size="small">
{{ translateOrderField('storage_status', row.storage_status) }}
</el-tag>
</template>
<template #column-print_status="{ row }">
<el-tag :type="getTagType('print_status', row.print_status)" size="small">
{{ translateOrderField('print_status', row.print_status) }}
</el-tag>
</template>
<template #column-pick_status="{ row }">
<el-tag :type="getTagType('pick_status', row.pick_status)" size="small">
{{ translateOrderField('pick_status', row.pick_status) }}
</el-tag>
</template>
<template #column-pack_status="{ row }">
<el-tag :type="getTagType('pack_status', row.pack_status)" size="small">
{{ translateOrderField('pack_status', row.pack_status) }}
</el-tag>
</template>
<template #column-sync_status="{ row }">
<el-tag :type="getTagType('sync_status', row.sync_status)" size="small">
{{ translateOrderField('sync_status', row.sync_status) }}
</el-tag>
</template>
<template #empty>
<div class="empty-tip">暂无待处理订单</div>
</template>
</upper-table>
</div>
<allocate-express-form
v-model="allocateDialogVisible"
:loading="allocateLoading"
@closed="resetAllocateDialog"
@submit="submitAllocateExpress"
/>
<storage-allocate-form
v-model="storageDialogVisible"
v-model:allow-storage-location="storageForm.allowStorageLocation"
:mode="storageDialogMode"
:order-count="storagePendingOrderIds.length"
:loading="storageAllocateLoading"
:request-id="storageAllocateRequestId"
:task-status="storageAllocateTaskStatus"
:progress-percent="storageAllocateProgressPercent"
:total-count="storageAllocateTotalCount"
:success-count="storageAllocateSuccessCount"
:failed-count="storageAllocateFailedCount"
:message="storageAllocateMessage"
@closed="resetStorageAllocateDialog"
@submit="submitStorageAllocate"
/>
<sync-order-ids-form
v-model="syncOrderIdsDialogVisible"
:order-count="selectionRows.length"
:loading="syncOrderIdsLoading"
@closed="resetSyncOrderIdsDialog"
@submit="submitSyncOrderIds"
/>
<manual-waybill-form
v-model="manualWaybillDialogVisible"
v-model:waybill-code="manualWaybillForm.waybill_code"
:loading="manualWaybillLoading"
:order-id="manualWaybillOrderId"
:order-code="manualWaybillOrderCode"
@closed="resetManualWaybillDialog"
@submit="submitManualWaybill"
/>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import ScanBox from '@/components/ScanBox/index.vue'
import UpperTable from '@/components/UpperTable/index.vue'
import { orderPendingOrder } from '@/api/order.pendingorder/orderpendingOrder'
import { orderWaveBatchRemoveOrders } from '@/api/order.wave/orderwave'
import * as indexApi from '@/api/index/index'
import AllocateExpressForm from '@/views/order/orderManagement/form/AllocateExpressForm.vue'
import StorageAllocateForm from '@/views/order/orderManagement/form/StorageAllocateForm.vue'
import SyncOrderIdsForm from '@/views/order/orderManagement/form/SyncOrderIdsForm.vue'
import ManualWaybillForm from '@/views/order/orderManagement/form/ManualWaybillForm.vue'
import OrderToolbarButtonGroup from '@/views/order/orderManagement/component/OrderToolbarButtonGroup.vue'
import { createPendingToolbarController } from '@/views/order/orderManagement/utils/toolbar-actions'
import { buildOrderWhereConditions, sanitizeOrderListWhere } from '@/views/order/orderManagement/utils/order-index-helpers'
import {
pendingCloums,
pendingAvailableFields,
pickToolbarButtons,
type ToolbarButtonConfig,
translateOrderField,
getTagType,
fillExpressCompanyScanFieldOptions
} from '@/views/order/orderManagement/config/order-common-config'
const props = defineProps<{
waveNo: string
}>()
const scanBox = ref<any>(null)
const upperTable = ref<any>(null)
const presetTree = ref<any[]>([])
const availableFieldsRef = reactive(
JSON.parse(JSON.stringify(pendingAvailableFields.filter((field: any) => field.value !== 'wave_no')))
)
const toolbarButtons = pickToolbarButtons(['refresh', 'columnConfig', 'allocateStorage', 'allocateExpress', 'manualWaybill', 'syncOrderIds'])
const list = ref<any[]>([])
const loading = ref(false)
const queryTime = ref(0)
const tableSize = ref('small')
const columns = ref(pendingCloums)
const selectionRows = ref<any[]>([])
const hasSelection = ref(false)
const quickSearch = ref('')
const pagination = reactive({ currentPage: 1, pageSize: 20, total: 0 })
const actionLoading = ref(false)
const removeFromWaveLoading = ref(false)
const expressCodeOptions = ref<Array<{ label: string; value: string }>>([])
const platformCodeOptions = ref<Array<{ label: string; value: string }>>([])
const initialConditions = computed(() => ({
type: 'custom',
conditions: {
wave_no: {
field: 'wave_no',
type: 'text',
operator: 'eq',
value: props.waveNo
}
}
}))
onMounted(() => {
loadData()
loadOrderMetaOptions()
loadStoreOptions()
})
watch(() => props.waveNo, () => {
pagination.currentPage = 1
loadData()
})
function normalizePositiveIntId(raw: unknown): number | null {
if (raw === undefined || raw === null || raw === '') return null
const n = typeof raw === 'number' ? raw : Number(raw)
if (!Number.isInteger(n) || n <= 0) return null
return n
}
async function loadData() {
if (loading.value) return
loading.value = true
const start = Date.now()
let where = buildOrderWhereConditions(scanBox.value?.getConditions?.() || {})
where.wave_no = {
operator: 'eq',
value: props.waveNo,
type: 'text'
}
if (quickSearch.value) {
where.delivery_order_code = {
operator: 'like',
value: quickSearch.value,
type: 'text'
}
}
where = sanitizeOrderListWhere(where)
try {
const res = await orderPendingOrder.list({
pagination: {
page: pagination.currentPage,
pageSize: pagination.pageSize
},
where,
sort: {
sortField: 'updated_at',
sortOrder: 'DESC' as const
}
})
if (res && (res.code === 1 || res.code === 200) && res.data) {
list.value = res.data.list || []
pagination.total = res.data.pagination?.total || res.data.total || 0
} else {
list.value = []
pagination.total = 0
}
} catch {
list.value = []
pagination.total = 0
ElMessage.error('获取待处理订单列表失败')
} finally {
loading.value = false
queryTime.value = Date.now() - start
}
}
function onSelectionChange(rows: any[]) {
selectionRows.value = rows || []
hasSelection.value = selectionRows.value.length > 0
}
function handleConditionChange() {
pagination.currentPage = 1
loadData()
}
function handleConditionClear() {
pagination.currentPage = 1
loadData()
}
function handleConditionReset() {
pagination.currentPage = 1
scanBox.value?.reset?.()
loadData()
}
function handlePageChange(page: number) {
pagination.currentPage = page
loadData()
}
function handlePageSizeChange(size: number) {
pagination.pageSize = size
pagination.currentPage = 1
loadData()
}
function onQuickSearch() {
pagination.currentPage = 1
loadData()
}
function openColumnConfigPanel() {
upperTable.value?.openColumnConfig?.()
}
function getSelectedIds(): number[] {
const ids: number[] = []
for (const item of selectionRows.value) {
const n = normalizePositiveIntId(item?.id)
if (n !== null) ids.push(n)
}
return ids
}
const {
actionMap,
dialogState: {
allocateDialogVisible,
allocateLoading,
storageDialogVisible,
storageDialogMode,
storagePendingOrderIds,
storageAllocateLoading,
storageForm,
storageAllocateRequestId,
storageAllocateTaskStatus,
storageAllocateProgressPercent,
storageAllocateTotalCount,
storageAllocateSuccessCount,
storageAllocateFailedCount,
storageAllocateMessage,
syncOrderIdsDialogVisible,
syncOrderIdsLoading,
manualWaybillDialogVisible,
manualWaybillLoading,
manualWaybillOrderId,
manualWaybillOrderCode,
manualWaybillForm
},
submitStorageAllocate,
submitAllocateExpress,
submitSyncOrderIds,
submitManualWaybill,
resetAllocateDialog,
resetStorageAllocateDialog,
resetSyncOrderIdsDialog,
resetManualWaybillDialog
} = createPendingToolbarController({
loadData,
handleExport: async () => {},
openColumnConfigPanel,
toggleDetailVisible: () => {},
openCreateOrderDialog: () => {},
getSelectedRows: () => selectionRows.value,
getSelectedIds,
pendingApi: orderPendingOrder,
actionLoading,
clearSelection: () => {
upperTable.value?.clearSelection?.()
selectionRows.value = []
hasSelection.value = false
},
expressCodeOptions,
platformCodeOptions
})
function resolveButtonLoading(loadingKey?: string) {
if (!loadingKey) return false
const loadingMap: Record<string, boolean> = {
actionLoading: actionLoading.value,
storageAllocateLoading: storageAllocateLoading.value,
allocateLoading: allocateLoading.value,
syncOrderIdsLoading: syncOrderIdsLoading.value,
manualWaybillLoading: manualWaybillLoading.value
}
return Boolean(loadingMap[loadingKey])
}
function resolveButtonDisabled(disabledKey?: string) {
if (!disabledKey) return false
const disabledMap: Record<string, boolean> = {
hasNoSelection: !hasSelection.value,
notSingleSelection: selectionRows.value.length !== 1
}
return Boolean(disabledMap[disabledKey])
}
function resolveButtonLabel(defaultLabel: string) {
if (defaultLabel === '录入运单号') return '手工分配快递号'
return defaultLabel
}
const toolbarLayoutKey = computed(() =>
JSON.stringify({
disabled: {
hasNoSelection: !hasSelection.value,
notSingleSelection: selectionRows.value.length !== 1
},
loading: {
actionLoading: actionLoading.value,
storageAllocateLoading: storageAllocateLoading.value,
allocateLoading: allocateLoading.value,
syncOrderIdsLoading: syncOrderIdsLoading.value,
manualWaybillLoading: manualWaybillLoading.value
}
})
)
function handleToolbarButtonClick(action: ToolbarButtonConfig['action']) {
const handler = actionMap[action]
if (!handler) return
void handler()
}
async function handleRemoveOrdersFromWave() {
const ids = getSelectedIds()
if (!ids.length) {
ElMessage.warning('请先勾选需要移出波次的订单')
return
}
if (removeFromWaveLoading.value) return
try {
await ElMessageBox.confirm(
`确定将选中的 ${ids.length} 条订单移出当前波次吗?`,
'移出波次',
{ type: 'warning', confirmButtonText: '确认移出', cancelButtonText: '取消' }
)
} catch {
return
}
removeFromWaveLoading.value = true
try {
const res = await orderWaveBatchRemoveOrders({ ids })
const ok = res && (res.code === 1 || res.code === 200 || res.flag === 'success')
if (!ok) {
ElMessage.error(res?.message || '移出波次失败')
return
}
const payload = res?.data && typeof res.data === 'object' && !Array.isArray(res.data) ? res.data : res
const removedCount = Number(payload?.removed_order_count ?? ids.length) || ids.length
ElMessage.success(`${res?.message || '移出波次成功'} ${removedCount} 条`)
upperTable.value?.clearSelection?.()
selectionRows.value = []
hasSelection.value = false
await loadData()
} catch (error: any) {
ElMessage.error(error?.message || '移出波次失败')
} finally {
removeFromWaveLoading.value = false
}
}
function normalizeCode(value: unknown) {
return String(value ?? '').trim()
}
function mapCodeOptions(rawList: any[], codeKeys: string[], nameKeys: string[]) {
const result: Array<{ label: string; value: string }> = []
const seen = new Set<string>()
for (const item of rawList || []) {
const code = normalizeCode(codeKeys.map((key) => item?.[key]).find((v) => v !== undefined && v !== null && v !== ''))
if (!code || seen.has(code)) continue
const name = normalizeCode(nameKeys.map((key) => item?.[key]).find((v) => v !== undefined && v !== null && v !== ''))
result.push({ value: code, label: name ? `${code} - ${name}` : code })
seen.add(code)
}
return result
}
function mapNameOptions(rawList: any[], nameKeys: string[]) {
const result: Array<{ label: string; value: string }> = []
const seen = new Set<string>()
for (const item of rawList || []) {
const name = normalizeCode(nameKeys.map((key) => item?.[key]).find((v) => v !== undefined && v !== null && v !== ''))
if (!name || seen.has(name)) continue
result.push({ value: name, label: name })
seen.add(name)
}
return result
}
/** 与 pendingOrder / deliveryOrder 等页一致:兼容 data 为数组、{ list }、顶层 list */
function unwrapIndexListResponse(res: any): any[] {
const payload = res?.data !== undefined ? res.data : res
if (Array.isArray(payload)) return payload
if (payload && typeof payload === 'object') {
if (Array.isArray(payload.list)) return payload.list
if (Array.isArray(payload.items)) return payload.items
if (Array.isArray(payload.records)) return payload.records
}
if (Array.isArray(res?.list)) return res.list
return []
}
async function loadOrderMetaOptions() {
try {
const [expressRes, platformRes] = await Promise.all([
indexApi.getExpressList({}),
indexApi.getPlatformList({})
])
const expressRaw = unwrapIndexListResponse(expressRes)
const platformRaw = unwrapIndexListResponse(platformRes)
expressCodeOptions.value = mapCodeOptions(expressRaw, ['code', 'logistics_code', 'express_code'], ['name', 'logistics_name', 'express_name'])
platformCodeOptions.value = mapCodeOptions(platformRaw, ['code', 'platform_code'], ['name', 'platform_name'])
const logisticsField = availableFieldsRef.find((item: any) => item.value === 'logistics_name')
if (logisticsField) {
logisticsField.options = mapNameOptions(expressRaw, ['name', 'logistics_name', 'express_name', 'label'])
}
fillExpressCompanyScanFieldOptions(availableFieldsRef as any[], expressRaw)
const platformField = availableFieldsRef.find((item: any) => item.value === 'sys_platform_name')
if (platformField) {
platformField.options = mapNameOptions(platformRaw, ['name', 'platform_name', 'sys_platform_name', 'label'])
}
} catch {
expressCodeOptions.value = []
platformCodeOptions.value = []
const logisticsField = availableFieldsRef.find((item: any) => item.value === 'logistics_name')
if (logisticsField) logisticsField.options = []
fillExpressCompanyScanFieldOptions(availableFieldsRef as any[], [])
const platformField = availableFieldsRef.find((item: any) => item.value === 'sys_platform_name')
if (platformField) platformField.options = []
}
}
function normalizeStoreOptions(rawStores: any[]) {
const result: Array<{ label: string; value: number | string }> = []
const seen = new Set<string>()
for (const item of rawStores || []) {
const rawValue = item?.value ?? item?.store_id ?? item?.id ?? item?.storeId
if (rawValue === undefined || rawValue === null || rawValue === '') continue
const value = Number.isNaN(Number(rawValue)) ? String(rawValue) : Number(rawValue)
const key = String(value)
if (seen.has(key)) continue
const label = String(item?.label ?? item?.store_name ?? item?.name ?? item?.storeName ?? key).trim() || key
result.push({ label, value })
seen.add(key)
}
return result
}
async function loadStoreOptions() {
try {
const storesRes: any = await indexApi.loadStores({ type: 'order' })
const rawStores = storesRes?.stores || storesRes?.data?.stores || storesRes?.data || []
const storeField = availableFieldsRef.find((item: any) => item.value === 'store_id')
if (storeField) {
storeField.options = normalizeStoreOptions(rawStores)
}
} catch {
const storeField = availableFieldsRef.find((item: any) => item.value === 'store_id')
if (storeField) storeField.options = []
}
}
</script>
<style scoped lang="scss">
.pending-order-panel {
display: flex;
gap: 12px;
height: 72vh;
min-height: 560px;
}
.pending-order-panel__main {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 12px;
}
.pending-order-panel__toolbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 10px 12px;
background: #f8fafc;
border: 1px solid #ebeef5;
border-radius: 6px;
}
.pending-order-panel__toolbar-left {
flex: 1;
min-width: 0;
display: flex;
align-items: center;
gap: 8px;
overflow: hidden;
}
.pending-order-panel__toolbar-right {
flex-shrink: 0;
}
.pending-order-panel__wave {
font-size: 13px;
color: #606266;
margin-right: 6px;
}
:deep(.upper-table-container) {
flex: 1;
min-height: 0;
}
:deep(.scan-box-container) {
flex: 0 0 250px;
}
</style>