WEB/src/views/order/orderManagement/utils/use-delivery-sub-waybill-print.ts
2026-09-01 19:26:55 +08:00

338 lines
12 KiB
TypeScript
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.

import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import {
getPrintDataByWaybillCodes,
type WavePlatformPrintDataPayload
} from '@/api/order.print/orderprint'
import { unwrapWavePlatformPrintPayload } from '@/views/order/waveOrder/config/wave-config'
import { orderDeliveryOrder } from '@/api/order.deliveryorder/orderdeliveryOrder'
import {
isOrderIndexApiSuccess,
parseOrderDetailPayload,
normalizeOrderExpressList
} from '../utils/order-index-helpers'
import { useUserStore } from '@/stores/modules/user'
type DeliverySubWaybillPrintRequestMeta = {
waybill_codes: string[]
order_ids: Array<number | string>
/** 仓库 ID(弹窗打印/解锁需要) */
warehouse_id?: number
}
/** 运单号选择项(来源于 order.deliveryOrder.detail 的运单信息) */
export type WaybillPrintOption = {
waybill_code: string
order_id: number | string
logistics_name: string
logistics_code: string
sys_logistics_name: string
business_key: string
is_main: boolean
}
type UseDeliveryOrderSubWaybillPrintOptions = {
getSelectionRows: () => any[]
onPrintSuccess?: () => void
emptySelectionMessage?: string
}
function isPrintApiSuccess(code: unknown) {
return code === undefined || code === null || code === 1 || code === 200 || code === 0
}
/** 从勾选的配送订单行收集订单 ID(row.id,正整数去重) */
function collectOrderIds(rows: any[]): number[] {
const ids: number[] = []
const seen = new Set<number>()
for (const row of rows || []) {
const id = Number(row?.id)
if (Number.isInteger(id) && id > 0 && !seen.has(id)) {
seen.add(id)
ids.push(id)
}
}
return ids
}
/**
* 按用户勾选的运单号过滤 waveGroups:
* - 第1层:按运单号过滤 orders(order 的运单号字段可能为 waybill_code/waybill_no/express_code/documentID)
* - 第2层:过滤"无波次无 ID"的空壳分组(wave_id 与 wave_no 均缺失,如 wave_id=0、wave_no="")
* 均带保护,避免结构不匹配时误删唯一数据源
*/
function filterWaveGroupsByWaybills(
waveGroups: unknown[] | undefined,
selectedSet: Set<string>
): unknown[] | undefined {
if (!Array.isArray(waveGroups) || !selectedSet.size) return waveGroups
// 只有 waveGroups 内 order 带运单号/documentID 字段时才过滤,避免结构不匹配导致打印丢失
const hasWaybillField = waveGroups.some((wave: any) =>
Array.isArray(wave?.platforms)
? wave.platforms.some((p: any) =>
Array.isArray(p?.orders)
? p.orders.some(
(o: any) =>
o && (o.waybill_code || o.waybill_no || o.express_code || o.documentID)
)
: false
)
: false
)
// 第1层:按勾选运单号过滤 orders(若 order 带运单号/documentID 字段)
let groups = waveGroups
if (hasWaybillField) {
groups = waveGroups
.map((wave: any) => {
if (!wave || typeof wave !== 'object') return wave
const platforms = Array.isArray(wave.platforms)
? wave.platforms
.map((p: any) => {
if (!p || typeof p !== 'object') return p
const orders = Array.isArray(p.orders)
? p.orders.filter((o: any) => {
if (!o || typeof o !== 'object') return false
const code = String(
o.waybill_code ?? o.waybill_no ?? o.express_code ?? o.documentID ?? ''
).trim()
return selectedSet.has(code)
})
: p.orders
return { ...p, orders }
})
.filter((p: any) => p && (!Array.isArray(p.orders) || p.orders.length > 0))
: wave.platforms
return { ...wave, platforms }
})
.filter(
(wave: any) => wave && (!Array.isArray(wave.platforms) || wave.platforms.length > 0)
)
// 保护:若过滤后一张面单都不剩(勾选运单号与返回结构完全不匹配),回退到原始数据避免误删
const remainingOrders = groups.reduce(
(total, w: any) =>
total +
(Array.isArray(w?.platforms)
? w.platforms.reduce(
(sum: number, p: any) =>
sum + (Array.isArray(p?.orders) ? p.orders.length : 0),
0
)
: 0),
0
)
if (remainingOrders === 0) groups = waveGroups
}
// 第2层:过滤"无波次无 ID"的空壳分组(wave_id 与 wave_no 均缺失)
// 仅当还存在"有波次信息"的合法分组时才过滤,避免把唯一数据源误删
const hasIdentifiedGroup = groups.some(
(w: any) => w && typeof w === 'object' && (w.wave_id || w.wave_no)
)
if (hasIdentifiedGroup) {
groups = groups.filter(
(w: any) => w && typeof w === 'object' && (w.wave_id || w.wave_no)
)
}
return groups
}
/**
* 配送订单「子单号打印」专用逻辑:
* 1. 勾选配送订单行 → 取订单 ID(row.id)
* 2. order.deliveryOrder.detail 获取该发货单号的运单号列表(配送模型,含子单/运单信息)
* 3. 用户选择要打印的运单号
* 4. order.print.getPrintDataByWaybillCodes 按选中的运单号获取打印数据
* 5. print.send / print.getList 弹窗内发送打印 / 打印台列表
*/
export function useDeliveryOrderSubWaybillPrint(options: UseDeliveryOrderSubWaybillPrintOptions) {
const userStore = useUserStore()
const dialogVisible = ref(false)
const loading = ref(false)
const errorMessage = ref('')
const payload = ref<WavePlatformPrintDataPayload | null>(null)
const requestMeta = ref<DeliverySubWaybillPrintRequestMeta | null>(null)
// 运单号选择对话框
const selectDialogVisible = ref(false)
const selectLoading = ref(false)
const waybillOptions = ref<WaybillPrintOption[]>([])
const selectedWaybills = ref<WaybillPrintOption[]>([])
const selectErrorMessage = ref('')
/** 当前选中的仓库 ID(弹窗打印/解锁需要) */
const currentWarehouseId = ref(0)
function resetState() {
payload.value = null
requestMeta.value = null
errorMessage.value = ''
waybillOptions.value = []
selectedWaybills.value = []
selectErrorMessage.value = ''
}
/** 点击「子单号打印」:收集订单 ID → order.deliveryOrder.detail 获取运单号列表 → 打开选择对话框 */
async function handlePrint() {
const rows = options.getSelectionRows()
if (!rows.length) {
ElMessage.warning(options.emptySelectionMessage || '请先勾选需要打印子单号的订单')
return
}
if (selectLoading.value || loading.value) return
const orderIds = collectOrderIds(rows)
if (!orderIds.length) {
ElMessage.warning('当前勾选记录缺少可用的订单 ID')
return
}
// 仓库 ID:优先取勾选行,其次当前登录用户上下文(与批量打印一致)
const warehouseId = Number(
rows[0]?.warehouse_id ?? userStore.user?.warehouse_id ?? userStore.user?.store_id
)
currentWarehouseId.value = Number.isFinite(warehouseId) && warehouseId > 0 ? warehouseId : 0
selectLoading.value = true
selectErrorMessage.value = ''
waybillOptions.value = []
selectedWaybills.value = []
try {
const list: WaybillPrintOption[] = []
const seen = new Set<string>()
for (const id of orderIds) {
const res: any = await orderDeliveryOrder.detail({ id, ids: [id], tableType: 'dispatch' })
if (!isOrderIndexApiSuccess(res)) continue
const data = parseOrderDetailPayload(res)
for (const item of normalizeOrderExpressList(data)) {
const code = item?.waybill_code
if (!code || seen.has(code)) continue
seen.add(code)
list.push({
waybill_code: code,
order_id: id,
logistics_name: item?.logistics_name || item?.sys_logistics_name || '',
logistics_code: item?.logistics_code || item?.sys_logistics_code || '',
sys_logistics_name: item?.sys_logistics_name || '',
business_key: String(item?.business_key ?? ''),
is_main: item?.is_main ?? false
})
}
}
if (!list.length) {
throw new Error('未从选中订单获取到运单号,请确认订单已分配快递号')
}
waybillOptions.value = list
selectDialogVisible.value = true
} catch (error: any) {
selectErrorMessage.value = error?.message || '获取运单号列表失败'
ElMessage.error(selectErrorMessage.value)
} finally {
selectLoading.value = false
}
}
/** 选择对话框勾选变化 */
function onSelectChange(rows: WaybillPrintOption[]) {
selectedWaybills.value = rows || []
}
/** 确认选中的运单号 → 按运单号获取打印数据并打开预览弹窗 */
async function confirmPrintWaybills() {
const codes = selectedWaybills.value.map((i) => i.waybill_code).filter(Boolean)
if (!codes.length) {
ElMessage.warning('请先选择要打印的运单号')
return
}
if (loading.value) return
const orderIds = waybillOptions.value.map((i) => i.order_id)
loading.value = true
errorMessage.value = ''
payload.value = null
try {
const res: any = await getPrintDataByWaybillCodes({ waybill_codes: codes })
if (!isPrintApiSuccess(res?.code)) {
throw new Error(res?.message || '获取打印数据失败')
}
const rawPayload = unwrapWavePlatformPrintPayload(res)
// 仅保留用户勾选的运单号对应的面单,避免后端按订单返回主单+子单多张被同时打印
rawPayload.waveGroups = filterWaveGroupsByWaybills(
rawPayload.waveGroups,
new Set(codes)
)
payload.value = rawPayload
requestMeta.value = {
waybill_codes: codes,
order_ids: orderIds,
warehouse_id: currentWarehouseId.value || undefined
}
selectDialogVisible.value = false
selectedWaybills.value = []
dialogVisible.value = true
ElMessage.success(res?.message || `已获取 ${codes.length} 个运单的打印数据`)
} catch (error: any) {
payload.value = null
errorMessage.value = error?.message || '获取打印数据失败'
dialogVisible.value = true
ElMessage.error(errorMessage.value)
} finally {
loading.value = false
}
}
/** 关闭选择对话框 */
function closeSelectDialog() {
selectDialogVisible.value = false
selectedWaybills.value = []
}
async function handleRefresh() {
const meta = requestMeta.value
if (!meta || !meta.waybill_codes.length) return
try {
const res: any = await getPrintDataByWaybillCodes({ waybill_codes: meta.waybill_codes })
if (!isPrintApiSuccess(res?.code)) {
throw new Error(res?.message || '刷新打印数据失败')
}
const rawPayload = unwrapWavePlatformPrintPayload(res)
// 与首次获取一致:过滤空壳分组与未勾选运单,避免刷新后多打"无波次无 ID"表单
rawPayload.waveGroups = filterWaveGroupsByWaybills(
rawPayload.waveGroups,
new Set(meta.waybill_codes)
)
payload.value = rawPayload
errorMessage.value = ''
} catch (error: any) {
payload.value = null
errorMessage.value = error?.message || '刷新打印数据失败'
ElMessage.error(errorMessage.value)
}
}
function onPrintSuccess() {
options.onPrintSuccess?.()
}
return {
dialogVisible,
loading,
errorMessage,
payload,
requestMeta,
resetState,
handlePrint,
handleRefresh,
onPrintSuccess,
selectDialogVisible,
selectLoading,
waybillOptions,
selectedWaybills,
selectErrorMessage,
onSelectChange,
confirmPrintWaybills,
closeSelectDialog
}
}