diff --git a/docs/B2B订单-批量打印拣货单-设计与实施.md b/docs/B2B订单-批量打印拣货单-设计与实施.md new file mode 100644 index 00000000..4d04c514 --- /dev/null +++ b/docs/B2B订单-批量打印拣货单-设计与实施.md @@ -0,0 +1,138 @@ +# B2B 订单「批量打印拣货单」设计与实施 + +> 需求:给 `order/orderManagement` 的两个 B2B 页签(**待处理B2B订单** / **配送B2B订单**)加上 +> 与 `order/waveOrder` 一致的「批量打印拣货单」,但**数据取订单管理表格数据,不走波次数据**。 + +## 一、范围与入口 + +| 页面 | 组件 | 页签 | 按钮 | +| --- | --- | --- | --- | +| `/order/orderManagement?tab=pendingOrder2b` | `views/order/orderManagement/pendingOrder2b.vue` → `pendingOrder.vue`(`b2b`) | 待处理B2B订单 | 工具栏「批量打印拣货单」 | +| `/order/orderManagement?tab=deliveryOrder2b` | `views/order/orderManagement/deliveryOrder2b.vue` → `deliveryOrder.vue`(`b2b`) | 配送B2B订单 | 同上 | + +按钮定义:`config/order-common-config.ts` → `ORDER_TOOLBAR_BUTTONS.b2bPickingPrint`, +并加入 `b2bToolbarButtonKeys`(仅 `buildB2bToolbarButtons()` 追加,普通订单页不出现)。 + +## 二、数据来源(与波次拣货单的区别) + +| 项 | 波次拣货单(`order/waveOrder`) | 本次 B2B 订单拣货单 | +| --- | --- | --- | +| 打印队列 | 勾选的**波次**(一行=一个波次) | 勾选的**订单**(一行=一张拣货单) | +| 队列号 | `wave_no` | `delivery_order_code` | +| 单据头 | 波次内首个订单 + `wave_no` | 该订单行字段(**运单号** / 平台 / 物流公司 / 创建时间 / 备注) | +| 明细表 | 波次内**订单列表**(订单号/物流单号/收件人/件数/省份) | 该订单的**商品明细**(`order.getB2bPackingSnapshot`) | +| 数据请求 | `order.pendingOrder.list`(按 `wave_id in`) | 无列表请求,直接用表格勾选行 + 逐单查快照 | + +明细字段映射(`details[i]`): + +| 模板 field_code | 来源 | +| --- | --- | +| `item_code` | `items[].item_code`(回退 `item_snapshot.item_code`) | +| `item_name` | `items[].item_name`(回退 `item_snapshot.item_name`) | +| `plan_qty` | `items[].plan_qty`(应拣数量) | +| `pick_locations_text` | `items[].pick_locations` 拼成 `E2区24-05-01×24,E2区24-02-02×72`,无储位为空 | + +实现:`views/order/orderManagement/utils/use-b2b-picking-print.ts` +→ 打开 `components/BatchReceivingPrintDialog.vue`(`business-type="PICKING"`, +`queue-no-field="delivery_order_code"`,`document-label="订单"`,`fetch-print-data` 逐单装配数据,按 order_id 缓存)。 + +### 单据头「运单号」(2026-11-20 调整) + +- 模板单据头的 `waybill_text` 由 `resolveB2bWaybillText(row)` 生成: + `waybill_codes` → `express_numbers` → `waybill_code/waybill_no` → `expresses[].waybill_code`, + 数组/JSON 字符串统一归一化为 `A, B`。 +- **不再使用 `delivery_order_code`(发货单号)作为单据头单号**;`delivery_order_code` 只用于弹窗左侧打印队列的单号显示。 +- 模板单据头的 `logistics_text` 由 `resolveB2bLogisticsText(row)` 生成: + B2B 列表实测 `sys_logistics_name` 为 **null**(只有 `logistics_name` 有值,如「其他」「顺丰空运」), + 因此按「系统快递 → 快递」回退;直接绑 `sys_logistics_name` 会印出空白。 +- 同页两个 B2B 页签的表格列名统一为「运单号」: + - 待处理B2B:`express_numbers` 列改名为「运单号」(`buildPendingB2bColumns()` 内改名,非 B2B 页签仍是「快递单号」) + - 配送B2B:本来就是「运单号」(`waybill_codes`) + +## 三、打印模板改造(生产库已完成) + +`wms.wms.gztbyc.com` · `wms_print_template` · **id = 17** + +| 项 | 改造前 | 改造后 | +| --- | --- | --- | +| template_name | 拣货单模板 | **B2B订单拣货单** | +| business_type | PICKING | PICKING(不变) | +| 页面尺寸 | 148×210 | 148×210(不变) | +| 内容 | 备货单版式(备货单标题 + 订单号/物流单号/件数/重量/省份表) | 拣货单版式(**运单号**/平台/物流公司/创建时间 + 商品条码/商品名称/应拣数量/取货储位) | + +> 注意:后端限制「同一业务类型 + 平台只能有一个自定义模板」,`setting.printTemplate.create` 会返回 +> `409 同一业务类型和平台下已存在自定义模板`,因此**只能改写 id=17**(该模板 `editable:true`,`warehouse_id=1000028`)。 +> 通用模板 id=16「拣货单」保持原样,继续给波次拣货单使用(`warehouse_id IS NULL`,接口不可写)。 + +新模板版式(148×210,页边距 10mm,内容宽 128mm): + +| 元素 | top | left | 宽×高 | 字段 | +| --- | --- | --- | --- | --- | +| 标题「拣 货 单」18pt 粗居中 | 6 | 0 | 148×10 | — | +| 横线 | 17.5 | 10 | 128×1 | — | +| 运单号: / 值 13pt 粗 | 21 | 10 / 30 | 20 / 58×7 | `waybill_text` | +| 平台: / 值 | 21 | 90 / 102 | 12 / 36×7 | `sys_platform_name` | +| 运单号条码(Code128) | 29 | 94 | 44×10 | `waybill_text` | +| 物流公司: / 值 | 30 | 10 / 34 | 24 / 56×7 | `logistics_text` | +| 创建时间: / 值 | 39 | 10 / 34 | 24 / 56×7 | `create_at` | +| 横线 | 48 | 10 | 128×1 | — | +| 「商品明细」12pt 粗 | 51 | 10 | 60×8 | — | +| 表格 | 61 | 10 | 128×(行高6/表头6) | 见下 | +| 横线 | 176 | 10 | 128×1 | — | +| 备注: / 值(自动换行) | 179 | 10 / 24 | 14 / 114×10 | `remark` | +| 打印时间: / 值 | 191 | 10 / 34 | 24 / 46×6 | `print_time` | +| 拣货人: + 签字线 | 199 / 205 | 10 | 20 / 38 | — | +| 复核人: + 签字线 | 199 / 205 | 68 | 20 / 34 | — | + +表格列(合计 128mm):商品条码 30 `item_code` / 商品名称 38 `item_name` / +应拣数量 22 `plan_qty` / 取货储位 38 `pick_locations_text`。 + +> 「应拣数量」列曾用 16mm 导致表头折行(第 2 行被行高压掉),已加宽到 22mm。 + +分页:`utils/printPaginate.ts` 按「表格后最近的 text 元素 top」切页 → 本模板为备注 179mm, +`距底部留白 = 210 - (179 - 2) = 33mm`,每页约 18 行商品,第 2 页起重复表头。 + +## 四、弹窗默认选中模板 + +`BatchReceivingPrintDialog` 新增 `default-template-name` 属性:模板列表加载完且用户未选模板时, +按名称匹配预选(同名优先,其次包含匹配)。两个 B2B 页传 `'B2B订单拣货单'` +(不用硬编码模板 ID,开发/生产 ID 不同也能命中)。 + +## 五、使用流程 + +1. `订单 → 订单管理 → 待处理B2B订单 / 配送B2B订单` +2. 勾选一张或多张订单 → 工具栏「批量打印拣货单」 +3. 弹窗左侧为打印队列(单号为 `delivery_order_code`),右侧预览,默认模板为「B2B订单拣货单」 +4. 选打印台 → 打印机 → 「打印当前单据 / 打印并切换下一个」(或「浏览器打印」) + +## 六、回滚 + +1. 前端:从 `b2bToolbarButtonKeys` 移除 `b2bPickingPrint`(或直接还原 + `pendingOrder.vue` / `deliveryOrder.vue` 的 `` 与 actionMap 绑定)。 +2. 模板:id=17 原内容为「备货单」版式(25 个元素,148×210), + 如需恢复请在「打印模板」页面用模板元素手动重建,或执行: + +```sql +-- 备份(改造后) +SELECT id, template_name, page_width, page_height, template_content +FROM wms_print_template WHERE id = 17; +``` + +> 备货单版式在开发库同样可由 `docs/拣货单模板-148x210.md` 的「备货单」描述重建; +> 生产改造前的 `template_content` 未留存完整副本(改造前即「拣货单模板」名下挂着备货单内容的不一致状态)。 + +## 七、已知限制 + +- ⚠️ **弹窗被 `v-if` 懒挂载时的初始化坑(本次已修)**:`v-if` 打开时才挂载组件, + `modelValue` 初值即为 `true`,而组件内 `watch(() => props.modelValue)` 默认不对初值触发 + → `initDialog()` 不执行 → **打印台/模板下拉为空**。 + 修复:watcher 加 `{ immediate: true }`;同时把 `loadPrintOptions()` 里模板列表与打印台接口拆成两个 try(模板优先), + 避免打印台接口异常连带清空模板下拉。 +- `order.getB2bPackingSnapshot` 为 B2B 备货口径接口(当前仓库 + B2B 订单)。 + 配送B2B(dispatch 分表)本次未在线上取到样本验证;若返回空 items,拣货单只打表头, + 控制台会打印 `[B2B拣货单] 获取分箱明细失败` 便于定位。 +- 模板下拉框仍会同时列出波次的「拣货单」(id=16),选错时明细列会是空的(列名/字段不同)。 +- 拣货单不含分箱箱号;如需箱号,在 `loadB2bPickingPrintData` 的 details 里补 `boxes` 字段并加到模板表格。 +- 模板是**生产库**上的 id=17;若本地 dev 连的是测试库(`192.168.11.56:6060`),需在测试库同法把 PICKING 的自定义模板 + 改成同一版式(列 `item_code / item_name / plan_qty / pick_locations_text`),否则默认模板匹配不到、预览需手动选模板。 + diff --git a/src/components/BatchReceivingPrintDialog.vue b/src/components/BatchReceivingPrintDialog.vue index dffef9aa..be314be0 100644 --- a/src/components/BatchReceivingPrintDialog.vue +++ b/src/components/BatchReceivingPrintDialog.vue @@ -198,13 +198,16 @@ const props = withDefaults(defineProps<{ dialogTitle?: string queueNoField?: string documentLabel?: string + /** 模板下拉框默认选中的模板名(按名称匹配,避免硬编码模板 ID;仅当前未选模板时生效) */ + defaultTemplateName?: string fetchPrintData?: (row: RowItem, index: number) => Promise }>(), { selectionRows: () => [], businessType: 'RECEIPT', dialogTitle: '批量打印收货单', queueNoField: 'receiving_number', - documentLabel: '单据' + documentLabel: '单据', + defaultTemplateName: '' }) const emit = defineEmits<{ @@ -464,7 +467,10 @@ watch( if (value) { initDialog() } - } + }, + // 弹窗可能被 `v-if` 包在父级(打开时才挂载):此时 modelValue 初值即为 true, + // 不加 immediate 会漏掉首次打开 → 打印台/模板下拉都是空的 + { immediate: true } ) async function initDialog() { @@ -775,6 +781,9 @@ async function loadPrintFormData(index: number) { } async function loadPrintOptions() { + // 模板列表优先且独立加载:打印台接口失败时不应连带让模板下拉为空 + await loadTemplatesByBusinessType() + try { const stations: any = await stationApi.getList({ page: 1, pageSize: 100, where: {} }) @@ -788,10 +797,8 @@ async function loadPrintOptions() { } else { console.warn('获取打印台列表失败:', stations) } - - await loadTemplatesByBusinessType() } catch (e) { - console.error('加载打印配置失败', e) + console.error('加载打印台失败', e) } } @@ -842,6 +849,7 @@ async function loadTemplatesByBusinessType() { id: item.id, name: item.title || item.name || item.template_name || String(item.id) })) + applyDefaultTemplate() } else { templateOptions.value = [] console.warn('获取模板列表失败:', templates) @@ -852,6 +860,19 @@ async function loadTemplatesByBusinessType() { } } +type TemplateOptionLike = { id: string | number; name?: string } + +/** 未手动选模板时,按名称预选中(同名优先,其次包含匹配) */ +function applyDefaultTemplate() { + if (printSettings.template) return + const keyword = String(props.defaultTemplateName || '').trim() + const options = templateOptions.value as TemplateOptionLike[] + if (!keyword || !options.length) return + const exact = options.find((item) => String(item.name || '') === keyword) + const fuzzy = exact || options.find((item) => String(item.name || '').includes(keyword)) + if (fuzzy) printSettings.template = fuzzy.id +} + async function handleStationChange(val: string | number) { printSettings.printer = '' printerOptions.value = [] diff --git a/src/views/order/orderManagement/config/order-common-config.ts b/src/views/order/orderManagement/config/order-common-config.ts index ff2038e5..e645b703 100644 --- a/src/views/order/orderManagement/config/order-common-config.ts +++ b/src/views/order/orderManagement/config/order-common-config.ts @@ -652,6 +652,19 @@ export const ORDER_TOOLBAR_BUTTONS: Record = { disabledKey: 'hasNoSelection', action: 'handleB2bCancelUrgent' }, + /** + * B2B 批量打印拣货单(business_type=PICKING) + * 数据取勾选的订单行 + order.getB2bPackingSnapshot 的商品/取货储位明细,不看波次数据 + */ + b2bPickingPrint: { + key: 'b2bPickingPrint', + label: '批量打印拣货单', + size: 'small', + category: 'action', + loadingKey: 'b2bPickingPrintLoading', + disabledKey: 'hasNoSelection', + action: 'openB2bPickingPrintDialog' + }, batchLock: { key: 'batchLock', label: '批量锁定', size: 'small', category: 'action', loadingKey: 'batchAsyncTaskLoading', disabledKey: 'hasNoSelection', action: 'handleBatchLock' }, batchUnlock: { key: 'batchUnlock', label: '批量解锁', size: 'small', category: 'action', loadingKey: 'batchAsyncTaskLoading', disabledKey: 'hasNoSelection', action: 'handleBatchUnlock' }, batchPrint: { key: 'batchPrint', label: '批量打印', size: 'small', category: 'action', loadingKey: 'batchPrintLoading', disabledKey: 'hasNoSelection', action: 'handleBatchPrint' }, @@ -2518,6 +2531,11 @@ export function buildPendingStyleColumns(baseColumns: ReadonlyArray<{ prop: stri */ export function buildPendingB2bColumns() { const base = buildPendingStyleColumns() + // 两个 B2B 页签统一叫「运单号」(与配送B2B的 waybill_codes 列同名); + // 仅在本页签改名,不影响待处理订单 / 待出库 / 异常等非 B2B 页签的「快递单号」 + const renamedBase = base.map((col) => + col.prop === 'express_numbers' ? { ...col, label: '运单号' } : col + ) const extras: Array<{ prop: string; label: string; [key: string]: any }> = [ // 与配送订单列表对齐的通用字段 { prop: 'pre_delivery_order_code', label: '前置单号', width: '150', showOverflowTooltip: true }, @@ -2560,7 +2578,7 @@ export function buildPendingB2bColumns() { // 行内操作列(按状态动态:备货 / 确认提货 / 设置车牌) { prop: 'actions', label: '操作', width: '220', minWidth: '220', fixed: 'right' }, ] - return applyOrderListCopyActions([...base, ...extras]) + return applyOrderListCopyActions([...renamedBase, ...extras]) } /** B2B 备货状态文案(none=未开始 / padding=备货中 / fin=已完成) */ @@ -2809,8 +2827,10 @@ export const pendingToolbarButtons = pickToolbarButtons(pendingToolbarButtonKeys * B2B 作业按钮(order.finishB2bPrep / cancelB2bPrep / pickupB2b / setB2bUrgent / cancelB2bUrgent) * 仅追加到「待处理B2B订单」「配送B2B订单」两个页签,普通订单页不展示。 * 「开始备货 / 分箱 / 设置车牌」是单订单行内操作,放在表格「操作」列。 + * b2bPickingPrint:按勾选订单批量打印拣货单(order.getB2bPackingSnapshot 提供商品与取货储位)。 */ export const b2bToolbarButtonKeys = [ + 'b2bPickingPrint', 'b2bFinishPrep', 'b2bCancelPrep', 'b2bPickup', diff --git a/src/views/order/orderManagement/deliveryOrder.vue b/src/views/order/orderManagement/deliveryOrder.vue index 954942ee..89b1edd3 100644 --- a/src/views/order/orderManagement/deliveryOrder.vue +++ b/src/views/order/orderManagement/deliveryOrder.vue @@ -392,6 +392,19 @@ @submit="submitPickup" /> + + + import('./form/B2bPrepFinis const B2bPickupPlateForm = defineAsyncComponent(() => import('./form/B2bPickupPlateForm.vue')) const B2bPickupForm = defineAsyncComponent(() => import('./form/B2bPickupForm.vue')) const B2bPrepForm = defineAsyncComponent(() => import('./form/B2bPrepForm.vue')) +const BatchReceivingPrintDialog = defineAsyncComponent(() => import('@/components/BatchReceivingPrintDialog.vue')) import { createOrderPageExport } from './utils/order-page-export' import { buildOrderWhereConditions, parseOrderListResponse, resolveOrderRecheckStatus } from '@/views/order/shared/orderListExport' import { useOrderListPageCleanup } from './utils/use-order-list-page-cleanup' import { useOrderBatchPrint } from './utils/use-order-batch-print' import { useDeliveryOrderSubWaybillPrint } from './utils/use-delivery-sub-waybill-print' import { useB2bActions } from './utils/use-b2b-actions' +import { useB2bPickingPrint } from './utils/use-b2b-picking-print' import { useVerticalSplitPane } from '@/composables/useVerticalSplitPane' import OrderToolbarButtonGroup from '@/components/ToolbarButtonGroup/index.vue' import AllocateSubOrderNumberForm from './form/AllocateSubOrderNumberForm.vue' @@ -773,7 +788,8 @@ const buttonLoadingMap = computed>(() => ({ batchPrintLoading: batchPrintLoading.value, subWaybillPrintLoading: subWaybillPrintLoading.value, allocateSubOrderNumberLoading: allocateSubOrderNumberLoading.value, - b2bActionLoading: b2bActionLoading.value + b2bActionLoading: b2bActionLoading.value, + b2bPickingPrintLoading: b2bPickingPrintLoading.value })) const buttonDisabledMap = computed>(() => ({ @@ -941,6 +957,19 @@ const { onSuccess: () => loadData() }) +// B2B 批量打印拣货单:打印队列 = 勾选订单行,明细 = order.getB2bPackingSnapshot 的商品与取货储位 +const { + pickingPrintVisible: b2bPickingPrintVisible, + pickingPrintLoading: b2bPickingPrintLoading, + pickingPrintRows: b2bPickingPrintRows, + defaultTemplateName: b2bPickingPrintTemplateName, + openB2bPickingPrintDialog, + loadB2bPickingPrintData +} = useB2bPickingPrint({ + getSelectionRows: () => selectionRows.value, + emptySelectionMessage: '请先勾选需要打印拣货单的 B2B 订单' +}) + /** 行内「操作」列(仅 B2B 页签):备货 / 确认提货 / 设置车牌(分箱在备货窗口内完成) */ function handleB2bRowAction(command: string, row: any) { if (command === 'prep') { @@ -966,6 +995,7 @@ toolbarActionMap.handleB2bCancelPrep = handleB2bCancelPrep toolbarActionMap.handleB2bPickup = openB2bPickupDialog toolbarActionMap.handleB2bSetUrgent = handleB2bSetUrgent toolbarActionMap.handleB2bCancelUrgent = handleB2bCancelUrgent +toolbarActionMap.openB2bPickingPrintDialog = openB2bPickingPrintDialog function resolveButtonLoading(loadingKey?: string) { if (!loadingKey) return false diff --git a/src/views/order/orderManagement/pendingOrder.vue b/src/views/order/orderManagement/pendingOrder.vue index 643f85f0..6ef7bc70 100644 --- a/src/views/order/orderManagement/pendingOrder.vue +++ b/src/views/order/orderManagement/pendingOrder.vue @@ -476,6 +476,19 @@ @submit="submitPickup" /> + + + import('./form/B2bPrepFinis const B2bPickupPlateForm = defineAsyncComponent(() => import('./form/B2bPickupPlateForm.vue')) const B2bPickupForm = defineAsyncComponent(() => import('./form/B2bPickupForm.vue')) const B2bPrepForm = defineAsyncComponent(() => import('./form/B2bPrepForm.vue')) +const BatchReceivingPrintDialog = defineAsyncComponent(() => import('@/components/BatchReceivingPrintDialog.vue')) const scanBox = ref(null) const upperTable = ref(null) @@ -1061,6 +1076,19 @@ const { onSuccess: () => loadData() }) +// B2B 批量打印拣货单:打印队列 = 勾选订单行,明细 = order.getB2bPackingSnapshot 的商品与取货储位 +const { + pickingPrintVisible: b2bPickingPrintVisible, + pickingPrintLoading: b2bPickingPrintLoading, + pickingPrintRows: b2bPickingPrintRows, + defaultTemplateName: b2bPickingPrintTemplateName, + openB2bPickingPrintDialog, + loadB2bPickingPrintData +} = useB2bPickingPrint({ + getSelectionRows: () => selectionRows.value, + emptySelectionMessage: '请先勾选需要打印拣货单的 B2B 订单' +}) + /** 行内「操作」列(仅 B2B 页签):备货 / 确认提货 / 设置车牌(分箱在备货窗口内完成) */ function handleB2bRowAction(command: string, row: any) { if (command === 'prep') { @@ -1323,6 +1351,7 @@ toolbarActionMap['openB2bFinishPrepDialog'] = openB2bFinishPrepDialog toolbarActionMap['handleB2bPickup'] = openB2bPickupDialog toolbarActionMap['handleB2bSetUrgent'] = handleB2bSetUrgent toolbarActionMap['handleB2bCancelUrgent'] = handleB2bCancelUrgent +toolbarActionMap['openB2bPickingPrintDialog'] = openB2bPickingPrintDialog toolbarActionMap['handleBatchPrint'] = handleBatchPrint toolbarActionMap['handleSubWaybillPrint'] = handleSubWaybillPrint toolbarActionMap['handleConfirmInterceptBatch'] = handleConfirmInterceptBatch @@ -1346,7 +1375,8 @@ const buttonLoadingMap = computed>(() => ({ allocateSubOrderNumberLoading: allocateSubOrderNumberLoading.value, subWaybillPrintLoading: subWaybillPrintLoading.value, confirmInterceptLoading: confirmInterceptLoading.value, - b2bActionLoading: b2bActionLoading.value + b2bActionLoading: b2bActionLoading.value, + b2bPickingPrintLoading: b2bPickingPrintLoading.value })) const toolbarLayoutKey = computed(() => diff --git a/src/views/order/orderManagement/utils/use-b2b-picking-print.ts b/src/views/order/orderManagement/utils/use-b2b-picking-print.ts new file mode 100644 index 00000000..b4008893 --- /dev/null +++ b/src/views/order/orderManagement/utils/use-b2b-picking-print.ts @@ -0,0 +1,204 @@ +import { ref } from 'vue' +import { ElMessage } from 'element-plus' +import { orderPendingOrderGetB2bPackingSnapshot } from '@/api/order.pendingorder/orderpendingOrder' + +/** + * B2B「批量打印拣货单」(与 order/waveOrder 的同名功能对齐,但**不使用波次数据**) + * + * - 打印队列 = 当前勾选的订单行(一单一份拣货单,队列号取 delivery_order_code) + * - 单据头 = 订单行字段:delivery_order_code / sys_platform_name / sys_logistics_name / create_at / remark + * - 明细表 = order.getB2bPackingSnapshot 的 items: + * item_code(商品条码)/ item_name / plan_qty(应拣数量)/ pick_locations_text(取货储位文案) + * - 模板:打印模板设置里的「B2B订单拣货单」(business_type=PICKING,148×210) + */ + +type UseB2bPickingPrintOptions = { + /** 当前页签勾选行 */ + getSelectionRows: () => any[] + /** 弹窗默认选中的模板名(各环境模板 ID 不同,按名称匹配更稳) */ + defaultTemplateName?: string + emptySelectionMessage?: string +} + +function isOkCode(res: any) { + return Boolean(res && (res.code === 1 || res.code === 200 || res.code === 0 || res.flag === 'success')) +} + +function pickData(res: any): Record { + const data = res?.data && typeof res.data === 'object' ? res.data : res + return (data && typeof data === 'object' ? data : {}) as Record +} + +function toOrderId(value: unknown): number | null { + const n = Number(value) + return Number.isInteger(n) && n > 0 ? n : null +} + +/** ISO 时间戳 → YYYY-MM-DD HH:mm:ss(模板直接取字符串,不认 ISO) */ +function formatPrintTime(val: unknown): string { + if (!val) return '' + try { + const d = new Date(String(val)) + if (isNaN(d.getTime())) return String(val) + const pad = (n: number) => String(n).padStart(2, '0') + return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}` + } catch { + return String(val) + } +} + +/** + * 取货储位文案:`E2区24-05-01×24,E2区24-02-02×72` + * (pick_locations 元素 { space_id, space_name, quantity },未分配储位为空数组) + */ +export function formatB2bPickLocations(value: unknown): string { + if (!Array.isArray(value)) return '' + const texts = value + .map((loc: any) => { + const name = String(loc?.space_name ?? loc?.space_id ?? '').trim() + if (!name) return '' + const qty = Number(loc?.quantity ?? 0) + return Number.isFinite(qty) && qty > 0 ? `${name}×${qty}` : name + }) + .filter(Boolean) + return texts.join(',') +} + +/** + * 运单号文本:`AUDIT-SF-1790610480234`(多个用 `, ` 连接) + * 取数顺序:waybill_codes(配送列表口径)→ express_numbers(待处理/待处理B2B口径) + * → waybill_code / waybill_no → expresses[].waybill_code + * ⚠️ 不使用 delivery_order_code(发货单号),两者是不同业务对象 + */ +export function resolveB2bWaybillText(row: Record | null | undefined): string { + if (!row) return '' + const normalize = (value: unknown): string => { + if (value === undefined || value === null) return '' + if (Array.isArray(value)) { + return value.map((item) => String(item ?? '').trim()).filter(Boolean).join(', ') + } + const text = String(value).trim() + if (!text) return '' + if (text.startsWith('[') && text.endsWith(']')) { + try { + const parsed = JSON.parse(text) + if (Array.isArray(parsed)) { + return parsed.map((item) => String(item ?? '').trim()).filter(Boolean).join(', ') + } + } catch { + // 非 JSON:按分隔符处理 + } + } + return text + } + + const candidates = [row.waybill_codes, row.express_numbers, row.waybill_code, row.waybill_no] + for (const candidate of candidates) { + const text = normalize(candidate) + if (text) return text + } + + const expresses = Array.isArray(row.expresses) ? row.expresses : [] + for (const item of expresses) { + const text = normalize(item?.waybill_code ?? item?.express_code) + if (text) return text + } + return '' +} + +/** + * 物流公司文本:B2B 列表实测 `sys_logistics_name` 为 null(只有 `logistics_name` 有值), + * 因此按「系统快递 → 快递」回退,避免模板「物流公司」行打印为空。 + */ +export function resolveB2bLogisticsText(row: Record | null | undefined): string { + if (!row) return '' + const sysName = String(row.sys_logistics_name ?? '').trim() + if (sysName) return sysName + return String(row.logistics_name ?? '').trim() +} + +export function useB2bPickingPrint(options: UseB2bPickingPrintOptions) { + const pickingPrintVisible = ref(false) + const pickingPrintLoading = ref(false) + /** 打印队列:勾选行的浅拷贝快照(关闭弹窗后表格重新选择不影响已打开的队列) */ + const pickingPrintRows = ref([]) + /** 单据头/明细缓存:order_id → 打印数据(弹窗内切换单据时不重复请求) */ + const printDataCache = ref>>({}) + + function openB2bPickingPrintDialog() { + const rows = options.getSelectionRows() || [] + if (!rows.length) { + ElMessage.warning(options.emptySelectionMessage || '请先勾选需要打印拣货单的 B2B 订单') + return + } + const invalid = rows.filter((row: any) => toOrderId(row?.id ?? row?.order_id) === null) + if (invalid.length === rows.length) { + ElMessage.error('所选订单缺少有效订单 ID,请刷新后重试') + return + } + pickingPrintRows.value = rows + .filter((row: any) => toOrderId(row?.id ?? row?.order_id) !== null) + .map((row: any) => ({ ...row })) + printDataCache.value = {} + pickingPrintVisible.value = true + } + + /** BatchReceivingPrintDialog 的 fetchPrintData:按订单组装单据头 + 商品明细 */ + async function loadB2bPickingPrintData(row: Record) { + const orderId = toOrderId(row?.id ?? row?.order_id) + if (orderId === null) return { ...row } + + const cacheKey = String(orderId) + const cached = printDataCache.value[cacheKey] + if (cached) return cached + + pickingPrintLoading.value = true + let details: Array> = [] + try { + const res: any = await orderPendingOrderGetB2bPackingSnapshot({ id: orderId }) + if (isOkCode(res)) { + const snapshot = pickData(res) + const items = Array.isArray(snapshot.items) ? snapshot.items : [] + details = items.map((item: any) => { + const itemSnapshot = (item?.item_snapshot ?? {}) as Record + return { + order_item_id: item?.order_item_id ?? '', + item_code: String(item?.item_code ?? itemSnapshot.item_code ?? '').trim(), + item_name: String(item?.item_name ?? itemSnapshot.item_name ?? '').trim(), + plan_qty: Number(item?.plan_qty ?? 0), + packed_quantity: Number(item?.packed_quantity ?? 0), + pick_locations_text: formatB2bPickLocations(item?.pick_locations) + } + }) + } else { + console.warn('[B2B拣货单] 获取分箱明细失败', res) + } + } catch (e) { + console.error('[B2B拣货单] 获取分箱明细出错', e) + } finally { + pickingPrintLoading.value = false + } + + const formData: Record = { + ...row, + // 模板「运单号」行 / 条码取值(不用 delivery_order_code 发货单号) + waybill_text: resolveB2bWaybillText(row), + // 模板「物流公司」行:B2B 列表里 sys_logistics_name 常为 null(实测),回退 logistics_name + logistics_text: resolveB2bLogisticsText(row), + create_at: formatPrintTime(row?.create_at ?? row?.created_at), + print_time: formatPrintTime(new Date().toISOString()), + details + } + printDataCache.value[cacheKey] = formData + return formData + } + + return { + pickingPrintVisible, + pickingPrintLoading, + pickingPrintRows, + defaultTemplateName: options.defaultTemplateName || 'B2B订单拣货单', + openB2bPickingPrintDialog, + loadB2bPickingPrintData + } +}