diff --git a/dist.tar.gz b/dist.tar.gz index 4e89efdc..5131fd22 100644 Binary files a/dist.tar.gz and b/dist.tar.gz differ diff --git a/src/api/combogoods/combogoods.ts b/src/api/combogoods/combogoods.ts index 400c66fb..646ebd4e 100644 --- a/src/api/combogoods/combogoods.ts +++ b/src/api/combogoods/combogoods.ts @@ -19,6 +19,7 @@ export type ComboGoodsListItem = Record & { id?: number combo_code?: string combo_name?: string + custom_code?: string | null combo_sku_id?: number status?: number warehouse_id?: number @@ -46,6 +47,7 @@ export type ComboGoodsCreateParams = { combo_name: string warehouse_id?: number remark?: string + custom_code?: string items: ComboGoodsCreateItem[] } @@ -53,6 +55,7 @@ export type ComboGoodsCreateResponse = { id: number combo_code: string combo_name: string + custom_code?: string | null } export type ComboGoodsUpdateParams = { @@ -60,6 +63,7 @@ export type ComboGoodsUpdateParams = { combo_name?: string warehouse_id?: number remark?: string + custom_code?: string | null status?: number items?: ComboGoodsCreateItem[] } diff --git a/src/api/order.index/orderindex.ts b/src/api/order.index/orderindex.ts index ddf243a7..049faea8 100644 --- a/src/api/order.index/orderindex.ts +++ b/src/api/order.index/orderindex.ts @@ -143,6 +143,9 @@ export type BindExpressPackageMaterialParams = { package_material_code: string } +/** order.export 导出模式:waybill=不含明细(默认),item=含明细 */ +export type OrderExportMode = 'waybill' | 'item' + export type OrderExportParams = { table_type?: string tableType?: string @@ -150,6 +153,9 @@ export type OrderExportParams = { module_name?: string where?: Record sort?: OrderListParams['sort'] + /** 导出模式,默认 waybill */ + export_mode?: OrderExportMode + exportMode?: OrderExportMode } export type OrderExportTaskProgressParams = { diff --git a/src/api/stock/stock.ts b/src/api/stock/stock.ts index 6438c489..cbafa9f3 100644 --- a/src/api/stock/stock.ts +++ b/src/api/stock/stock.ts @@ -399,7 +399,13 @@ export function stockStockWarehouse(data: { pagination?: any; where?: any }) { } as any) } -export function exportStockWarehouse(data: { where?: Record; group_by_batch?: boolean; sort?: Record }) { +export function exportStockWarehouse(data: { + where?: Record + group_by_batch?: boolean + sort?: Record + export_mode?: 'waybill' | 'item' + exportMode?: 'waybill' | 'item' +}) { return request({ url: '/system', method: 'post', diff --git a/src/api/storage.directinbound/directinbound.ts b/src/api/storage.directinbound/directinbound.ts new file mode 100644 index 00000000..4a49e41b --- /dev/null +++ b/src/api/storage.directinbound/directinbound.ts @@ -0,0 +1,250 @@ +import request from '@/utils/request' + +const v = '1.0' + +export type DirectInboundGetItemsParams = { + /** 入库单号 */ + entry_order_code: string +} + +export type DirectInboundEntryOrder = { + id?: number + entry_order_code?: string + order_type?: string + order_status?: string + source_type?: string + warehouse_id?: number + store_id?: number + remark?: string + [key: string]: unknown +} + +export type DirectInboundLog = { + id?: number + stock_id?: number + quantity?: number + inbound_type?: string + remark?: string + /** 存放库位ID,关联 wms_location_space.id */ + space_id?: number + created_at?: string + warehouse_item_code?: string + warehouse_item_name?: string + [key: string]: unknown +} + +/** pending 绑定项,结构同 storage.entry.get */ +export type DirectInboundItemBinding = { + id?: number + entry_item_id?: number + receiving_detail_id?: number + allocated_quantity?: number + status?: string + receivingDetail?: Record + [key: string]: unknown +} + +export type DirectInboundItem = { + id?: number + stock_id?: number + count?: number + received_quantity?: number + direct_inbound_quantity?: number + remaining_quantity?: number + /** pending 绑定总量 */ + pending_binding_total?: number + /** pending 绑定列表 */ + bindings?: DirectInboundItemBinding[] + direct_logs?: DirectInboundLog[] + [key: string]: unknown +} + +export type DirectInboundSummary = { + total_items?: number + total_planned?: number + total_direct_inbound?: number + [key: string]: unknown +} + +export type DirectInboundGetItemsResponse = { + code?: number + message?: string + entryOrder?: DirectInboundEntryOrder + items?: DirectInboundItem[] + direct_logs?: DirectInboundLog[] + summary?: DirectInboundSummary + data?: { + entryOrder?: DirectInboundEntryOrder + items?: DirectInboundItem[] + direct_logs?: DirectInboundLog[] + summary?: DirectInboundSummary + } +} + +/** 获取入库单的导入/PDA 入库信息 */ +export function getDirectInboundItems( + data: DirectInboundGetItemsParams +): Promise { + return request({ + url: '/system', + method: 'post', + params: { + method: 'storage.directInbound.getItems', + v, + timestamp: new Date().getTime() + }, + data + }) +} + +export type DirectInboundAddItemBatchEntry = { + /** 商品SKU ID(对应 wms_stock_warehouse.id) */ + stock_id: number + /** 本次入库数量(正整数) */ + quantity: number + /** 入库方式:import(导入入库)、pda(PDA入库) */ + inbound_type: 'import' | 'pda' | string + /** 存放库位ID,关联 wms_location_space.id;为空时 commit 默认使用库位 1 */ + space_id?: number + /** 备注(如导入文件名、PDA操作备注等) */ + remark?: string +} + +export type DirectInboundAddItemSingleParams = { + /** 入库单号 */ + entry_order_code: string + /** 商品SKU ID(对应 wms_stock_warehouse.id) */ + stock_id: number + /** 本次入库数量(正整数) */ + quantity: number + /** 入库方式:import(导入入库)、pda(PDA入库) */ + inbound_type: 'import' | 'pda' | string + /** 存放库位ID,关联 wms_location_space.id;为空时 commit 默认使用库位 1 */ + space_id?: number + /** 备注(如导入文件名、PDA操作备注等) */ + remark?: string +} + +export type DirectInboundAddItemBatchParams = { + /** 入库单号 */ + entry_order_code: string + /** 批量模式:商品列表。传入 items 时忽略顶层的 stock_id/quantity/inbound_type/remark */ + items: DirectInboundAddItemBatchEntry[] +} + +export type DirectInboundAddItemParams = + | DirectInboundAddItemSingleParams + | DirectInboundAddItemBatchParams + +export type DirectInboundAddItemResultEntry = { + id?: number + stock_id?: number + quantity?: number + inbound_type?: string + /** 存放库位ID */ + space_id?: number + plan_quantity?: number + existing_before?: number + existing_after?: number + remaining?: number + [key: string]: unknown +} + +export type DirectInboundAddItemResponse = { + code?: number + message?: string + /** 单条模式 */ + id?: number + stock_id?: number + quantity?: number + inbound_type?: string + plan_quantity?: number + existing_before?: number + existing_after?: number + remaining?: number + /** 批量模式 */ + count?: number + total_quantity?: number + items?: DirectInboundAddItemResultEntry[] + data?: Partial +} + +/** 按商品增量添加导入/PDA 入库记录(支持单条与批量) */ +export function addDirectInboundItem( + data: DirectInboundAddItemParams +): Promise { + return request({ + url: '/system', + method: 'post', + params: { + method: 'storage.directInbound.addItem', + v, + timestamp: new Date().getTime() + }, + data + }) +} + +export type DirectInboundCommitParams = { + /** 入库单号 */ + entry_order_code: string +} + +export type DirectInboundCommitResponse = { + code?: number + message?: string + id?: number + entry_order_code?: string + order_status?: string + sync_status?: string + items_count?: number + total_quantity?: number + data?: Partial +} + +/** 提交确认完成导入/PDA 入库 */ +export function commitDirectInbound( + data: DirectInboundCommitParams +): Promise { + return request({ + url: '/system', + method: 'post', + params: { + method: 'storage.directInbound.commit', + v, + timestamp: new Date().getTime() + }, + data + }) +} + +export type DirectInboundRemoveItemParams = { + /** 入库记录ID(wms_inbound_direct_log.id) */ + id: number +} + +export type DirectInboundRemoveItemResponse = { + code?: number + message?: string + id?: number + stock_id?: number + quantity?: number + inbound_type?: string + data?: Partial +} + +/** 移除一条导入/PDA 入库记录(仅限未提交的入库单) */ +export function removeDirectInboundItem( + data: DirectInboundRemoveItemParams +): Promise { + return request({ + url: '/system', + method: 'post', + params: { + method: 'storage.directInbound.removeItem', + v, + timestamp: new Date().getTime() + }, + data + }) +} diff --git a/src/api/storage.entry/entry.ts b/src/api/storage.entry/entry.ts index ae5da388..42fdf29c 100644 --- a/src/api/storage.entry/entry.ts +++ b/src/api/storage.entry/entry.ts @@ -203,3 +203,39 @@ export function unbindReceivingDetails( data }) } + +export type GetEntryPrintDataParams = { + /** 入库单ID */ + id: number +} + +/** 打印明细行(RECEIPT 模板 field_code 映射) */ +export type EntryPrintDataItem = Record + +/** 打印数据:扁平键值对 + items 明细数组 */ +export type EntryPrintData = { + items?: EntryPrintDataItem[] + [key: string]: unknown +} + +export type GetEntryPrintDataResponse = { + code?: number + message?: string + data?: EntryPrintData +} + +/** 获取入库单打印数据(按 RECEIPT 模板 field_code 映射) */ +export function getEntryPrintData( + data: GetEntryPrintDataParams +): Promise { + return request({ + url: '/system', + method: 'post', + params: { + method: 'storage.entry.getPrintData', + v, + timestamp: new Date().getTime() + }, + data + }) +} diff --git a/src/api/storage.report/report.ts b/src/api/storage.report/report.ts index 949b556e..f7e0a292 100644 --- a/src/api/storage.report/report.ts +++ b/src/api/storage.report/report.ts @@ -36,7 +36,10 @@ export interface StorageReportSearchBody { } } -export interface StorageReportExportBody extends StorageReportSearchBody {} +export interface StorageReportExportBody extends StorageReportSearchBody { + export_mode?: 'waybill' | 'item' + exportMode?: 'waybill' | 'item' +} export interface StorageReportExportTaskResponse { task_id: string diff --git a/src/components/AsyncExportProgressDialog.vue b/src/components/AsyncExportProgressDialog.vue new file mode 100644 index 00000000..e0b1dc79 --- /dev/null +++ b/src/components/AsyncExportProgressDialog.vue @@ -0,0 +1,85 @@ + + + + + diff --git a/src/components/ExportModeDropdown.vue b/src/components/ExportModeDropdown.vue new file mode 100644 index 00000000..620cfefe --- /dev/null +++ b/src/components/ExportModeDropdown.vue @@ -0,0 +1,39 @@ + + + diff --git a/src/components/ScanBox/index.vue b/src/components/ScanBox/index.vue index 8662cb52..4d24207f 100644 --- a/src/components/ScanBox/index.vue +++ b/src/components/ScanBox/index.vue @@ -54,7 +54,10 @@ {{ field.extraAction.label }} -
+
无需填值 + v.trim()) + .filter(Boolean) + return values.join(',') +} function getTextPlaceholder(field: any) { const operator = customConditions[field.value].operator @@ -699,16 +729,17 @@ function normalizeTextValue(field: any) { const operator = customConditions[field.value].operator const value = customConditions[field.value].value - if (operator !== 'contains' || !value) { + if (!isMultiValueTextOperator(operator) || !value) { return } - let normalizedValue = value - normalizedValue = normalizedValue - .replace(/[,;;、]/g, ',') - .replace(/\s+/g, '') - .replace(/,+/g, ',') - .replace(/^,|,$/g, '') + let normalizedValue = normalizeMultiValueText(String(value)) + if (operator === 'contains') { + normalizedValue = normalizedValue + .replace(/\s+/g, '') + .replace(/,+/g, ',') + .replace(/^,|,$/g, '') + } if (normalizedValue !== value) { customConditions[field.value].value = normalizedValue @@ -716,6 +747,28 @@ function normalizeTextValue(field: any) { } } +function handleMultiValuePaste(event: ClipboardEvent, field: any) { + const operator = customConditions[field.value].operator + if (!isMultiValueTextOperator(operator)) return + + const pasted = event.clipboardData?.getData('text') || '' + if (!/[\r\n\t]/.test(pasted)) return + + event.preventDefault() + const current = String(customConditions[field.value].value || '').trim() + const normalizedPaste = normalizeMultiValueText(pasted) + if (!normalizedPaste) return + + customConditions[field.value].value = current + ? `${current.replace(/,+$/g, '')},${normalizedPaste}` + : normalizedPaste + + handleCustomChange() + nextTick(() => { + handleSubmit() + }) +} + const defaultDayStart = new Date(2000, 0, 1, 0, 0, 0) const defaultDayEnd = new Date(2000, 0, 1, 23, 59, 59) @@ -1384,10 +1437,25 @@ defineExpose({ getConditions, reset, clear, getFieldDraft, setFieldCondition, su min-width: 0; } -.field-control--range { +.field-control--range, +.field-control--multi { flex-direction: column; } +.field-control--multi .operator-select { + width: 100%; +} + +.field-control--multi .value-input--multi { + width: 100%; +} + +.field-control--multi :deep(.el-textarea__inner) { + min-height: 72px; + line-height: 1.5; + font-size: 12px; +} + .field-control--range :deep(.el-date-editor--daterange), .field-control--range :deep(.el-date-editor--datetimerange) { width: 100%; diff --git a/src/composables/useAsyncExportTask.ts b/src/composables/useAsyncExportTask.ts new file mode 100644 index 00000000..2b5de64c --- /dev/null +++ b/src/composables/useAsyncExportTask.ts @@ -0,0 +1,250 @@ +import { computed, onBeforeUnmount, reactive, ref } from 'vue' +import { ElMessage } from 'element-plus' +import type { ExportMode } from '@/utils/asyncExportHelpers' +import { + downloadExportFile, + extractExportDownloadUrl, + isExportApiSuccess, + parseExportTaskPayload +} from '@/utils/asyncExportHelpers' + +export type AsyncExportPayload = Record & { + export_mode?: ExportMode + exportMode?: ExportMode +} + +export function useAsyncExportTask(options: { + storageKey?: string + submitExport: (payload: AsyncExportPayload) => Promise + queryProgress: (params: { task_id: string; taskId?: string }) => Promise + isSuccess?: (res: unknown) => boolean +}) { + const isSuccess = options.isSuccess || isExportApiSuccess + const exportLoading = ref(false) + const exportDialogVisible = ref(false) + const exportTaskProgress = reactive({ + taskId: '', + status: 'submitted', + progress: 0, + message: '', + error: '', + downloadUrl: '', + updateTime: 0 + }) + + let exportPollingTimer: number | null = null + + function resetExportProgress() { + exportTaskProgress.taskId = '' + exportTaskProgress.status = 'submitted' + exportTaskProgress.progress = 0 + exportTaskProgress.message = '' + exportTaskProgress.error = '' + exportTaskProgress.downloadUrl = '' + exportTaskProgress.updateTime = 0 + } + + function stopExportPolling() { + if (exportPollingTimer) { + window.clearTimeout(exportPollingTimer) + exportPollingTimer = null + } + } + + function scheduleExportPolling(delay = 1500) { + stopExportPolling() + exportPollingTimer = window.setTimeout(() => { + void refreshExportTaskProgress() + }, delay) + } + + function saveExportTaskId(taskId: string) { + if (!options.storageKey || !taskId) return + try { + window.localStorage.setItem(options.storageKey, taskId) + } catch { + // ignore + } + } + + function clearSavedExportTaskId() { + if (!options.storageKey) return + try { + window.localStorage.removeItem(options.storageKey) + } catch { + // ignore + } + } + + async function refreshExportTaskProgress() { + if (!exportTaskProgress.taskId) return + try { + const res = await options.queryProgress({ + task_id: exportTaskProgress.taskId, + taskId: exportTaskProgress.taskId + }) + if (!isSuccess(res)) { + scheduleExportPolling() + return + } + const payload = parseExportTaskPayload(res) + exportTaskProgress.status = String(payload.status || exportTaskProgress.status) + exportTaskProgress.progress = Number.isFinite(Number(payload.progress)) + ? Number(payload.progress) + : exportTaskProgress.progress + exportTaskProgress.message = String(payload.message || '') + exportTaskProgress.error = String(payload.error || '') + exportTaskProgress.downloadUrl = extractExportDownloadUrl(payload) + exportTaskProgress.updateTime = Number(payload.update_time || payload.updateTime || 0) + + if (exportTaskProgress.status === 'success') { + stopExportPolling() + exportLoading.value = false + clearSavedExportTaskId() + try { + if (exportTaskProgress.downloadUrl) { + downloadExportFile(exportTaskProgress.downloadUrl) + ElMessage.success(exportTaskProgress.message || '导出完成,文件已开始下载') + } else { + ElMessage.warning(exportTaskProgress.message || '导出完成,但未返回下载地址') + } + } finally { + window.setTimeout(() => { + exportDialogVisible.value = false + resetExportProgress() + }, 1200) + } + return + } + + if (exportTaskProgress.status === 'failed' || exportTaskProgress.status === 'not_found') { + stopExportPolling() + exportLoading.value = false + clearSavedExportTaskId() + ElMessage.error(exportTaskProgress.error || exportTaskProgress.message || '导出任务失败') + return + } + + scheduleExportPolling() + } catch { + scheduleExportPolling(2000) + } + } + + async function submitExportTask(payload: AsyncExportPayload) { + if (exportLoading.value) return + exportLoading.value = true + resetExportProgress() + exportDialogVisible.value = true + try { + const res = await options.submitExport(payload) + if (!isSuccess(res)) { + throw new Error((res as any)?.message || '导出任务提交失败') + } + const data = parseExportTaskPayload(res) + const taskId = String(data.task_id || data.taskId || '').trim() + if (!taskId) { + throw new Error((res as any)?.message || '导出任务提交失败') + } + exportTaskProgress.taskId = taskId + exportTaskProgress.status = String(data.status || 'submitted') + exportTaskProgress.progress = Number.isFinite(Number(data.progress)) ? Number(data.progress) : 0 + exportTaskProgress.message = String(data.message || '任务已受理') + exportTaskProgress.error = String(data.error || '') + exportTaskProgress.updateTime = Number(data.update_time || data.updateTime || 0) + saveExportTaskId(taskId) + scheduleExportPolling(800) + } catch (error: any) { + exportLoading.value = false + exportDialogVisible.value = false + resetExportProgress() + ElMessage.error(error?.message || '导出任务提交失败') + } + } + + async function submitExportTaskWithMode( + payload: Record, + exportMode: ExportMode = 'waybill' + ) { + await submitExportTask({ + ...payload, + export_mode: exportMode, + exportMode + }) + } + + const exportProgressPercent = computed(() => { + const value = Number(exportTaskProgress.progress || 0) + if (!Number.isFinite(value)) return 0 + return Math.max(0, Math.min(100, value)) + }) + + const exportProgressStatus = computed(() => { + if (exportTaskProgress.status === 'failed' || exportTaskProgress.status === 'not_found') { + return 'exception' + } + if (exportTaskProgress.status === 'success' || exportProgressPercent.value >= 100) { + return 'success' + } + return undefined + }) + + const exportStatusLabel = computed(() => { + const map: Record = { + submitted: '已提交', + running: '执行中', + success: '已完成', + failed: '失败', + not_found: '未找到' + } + return map[exportTaskProgress.status] || exportTaskProgress.status || '—' + }) + + function getSavedExportTaskId() { + if (!options.storageKey) return '' + try { + return String(window.localStorage.getItem(options.storageKey) || '').trim() + } catch { + return '' + } + } + + function resumeExportTaskFromStorage() { + const savedTaskId = getSavedExportTaskId() + if (!savedTaskId || exportLoading.value) return + exportTaskProgress.taskId = savedTaskId + exportTaskProgress.status = 'submitted' + exportTaskProgress.progress = 0 + exportTaskProgress.message = '检测到未完成导出任务,正在恢复进度...' + exportTaskProgress.error = '' + exportTaskProgress.downloadUrl = '' + exportTaskProgress.updateTime = 0 + exportDialogVisible.value = true + exportLoading.value = true + scheduleExportPolling(200) + } + + function hasPendingExportTask() { + return Boolean(getSavedExportTaskId()) + } + + onBeforeUnmount(() => { + stopExportPolling() + }) + + return { + exportLoading, + exportDialogVisible, + exportTaskProgress, + exportProgressPercent, + exportProgressStatus, + exportStatusLabel, + submitExportTask, + submitExportTaskWithMode, + refreshExportTaskProgress, + resetExportProgress, + stopExportPolling, + resumeExportTaskFromStorage, + hasPendingExportTask + } +} diff --git a/src/composables/useOrderAsyncExport.ts b/src/composables/useOrderAsyncExport.ts index a05f968a..20b6000a 100644 --- a/src/composables/useOrderAsyncExport.ts +++ b/src/composables/useOrderAsyncExport.ts @@ -1,11 +1,12 @@ import { computed, onBeforeUnmount, reactive, ref } from 'vue' import { ElMessage } from 'element-plus' -import { orderExport, orderExportTaskProgress } from '@/api/order.index/orderindex' +import { orderExport, orderExportTaskProgress, type OrderExportMode } from '@/api/order.index/orderindex' import { - downloadOrderExportFile, - isOrderIndexApiSuccess, - parseOrderExportTaskPayload -} from '@/views/order/orderManagement/utils/order-index-helpers' + downloadExportFile, + extractExportDownloadUrl, + isExportApiSuccess, + parseExportTaskPayload +} from '@/utils/asyncExportHelpers' export type OrderAsyncExportPayload = { table_type?: string @@ -14,6 +15,8 @@ export type OrderAsyncExportPayload = { module_name?: string where?: Record sort?: Record + export_mode?: OrderExportMode + exportMode?: OrderExportMode } export function useOrderAsyncExport(storageKey?: string) { @@ -77,18 +80,18 @@ export function useOrderAsyncExport(storageKey?: string) { if (!exportTaskProgress.taskId) return try { const res: any = await orderExportTaskProgress({ task_id: exportTaskProgress.taskId }) - if (!isOrderIndexApiSuccess(res)) { + if (!isExportApiSuccess(res)) { scheduleExportPolling() return } - const payload = parseOrderExportTaskPayload(res) + const payload = parseExportTaskPayload(res) exportTaskProgress.status = String(payload.status || exportTaskProgress.status) exportTaskProgress.progress = Number.isFinite(Number(payload.progress)) ? Number(payload.progress) : exportTaskProgress.progress exportTaskProgress.message = String(payload.message || '') exportTaskProgress.error = String(payload.error || '') - exportTaskProgress.downloadUrl = String(payload.download_url || payload.downloadUrl || '') + exportTaskProgress.downloadUrl = extractExportDownloadUrl(payload) exportTaskProgress.updateTime = Number(payload.update_time || payload.updateTime || 0) if (exportTaskProgress.status === 'success') { @@ -97,7 +100,7 @@ export function useOrderAsyncExport(storageKey?: string) { clearSavedExportTaskId() try { if (exportTaskProgress.downloadUrl) { - downloadOrderExportFile(exportTaskProgress.downloadUrl) + downloadExportFile(exportTaskProgress.downloadUrl) ElMessage.success(exportTaskProgress.message || '导出完成,文件已开始下载') } else { ElMessage.warning(exportTaskProgress.message || '导出完成,但未返回下载地址') @@ -132,10 +135,10 @@ export function useOrderAsyncExport(storageKey?: string) { exportDialogVisible.value = true try { const res: any = await orderExport(payload) - if (!isOrderIndexApiSuccess(res)) { + if (!isExportApiSuccess(res)) { throw new Error(res?.message || '导出任务提交失败') } - const data = parseOrderExportTaskPayload(res) + const data = parseExportTaskPayload(res) const taskId = String(data.task_id || data.taskId || '').trim() if (!taskId) { throw new Error(res?.message || '导出任务提交失败') diff --git a/src/utils/asyncExportHelpers.ts b/src/utils/asyncExportHelpers.ts new file mode 100644 index 00000000..09a1e988 --- /dev/null +++ b/src/utils/asyncExportHelpers.ts @@ -0,0 +1,78 @@ +/** 异步导出模式:waybill=不含明细(默认),item=含明细 */ +export type ExportMode = 'waybill' | 'item' + +export const EXPORT_MODE_OPTIONS: Array<{ label: string; action: string; divided?: boolean }> = [ + { label: '不含明细', action: 'handleExportWaybill' }, + { label: '含明细', action: 'handleExportItem', divided: true } +] + +const EXPORT_API_SUCCESS_CODES = new Set([0, 1, 200, 20000]) + +export function isExportApiSuccess(res: unknown): boolean { + if (!res || typeof res !== 'object') return false + return EXPORT_API_SUCCESS_CODES.has(Number((res as Record).code)) +} + +/** 解析 export / exportTaskProgress 响应体(兼容 data 嵌套) */ +export function parseExportTaskPayload(res: unknown): Record { + if (!res || typeof res !== 'object') return {} + const root = res as Record + const nested = root.data + if (nested && typeof nested === 'object' && !Array.isArray(nested)) { + if ( + nested.task_id + || nested.taskId + || nested.status + || nested.download_url + || nested.downloadUrl + ) { + return nested + } + if (nested.data && typeof nested.data === 'object') return nested.data + } + return root +} + +export function extractExportDownloadUrl(payload: Record): string { + const direct = payload.download_url || payload.downloadUrl + if (direct) return String(direct).trim() + const nested = payload.result + if (nested && typeof nested === 'object') { + return String(nested.download_url || nested.downloadUrl || '').trim() + } + return '' +} + +export function normalizeExportDownloadUrl(fileUrl: string) { + if (!fileUrl) return '' + if (/^https?:\/\//i.test(fileUrl)) return fileUrl + const normalizedPath = fileUrl.startsWith('/') ? fileUrl : `/${fileUrl}` + const baseApi = String(import.meta.env.VITE_APP_BASE_API || '') + const normalizedBase = baseApi.endsWith('/') ? baseApi.slice(0, -1) : baseApi + if (normalizedBase.startsWith('/')) { + return `${window.location.origin}${normalizedBase}${normalizedPath}` + } + return `${window.location.origin}${normalizedPath}` +} + +export function downloadExportFile(url: string) { + const finalUrl = normalizeExportDownloadUrl(url) + if (!finalUrl) throw new Error('导出文件地址为空') + const link = document.createElement('a') + link.href = finalUrl + link.target = '_blank' + document.body.appendChild(link) + link.click() + link.remove() +} + +export function appendExportMode( + payload: Record, + exportMode: ExportMode = 'waybill' +): Record { + return { + ...payload, + export_mode: exportMode, + exportMode + } +} diff --git a/src/views/order/orderManagement/archiveOrder.vue b/src/views/order/orderManagement/archiveOrder.vue index 9de4fa26..f0e74ffe 100644 --- a/src/views/order/orderManagement/archiveOrder.vue +++ b/src/views/order/orderManagement/archiveOrder.vue @@ -300,6 +300,8 @@ const { exportProgressStatus, exportStatusLabel, handleExport, + handleExportWaybill, + handleExportItem, handleExportSelection } = pageExport @@ -388,6 +390,8 @@ const toolbarLayoutKey = computed(() => const { actionMap: toolbarActionMap } = createSimpleListToolbarController({ loadData, handleExport, + handleExportWaybill, + handleExportItem, handleExportSelection, openColumnConfigPanel, toggleDetailVisible diff --git a/src/views/order/orderManagement/component/OrderToolbarButtonGroup.vue b/src/views/order/orderManagement/component/OrderToolbarButtonGroup.vue index 913c1be2..b9ec21e2 100644 --- a/src/views/order/orderManagement/component/OrderToolbarButtonGroup.vue +++ b/src/views/order/orderManagement/component/OrderToolbarButtonGroup.vue @@ -1,18 +1,45 @@
- - {{ resolveLabel(button.label, button.dynamicLabelKey) }} - +
@@ -185,6 +228,10 @@ watch( flex-wrap: nowrap; } +.order-toolbar-button-group__main :deep(.el-dropdown) { + flex-shrink: 0; +} + .order-toolbar-button-group__overflow-list { display: flex; flex-direction: column; diff --git a/src/views/order/orderManagement/config/order-common-config.ts b/src/views/order/orderManagement/config/order-common-config.ts index def77e7b..1c714631 100644 --- a/src/views/order/orderManagement/config/order-common-config.ts +++ b/src/views/order/orderManagement/config/order-common-config.ts @@ -255,6 +255,9 @@ export interface ToolbarButtonConfig { loadingKey?: string disabledKey?: string action: string + /** 下拉按钮:主按钮点击 action,菜单项使用 dropdownOptions[].action */ + buttonType?: 'default' | 'dropdown' + dropdownOptions?: Array<{ label: string; action: string; divided?: boolean }> } export interface ToolbarApiActionConfig { @@ -286,7 +289,18 @@ export interface PendingBatchAsyncTaskConfig { export const ORDER_TOOLBAR_BUTTONS: Record = { refresh: { key: 'refresh', label: '刷新', type: 'primary', size: 'small', action: 'loadData' }, - export: { key: 'export', label: '导出', size: 'small', loadingKey: 'exportLoading', action: 'handleExport' }, + export: { + key: 'export', + label: '导出', + size: 'small', + loadingKey: 'exportLoading', + action: 'handleExportWaybill', + buttonType: 'dropdown', + dropdownOptions: [ + { label: '不含明细', action: 'handleExportWaybill' }, + { label: '含明细', action: 'handleExportItem', divided: true } + ] + }, exportSelection: { key: 'exportSelection', label: '导出选中', @@ -919,25 +933,17 @@ export const simpleListToolbarButtons = pickToolbarButtons(simpleListToolbarButt -/** ScanBox 筛选字段分组 */ -export const SCAN_FIELD_GROUPS = { - order: '单号信息', - shop: '店铺平台', - receiver: '收货信息', - logistics: '物流信息', - status: '订单状态', - warehouse: '仓储流程', - time: '时间范围', -} as const +/** ScanBox 筛选字段分组:基础信息 + 工作流程(工作流程字段以 label 为分组名) */ +export const SCAN_BASIC_INFO_GROUP = '订单基础信息' -type ScanFieldGroupKey = keyof typeof SCAN_FIELD_GROUPS +/** 为 ScanBox 基础信息字段附加分组标签 */ +export function scanBasicField(field: Record) { + return { ...field, group: SCAN_BASIC_INFO_GROUP } +} -/** 为 ScanBox 字段附加分组标签 */ -export function scanField( - group: G, - field: Record -) { - return { ...field, group: SCAN_FIELD_GROUPS[group] } +/** 为 ScanBox 工作流程字段附加分组标签(按字段 label 独立分组) */ +export function scanWorkflowField(field: Record) { + return { ...field, group: field.label } } /** 通用下拉选项 */ @@ -954,14 +960,12 @@ export const buyerMessageHasFilterOptions = [ export const syncStatusFilterOptionsBasic = [ { label: '待同步', value: 'padding' }, { label: '已同步', value: 'fin' }, - { label: '错误', value: 'error' }, ] export const syncStatusFilterOptionsExtended = [ { label: '待同步', value: 'padding' }, // { label: '同步中', value: 'pending' }, { label: '已同步', value: 'fin' }, - { label: '错误', value: 'error' }, { label: '未同步', value: 'none' }, ] @@ -969,14 +973,12 @@ export const storageStatusFilterOptions = [ { label: '未分配', value: 'none' }, // { label: '分配中', value: 'padding' }, { label: '已完成', value: 'fin' }, - { label: '错误', value: 'error' }, ] export const postStatusFilterOptions = [ { label: '未分配', value: 'none' }, // { label: '分配中', value: 'padding' }, { label: '已分配', value: 'fin' }, - { label: '错误', value: 'error' }, ] export const postStatusFilterOptionsExtended = [ @@ -1017,7 +1019,6 @@ export const pendingOrderStatusFilterOptions = [ { label: '待审核', value: 'pedding' }, { label: '已创建', value: 'created' }, { label: '已取消', value: 'cancel' }, - { label: '错误', value: 'error' }, { label: '售后异常', value: 'after-sales-error' }, { label: '已完成', value: 'finished' }, { label: '已作废', value: 'cancelled' }, @@ -1027,13 +1028,11 @@ export const pendingOrderStatusFilterOptions = [ export const reviewOrderStatusFilterOptions = [ { label: '待审核', value: 'pedding' }, { label: '已创建', value: 'created' }, - { label: '错误', value: 'error' }, ] export const exceptionOrderStatusFilterOptions = [ { label: '待审核', value: 'pedding' }, { label: '已创建', value: 'created' }, - { label: '错误', value: 'error' }, { label: '已作废', value: 'cancelled' }, { label: '已归档', value: 'archived' }, ] @@ -1041,38 +1040,61 @@ export const exceptionOrderStatusFilterOptions = [ export const archiveOrderStatusFilterOptions = [ { label: '待审核', value: 'pedding' }, { label: '已创建', value: 'created' }, - { label: '错误', value: 'error' }, { label: '已完成', value: 'finished' }, { label: '已作废', value: 'cancelled' }, { label: '已归档', value: 'archived' }, ] -/** 可复用 ScanBox 字段片段 */ -export const storeScanField = scanField('order', { label: '货主', value: 'store_id', type: 'select', multiple: true, options: [] }) -export const orderFlagScanField = scanField('order', { label: '订单标记', value: 'order_flag', type: 'text', operators: ['like', 'notlike'], defaultOperator: 'like' }) -export const waveNoScanField = scanField('order', { label: '波次号', value: 'wave_no', type: 'text' }) -export const deliveryOrderCodeScanField = scanField('order', { label: '发货单号', value: 'delivery_order_code', type: 'text' }) -export const pendingOrderCodeScanField = scanField('order', { label: '发货单号', value: 'order_code', type: 'text' }) -export const exceptionOrderCodeScanField = scanField('order', { label: '发货单号', value: 'order_code', type: 'text' }) -export const shopNickScanField = scanField('shop', { label: '店铺名称', value: 'shop_nick', type: 'text' }) -export const sysPlatformNameScanField = scanField('shop', { label: '来源', value: 'sys_platform_name', type: 'select', options: [] }) -export const sysPlatformCodeScanField = scanField('shop', { label: '平台编码', value: 'sys_platform_code', type: 'select', options: [] }) -export const buyerNickScanField = scanField('shop', { label: '买家昵称', value: 'buyer_nick', type: 'text' }) -export const receiverNameScanField = scanField('receiver', { label: '收件人', value: 'name', type: 'text' }) -export const receiverMobileScanField = scanField('receiver', { label: '电话', value: 'mobile', type: 'text' }) -export const receiverProvinceScanField = scanField('receiver', { label: '省份', value: 'province', type: 'text' }) -export const receiverCityScanField = scanField('receiver', { label: '城市', value: 'city', type: 'text' }) -export const receiverAreaScanField = scanField('receiver', { label: '区县', value: 'area', type: 'text' }) -export const logisticsNameScanField = scanField('logistics', { label: '物流公司', value: 'logistics_name', type: 'select', options: [] }) -export const waybillCodesScanField = scanField('logistics', { label: '快递单号', value: 'waybill_codes', type: 'text' }) -export const expressCodeScanField = scanField('logistics', { label: '快递单号', value: 'express_code', type: 'text' }) -export const createAtRangeScanField = scanField('time', { label: '创建时间', value: 'create_at', type: 'datetimerange' }) -export const payTimeRangeScanField = scanField('time', { label: '支付时间', value: 'pay_time', type: 'datetimerange' }) -export const deliveryTimeRangeScanField = scanField('time', { label: '配送时间', value: 'delivery_time', type: 'datetimerange' }) -export const placeOrderTimeRangeScanField = scanField('time', { label: '下单时间', value: 'place_order_time', type: 'datetimerange' }) +export const recheckStatusFilterOptions = [ + { label: '未复核', value: 'none' }, + { label: '已复核', value: 'fin' } +] + +/** 单号类字段:支持 IN(逗号分隔)批量查询 */ +export const ORDER_BULK_SEARCH_OPERATORS = ['eq', 'ne', 'like', 'notlike', 'contains', 'in', 'notin', 'startswith', 'endswith'] + +/** 可复用 ScanBox 字段片段(基础信息) */ +export const storeScanField = scanBasicField({ label: '货主', value: 'store_id', type: 'select', multiple: true, options: [] }) +export const orderFlagScanField = scanBasicField({ label: '订单标记', value: 'order_flag', type: 'text', operators: ['like', 'notlike'], defaultOperator: 'like' }) +export const waveNoScanField = scanBasicField({ label: '波次号', value: 'wave_no', type: 'text', operators: ORDER_BULK_SEARCH_OPERATORS, defaultOperator: 'eq' }) +export const deliveryOrderCodeScanField = scanBasicField({ label: '发货单号', value: 'delivery_order_code', type: 'text', operators: ORDER_BULK_SEARCH_OPERATORS, defaultOperator: 'eq' }) +export const pendingOrderCodeScanField = scanBasicField({ label: '发货单号', value: 'order_code', type: 'text', operators: ORDER_BULK_SEARCH_OPERATORS, defaultOperator: 'eq' }) +export const exceptionOrderCodeScanField = scanBasicField({ label: '发货单号', value: 'order_code', type: 'text', operators: ORDER_BULK_SEARCH_OPERATORS, defaultOperator: 'eq' }) +export const shopNickScanField = scanBasicField({ label: '店铺名称', value: 'shop_nick', type: 'text' }) +export const sysPlatformNameScanField = scanBasicField({ label: '来源', value: 'sys_platform_name', type: 'select', options: [] }) +export const sysPlatformCodeScanField = scanBasicField({ label: '平台编码', value: 'sys_platform_code', type: 'select', options: [] }) +export const buyerNickScanField = scanBasicField({ label: '买家昵称', value: 'buyer_nick', type: 'text' }) +export const receiverNameScanField = scanBasicField({ label: '收件人', value: 'name', type: 'text' }) +export const receiverMobileScanField = scanBasicField({ label: '电话', value: 'mobile', type: 'text' }) +export const receiverProvinceScanField = scanBasicField({ label: '省份', value: 'province', type: 'text' }) +export const receiverCityScanField = scanBasicField({ label: '城市', value: 'city', type: 'text' }) +export const receiverAreaScanField = scanBasicField({ label: '区县', value: 'area', type: 'text' }) +export const logisticsNameScanField = scanBasicField({ label: '物流公司', value: 'logistics_name', type: 'select', options: [] }) +export const waybillCodesScanField = scanBasicField({ label: '快递单号', value: 'waybill_codes', type: 'text', operators: ORDER_BULK_SEARCH_OPERATORS, defaultOperator: 'eq' }) +export const expressCodeScanField = scanBasicField({ label: '快递单号', value: 'express_code', type: 'text', operators: ORDER_BULK_SEARCH_OPERATORS, defaultOperator: 'eq' }) +export const createAtRangeScanField = scanBasicField({ label: '创建时间', value: 'create_at', type: 'datetimerange' }) +export const payTimeRangeScanField = scanBasicField({ label: '支付时间', value: 'pay_time', type: 'datetimerange' }) +export const deliveryTimeRangeScanField = scanBasicField({ label: '配送时间', value: 'delivery_time', type: 'datetimerange' }) +export const placeOrderTimeRangeScanField = scanBasicField({ label: '下单时间', value: 'place_order_time', type: 'datetimerange' }) +export const isUrgencyScanField = scanBasicField({ label: '是否紧急', value: 'is_urgency', type: 'select', options: isUrgencyFilterOptions }) +export const buyerMessageHasScanField = scanBasicField({ label: '有无留言', value: 'buyer_message_has', type: 'select', options: buyerMessageHasFilterOptions }) +export const buyerMessageScanField = scanBasicField({ label: '买家留言', value: 'buyer_message', type: 'text' }) + +/** 可复用 ScanBox 字段片段(工作流程) */ +export const orderStatusScanField = (options: Array<{ label: string; value: string }>) => + scanWorkflowField({ label: '订单状态', value: 'status', type: 'select', options }) +export const syncStatusScanField = scanWorkflowField({ label: '同步状态', value: 'sync_status', type: 'select', options: syncStatusFilterOptionsBasic }) +export const recheckStatusScanField = scanWorkflowField({ label: '复核', value: 'recheck_status', type: 'select', options: recheckStatusFilterOptions }) +export const storageStatusScanField = scanWorkflowField({ label: '储位', value: 'storage_status', type: 'select', options: storageStatusFilterOptions }) +export const postStatusScanField = scanWorkflowField({ label: '快递', value: 'post_status', type: 'select', options: postStatusFilterOptions }) +export const pickStatusScanField = scanWorkflowField({ label: '拣货状态', value: 'pick_status', type: 'select', options: pickStatusFilterOptions }) +export const packStatusScanField = scanWorkflowField({ label: '打包状态', value: 'pack_status', type: 'select', options: packStatusFilterOptions }) +export const printStatusScanField = scanWorkflowField({ label: '打印状态', value: 'print_status', type: 'select', options: printStatusFilterOptions }) +export const outboundStatusScanField = scanWorkflowField({ label: '出库状态', value: 'outbound_status', type: 'select', options: outboundStatusFilterOptions }) +export const interceptStatusScanField = scanWorkflowField({ label: '拦截状态', value: 'intercept_status', type: 'select', options: interceptStatusFilterOptions }) /** ScanBox:波次分配 → where.wave_id 为 { operator: 'eq'|'ne', value: 0 } */ -export const waveAssignmentScanField = scanField('order', { +export const waveAssignmentScanField = scanBasicField({ label: '波次分配', value: 'wave_id', type: 'select', @@ -1084,7 +1106,7 @@ export const waveAssignmentScanField = scanField('order', { }) /** ScanBox:快递公司(快递编码),选项由 index.getExpressList + fillExpressCompanyScanFieldOptions 注入 */ -export const expressCompanyScanField = scanField('logistics', { +export const expressCompanyScanField = scanBasicField({ label: '快递公司', value: 'logistics_code', type: 'select', @@ -1159,34 +1181,29 @@ export function fillStoreScanFieldOptions(availableFields: any[], rawStores: any // deliveryOrder相关配置 export const deliveryAvailableFields = [ - // 单号信息 + // 订单基础信息 storeScanField, deliveryOrderCodeScanField, orderFlagScanField, waveAssignmentScanField, waveNoScanField, - // 店铺平台 shopNickScanField, sysPlatformNameScanField, - // 收货信息 receiverNameScanField, receiverMobileScanField, - scanField('receiver', { label: '有无留言', value: 'buyer_message_has', type: 'select', options: buyerMessageHasFilterOptions }), - scanField('receiver', { label: '买家留言', value: 'buyer_message', type: 'text' }), - // 物流信息 + buyerMessageHasScanField, + buyerMessageScanField, logisticsNameScanField, expressCompanyScanField, - scanField('logistics', { label: '物流单号', value: 'waybill_codes', type: 'text' }), - // 订单状态 - scanField('status', { label: '是否紧急', value: 'is_urgency', type: 'select', options: isUrgencyFilterOptions }), - scanField('status', { label: '同步状态', value: 'sync_status', type: 'select', options: syncStatusFilterOptionsBasic }), - // 仓储流程 - scanField('warehouse', { label: '出库状态', value: 'outbound_status', type: 'select', options: outboundStatusFilterOptions }), - scanField('warehouse', { label: '打印状态', value: 'print_status', type: 'select', options: printStatusFilterOptions }), - // 时间范围 + waybillCodesScanField, + isUrgencyScanField, createAtRangeScanField, payTimeRangeScanField, deliveryTimeRangeScanField, + // 工作流程(按订单作业顺序) + syncStatusScanField, + outboundStatusScanField, + printStatusScanField, ] export const deliveryColumns = [ @@ -1340,39 +1357,26 @@ export const deliveryOrderToolbarButtonKeys = [ ] export const deliveryOrderToolbarButtons = pickToolbarButtons(deliveryOrderToolbarButtonKeys) - - - - -export const recheckStatusFilterOptions = [ - { label: '未复核', value: 'none' }, - { label: '已复核', value: 'fin' } -] - // revieworder相关配置 export const reviewAvailableFields = [ - // 单号信息 + // 订单基础信息 storeScanField, deliveryOrderCodeScanField, waveAssignmentScanField, waveNoScanField, - // 店铺平台 shopNickScanField, sysPlatformCodeScanField, - // 收货信息 receiverNameScanField, receiverMobileScanField, - scanField('receiver', { label: '有无留言', value: 'buyer_message_has', type: 'select', options: buyerMessageHasFilterOptions }), - scanField('receiver', { label: '买家留言', value: 'buyer_message', type: 'text' }), - // 物流信息 + buyerMessageHasScanField, + buyerMessageScanField, expressCompanyScanField, - // 订单状态 - scanField('status', { label: '订单状态', value: 'status', type: 'select', options: reviewOrderStatusFilterOptions }), - scanField('status', { label: '是否紧急', value: 'is_urgency', type: 'select', options: isUrgencyFilterOptions }), - scanField('status', { label: '同步状态', value: 'sync_status', type: 'select', options: syncStatusFilterOptionsBasic }), - scanField('status', { label: '复核', value: 'recheck_status', type: 'select', options: recheckStatusFilterOptions }), - // 时间范围 + isUrgencyScanField, createAtRangeScanField, + // 工作流程(按订单作业顺序) + orderStatusScanField(reviewOrderStatusFilterOptions), + syncStatusScanField, + recheckStatusScanField, ] export const reviewColums = [ @@ -1498,41 +1502,36 @@ export const outboundToolbarButtons = pickToolbarButtons(outboundToolbarButtonKe // pendingOrder相关配置 export const pendingAvailableFields = [ - // 单号信息 + // 订单基础信息 storeScanField, pendingOrderCodeScanField, orderFlagScanField, waveAssignmentScanField, waveNoScanField, - // 店铺平台 shopNickScanField, sysPlatformNameScanField, - // 物流信息 logisticsNameScanField, expressCompanyScanField, waybillCodesScanField, - // 订单状态 - scanField('status', { label: '订单状态', value: 'status', type: 'select', options: pendingOrderStatusFilterOptions }), - scanField('status', { label: '是否紧急', value: 'is_urgency', type: 'select', options: isUrgencyFilterOptions }), - scanField('status', { label: '同步状态', value: 'sync_status', type: 'select', options: syncStatusFilterOptionsBasic }), - scanField('status', { label: '复核', value: 'recheck_status', type: 'select', options: recheckStatusFilterOptions }), - // 仓储流程 - scanField('warehouse', { label: '储位', value: 'storage_status', type: 'select', options: storageStatusFilterOptions }), - scanField('warehouse', { label: '快递', value: 'post_status', type: 'select', options: postStatusFilterOptions }), - scanField('warehouse', { label: '拣货状态', value: 'pick_status', type: 'select', options: pickStatusFilterOptions }), - scanField('warehouse', { label: '打包状态', value: 'pack_status', type: 'select', options: packStatusFilterOptions }), - scanField('warehouse', { label: '打印状态', value: 'print_status', type: 'select', options: printStatusFilterOptions }), - // 收货信息 receiverNameScanField, receiverMobileScanField, receiverProvinceScanField, receiverCityScanField, receiverAreaScanField, - scanField('receiver', { label: '有无留言', value: 'buyer_message_has', type: 'select', options: buyerMessageHasFilterOptions }), - scanField('receiver', { label: '买家留言', value: 'buyer_message', type: 'text' }), - // 时间范围 + buyerMessageHasScanField, + buyerMessageScanField, + isUrgencyScanField, placeOrderTimeRangeScanField, createAtRangeScanField, + // 工作流程(按订单作业顺序) + orderStatusScanField(pendingOrderStatusFilterOptions), + syncStatusScanField, + recheckStatusScanField, + storageStatusScanField, + postStatusScanField, + pickStatusScanField, + packStatusScanField, + printStatusScanField, ] export const pendingCloums = [ @@ -1766,18 +1765,16 @@ export const workbenchStatusOptions = [ ] export const workbenchAvailableFields = [ - // 单号信息 + // 订单基础信息 deliveryOrderCodeScanField, waveAssignmentScanField, waveNoScanField, - // 店铺平台 buyerNickScanField, - // 订单状态 - scanField('status', { label: '订单状态', value: 'status', type: 'select', options: workbenchStatusOptions }), - scanField('status', { label: '是否紧急', value: 'is_urgency', type: 'select', options: isUrgencyFilterOptions }), - // 收货信息 - scanField('receiver', { label: '有无留言', value: 'buyer_message_has', type: 'select', options: buyerMessageHasFilterOptions }), - scanField('receiver', { label: '买家留言', value: 'buyer_message', type: 'text' }), + buyerMessageHasScanField, + buyerMessageScanField, + isUrgencyScanField, + // 工作流程 + orderStatusScanField(workbenchStatusOptions), ] export const workbenchColumns = [ @@ -1823,33 +1820,29 @@ export const workbenchBadgeItems = [ // expectionOrder相关配置 export const expectionOrderAvailableFields = [ - // 单号信息 + // 订单基础信息 storeScanField, exceptionOrderCodeScanField, deliveryOrderCodeScanField, orderFlagScanField, waveAssignmentScanField, waveNoScanField, - // 物流信息 logisticsNameScanField, expressCompanyScanField, expressCodeScanField, - // 订单状态 - scanField('status', { label: '是否紧急', value: 'is_urgency', type: 'select', options: isUrgencyFilterOptions }), - scanField('status', { label: '拦截状态', value: 'intercept_status', type: 'select', options: interceptStatusFilterOptions }), - scanField('status', { label: '订单状态', value: 'status', type: 'select', options: exceptionOrderStatusFilterOptions }), - scanField('status', { label: '同步状态', value: 'sync_status', type: 'select', options: syncStatusFilterOptionsBasic }), - // 仓储流程 - scanField('warehouse', { label: '储位', value: 'storage_status', type: 'select', options: storageStatusFilterOptions }), - scanField('warehouse', { label: '快递', value: 'post_status', type: 'select', options: postStatusFilterOptions }), - scanField('warehouse', { label: '打印状态', value: 'print_status', type: 'select', options: printStatusFilterOptions }), - scanField('warehouse', { label: '拣货状态', value: 'pick_status', type: 'select', options: pickStatusFilterOptions }), - scanField('warehouse', { label: '打包状态', value: 'pack_status', type: 'select', options: packStatusFilterOptions }), - // 收货信息 - scanField('receiver', { label: '有无留言', value: 'buyer_message_has', type: 'select', options: buyerMessageHasFilterOptions }), - scanField('receiver', { label: '买家留言', value: 'buyer_message', type: 'text' }), - // 时间范围 + buyerMessageHasScanField, + buyerMessageScanField, + isUrgencyScanField, createAtRangeScanField, + // 工作流程(按订单作业顺序) + orderStatusScanField(exceptionOrderStatusFilterOptions), + syncStatusScanField, + storageStatusScanField, + postStatusScanField, + pickStatusScanField, + packStatusScanField, + printStatusScanField, + interceptStatusScanField, ] export const expectionColumns = [ @@ -1933,29 +1926,25 @@ export const expectionOrderbuttonList: any[] = [ // deliveryException相关配置 export const archiveAvailableFields = [ - // 单号信息 + // 订单基础信息 storeScanField, exceptionOrderCodeScanField, deliveryOrderCodeScanField, waveAssignmentScanField, waveNoScanField, - // 物流信息 - expressCompanyScanField, - // 订单状态 - scanField('status', { label: '是否紧急', value: 'is_urgency', type: 'select', options: isUrgencyFilterOptions }), - scanField('status', { label: '订单状态', value: 'status', type: 'select', options: archiveOrderStatusFilterOptions }), - scanField('status', { label: '同步状态', value: 'sync_status', type: 'select', options: syncStatusFilterOptionsBasic }), - // 仓储流程 - scanField('warehouse', { label: '出库状态', value: 'outbound_status', type: 'select', options: outboundStatusFilterOptions }), - scanField('warehouse', { label: '拣货状态', value: 'pick_status', type: 'select', options: pickStatusFilterOptions }), - scanField('warehouse', { label: '打包状态', value: 'pack_status', type: 'select', options: packStatusFilterOptions }), - // 店铺平台 shopNickScanField, - // 收货信息 + expressCompanyScanField, receiverNameScanField, receiverMobileScanField, - scanField('receiver', { label: '有无留言', value: 'buyer_message_has', type: 'select', options: buyerMessageHasFilterOptions }), - scanField('receiver', { label: '买家留言', value: 'buyer_message', type: 'text' }), + buyerMessageHasScanField, + buyerMessageScanField, + isUrgencyScanField, + // 工作流程(按订单作业顺序) + orderStatusScanField(archiveOrderStatusFilterOptions), + syncStatusScanField, + outboundStatusScanField, + pickStatusScanField, + packStatusScanField, ] export const archiveColumns = [ diff --git a/src/views/order/orderManagement/deliveryException.vue b/src/views/order/orderManagement/deliveryException.vue index dc0f74bd..85a4496c 100644 --- a/src/views/order/orderManagement/deliveryException.vue +++ b/src/views/order/orderManagement/deliveryException.vue @@ -295,6 +295,8 @@ const { exportProgressStatus, exportStatusLabel, handleExport, + handleExportWaybill, + handleExportItem, handleExportSelection } = pageExport @@ -383,6 +385,8 @@ const toolbarLayoutKey = computed(() => const { actionMap: toolbarActionMap } = createSimpleListToolbarController({ loadData, handleExport, + handleExportWaybill, + handleExportItem, handleExportSelection, openColumnConfigPanel, toggleDetailVisible diff --git a/src/views/order/orderManagement/deliveryOrder.vue b/src/views/order/orderManagement/deliveryOrder.vue index a53017e4..08773a93 100644 --- a/src/views/order/orderManagement/deliveryOrder.vue +++ b/src/views/order/orderManagement/deliveryOrder.vue @@ -451,6 +451,8 @@ const { exportProgressStatus, exportStatusLabel, handleExport, + handleExportWaybill, + handleExportItem, handleExportSelection } = pageExport @@ -523,6 +525,8 @@ const toolbarLayoutKey = computed(() => const { actionMap: toolbarActionMap } = createSimpleListToolbarController({ loadData, handleExport, + handleExportWaybill, + handleExportItem, handleExportSelection, openColumnConfigPanel, toggleDetailVisible diff --git a/src/views/order/orderManagement/entrustWarehouse.vue b/src/views/order/orderManagement/entrustWarehouse.vue index 35363aa3..d207e50e 100644 --- a/src/views/order/orderManagement/entrustWarehouse.vue +++ b/src/views/order/orderManagement/entrustWarehouse.vue @@ -295,6 +295,8 @@ const { exportProgressStatus, exportStatusLabel, handleExport, + handleExportWaybill, + handleExportItem, handleExportSelection } = pageExport @@ -383,6 +385,8 @@ const toolbarLayoutKey = computed(() => const { actionMap: toolbarActionMap } = createSimpleListToolbarController({ loadData, handleExport, + handleExportWaybill, + handleExportItem, handleExportSelection, openColumnConfigPanel, toggleDetailVisible diff --git a/src/views/order/orderManagement/exceptionOrder.vue b/src/views/order/orderManagement/exceptionOrder.vue index 7a35cd5c..0d112b07 100644 --- a/src/views/order/orderManagement/exceptionOrder.vue +++ b/src/views/order/orderManagement/exceptionOrder.vue @@ -722,6 +722,8 @@ const { exportProgressStatus, exportStatusLabel, handleExport, + handleExportWaybill, + handleExportItem, handleExportSelection } = pageExport @@ -957,6 +959,8 @@ const { } = createPendingToolbarController({ loadData, handleExport, + handleExportWaybill, + handleExportItem, handleExportSelection, openColumnConfigPanel, toggleDetailVisible, diff --git a/src/views/order/orderManagement/outboundOrder.vue b/src/views/order/orderManagement/outboundOrder.vue index ea0ed265..c1ade151 100644 --- a/src/views/order/orderManagement/outboundOrder.vue +++ b/src/views/order/orderManagement/outboundOrder.vue @@ -303,6 +303,8 @@ const { exportProgressStatus, exportStatusLabel, handleExport, + handleExportWaybill, + handleExportItem, handleExportSelection } = pageExport @@ -489,6 +491,8 @@ const toolbarLayoutKey = computed(() => const { actionMap: baseToolbarActionMap } = createSimpleListToolbarController({ loadData, handleExport, + handleExportWaybill, + handleExportItem, handleExportSelection, openColumnConfigPanel, toggleDetailVisible diff --git a/src/views/order/orderManagement/pendingOrder.vue b/src/views/order/orderManagement/pendingOrder.vue index e7d215f5..5bdaa299 100644 --- a/src/views/order/orderManagement/pendingOrder.vue +++ b/src/views/order/orderManagement/pendingOrder.vue @@ -605,6 +605,8 @@ const { exportProgressStatus, exportStatusLabel, handleExport, + handleExportWaybill, + handleExportItem, handleExportSelection } = pageExport @@ -736,6 +738,8 @@ const { } = createPendingToolbarController({ loadData, handleExport, + handleExportWaybill, + handleExportItem, handleExportSelection, openColumnConfigPanel, toggleDetailVisible, diff --git a/src/views/order/orderManagement/reviewOrder.vue b/src/views/order/orderManagement/reviewOrder.vue index 42ef8bb9..3b21e709 100644 --- a/src/views/order/orderManagement/reviewOrder.vue +++ b/src/views/order/orderManagement/reviewOrder.vue @@ -373,6 +373,8 @@ const { exportProgressStatus, exportStatusLabel, handleExport, + handleExportWaybill, + handleExportItem, handleExportSelection } = pageExport @@ -454,6 +456,8 @@ const { } = createReviewToolbarController({ loadData, handleExport, + handleExportWaybill, + handleExportItem, handleExportSelection, openColumnConfigPanel, toggleDetailVisible, diff --git a/src/views/order/orderManagement/utils/order-index-helpers.ts b/src/views/order/orderManagement/utils/order-index-helpers.ts index a6d4985b..12342ec5 100644 --- a/src/views/order/orderManagement/utils/order-index-helpers.ts +++ b/src/views/order/orderManagement/utils/order-index-helpers.ts @@ -1,4 +1,18 @@ -import type { UpdateExpressWeighingWeightResponse } from '@/api/order.index/orderindex' +import type { OrderExportMode, UpdateExpressWeighingWeightResponse } from '@/api/order.index/orderindex' + +export type { OrderExportMode } +export { + isExportApiSuccess as isOrderIndexApiSuccess, + parseExportTaskPayload as parseOrderExportTaskPayload, + normalizeExportDownloadUrl as normalizeOrderDownloadUrl, + downloadExportFile as downloadOrderExportFile +} from '@/utils/asyncExportHelpers' + +/** order.export 导出模式选项 */ +export const ORDER_EXPORT_MODE_OPTIONS: Array<{ label: string; value: OrderExportMode }> = [ + { label: '不含明细', value: 'waybill' }, + { label: '含明细', value: 'item' } +] export type OrderExportScope = { table_type?: string @@ -44,10 +58,6 @@ export const ORDER_INDEX_EXPORT_SCOPES: Record = { archiveOrder: { table_type: 'history', module: 'archiveOrder' } } -export function isOrderIndexApiSuccess(res: any) { - return !!res && [0, 1, 200, 20000].includes(res.code) -} - export function parseOrderListResponse(res: any): ParsedOrderListResponse { const pick = (obj: any) => { if (!obj || typeof obj !== 'object') { @@ -256,39 +266,6 @@ export function parseOrderLogsResponse(res: any): { list: any[]; total: number } return pick(level1) } -export function parseOrderExportTaskPayload(res: any): Record { - if (!res || typeof res !== 'object') return {} - const nested = res.data - if (nested && typeof nested === 'object' && !Array.isArray(nested)) { - if (nested.task_id || nested.taskId || nested.status) return nested - if (nested.data && typeof nested.data === 'object') return nested.data - } - return res -} - -export function normalizeOrderDownloadUrl(fileUrl: string) { - if (!fileUrl) return '' - if (/^https?:\/\//i.test(fileUrl)) return fileUrl - const normalizedPath = fileUrl.startsWith('/') ? fileUrl : `/${fileUrl}` - const baseApi = String(import.meta.env.VITE_APP_BASE_API || '') - const normalizedBase = baseApi.endsWith('/') ? baseApi.slice(0, -1) : baseApi - if (normalizedBase.startsWith('/')) { - return `${window.location.origin}${normalizedBase}${normalizedPath}` - } - return `${window.location.origin}${normalizedPath}` -} - -export function downloadOrderExportFile(url: string) { - const finalUrl = normalizeOrderDownloadUrl(url) - if (!finalUrl) throw new Error('导出文件地址为空') - const link = document.createElement('a') - link.href = finalUrl - link.target = '_blank' - document.body.appendChild(link) - link.click() - link.remove() -} - export function sanitizeOrderListWhere(where: Record) { const next = { ...where } delete next.warehouse_id diff --git a/src/views/order/orderManagement/utils/order-page-export.ts b/src/views/order/orderManagement/utils/order-page-export.ts index 1a2655a4..9dbaf682 100644 --- a/src/views/order/orderManagement/utils/order-page-export.ts +++ b/src/views/order/orderManagement/utils/order-page-export.ts @@ -1,5 +1,6 @@ import { ref, type Ref } from 'vue' import { ElMessage } from 'element-plus' +import type { OrderExportMode } from '@/api/order.index/orderindex' import { useOrderAsyncExport } from '@/composables/useOrderAsyncExport' import { ORDER_INDEX_EXPORT_SCOPES, sanitizeOrderListWhere } from './order-index-helpers' import { exportUpperTableRows } from './export' @@ -17,7 +18,7 @@ export function createOrderPageExport(options: { const asyncExport = useOrderAsyncExport(options.storageKey) const exportSelectionLoading = ref(false) - async function handleExport() { + async function handleExport(exportMode: OrderExportMode = 'waybill') { const scope = ORDER_INDEX_EXPORT_SCOPES[options.scopeKey] if (!scope) { ElMessage.error('未配置导出范围') @@ -26,10 +27,19 @@ export function createOrderPageExport(options: { await asyncExport.submitExportTask({ ...scope, where: sanitizeOrderListWhere(options.buildWhere()), - sort: options.buildSort?.() + sort: options.buildSort?.(), + export_mode: exportMode }) } + async function handleExportWaybill() { + await handleExport('waybill') + } + + async function handleExportItem() { + await handleExport('item') + } + async function handleExportSelection() { if (!options.selectionRows.value.length) { ElMessage.warning('请先勾选要导出的订单') @@ -54,7 +64,9 @@ export function createOrderPageExport(options: { return { ...asyncExport, exportSelectionLoading, - handleExport, + handleExport: handleExportWaybill, + handleExportWaybill, + handleExportItem, handleExportSelection } } diff --git a/src/views/order/orderManagement/utils/toolbar-actions.ts b/src/views/order/orderManagement/utils/toolbar-actions.ts index 180e1312..a0b0fc9b 100644 --- a/src/views/order/orderManagement/utils/toolbar-actions.ts +++ b/src/views/order/orderManagement/utils/toolbar-actions.ts @@ -15,6 +15,20 @@ import { navigateToSandanWaveTab } from '@/utils/wave-order-nav' type ActionHandler = () => void | Promise type OrderId = number | string +function bindExportToolbarActions(params: { + handleExport: () => Promise + handleExportWaybill?: () => Promise + handleExportItem?: () => Promise + handleExportSelection?: () => Promise +}) { + return { + handleExport: params.handleExport, + handleExportWaybill: params.handleExportWaybill || params.handleExport, + handleExportItem: params.handleExportItem || params.handleExport, + ...(params.handleExportSelection ? { handleExportSelection: params.handleExportSelection } : {}) + } +} + function buildPayload(ids: OrderId[], config: ToolbarApiActionConfig) { if (!config.payloadKey) return ids return { [config.payloadKey]: ids } @@ -212,6 +226,8 @@ export function createReviewToolbarActionMap(params: { export function createReviewToolbarController(params: { loadData: () => Promise handleExport: () => Promise + handleExportWaybill?: () => Promise + handleExportItem?: () => Promise handleExportSelection?: () => Promise openColumnConfigPanel: () => void toggleDetailVisible: () => void @@ -225,8 +241,7 @@ export function createReviewToolbarController(params: { const actionMap = createReviewToolbarActionMap({ baseActions: { loadData: params.loadData, - handleExport: params.handleExport, - ...(params.handleExportSelection ? { handleExportSelection: params.handleExportSelection } : {}), + ...bindExportToolbarActions(params), openColumnConfigPanel: params.openColumnConfigPanel, toggleDetailVisible: params.toggleDetailVisible, openCreateOrderDialog: params.openCreateOrderDialog @@ -341,6 +356,8 @@ function getApiResponsePayload>(response: any): T { export function createPendingToolbarController(params: { loadData: () => Promise handleExport: () => Promise + handleExportWaybill?: () => Promise + handleExportItem?: () => Promise handleExportSelection?: () => Promise openColumnConfigPanel: () => void toggleDetailVisible: () => void @@ -493,8 +510,7 @@ export function createPendingToolbarController(params: { const actionMap = createPendingToolbarActionMap({ baseActions: { loadData: params.loadData, - handleExport: params.handleExport, - ...(params.handleExportSelection ? { handleExportSelection: params.handleExportSelection } : {}), + ...bindExportToolbarActions(params), openColumnConfigPanel: params.openColumnConfigPanel, toggleDetailVisible: params.toggleDetailVisible, openStorageAllocateDialog: () => openStorageDialog('allocate'), @@ -1180,14 +1196,15 @@ export function createPendingToolbarController(params: { export function createSimpleListToolbarController(params: { loadData: () => Promise handleExport: () => Promise + handleExportWaybill?: () => Promise + handleExportItem?: () => Promise handleExportSelection?: () => Promise openColumnConfigPanel: () => void toggleDetailVisible: () => void }) { const actionMap: Record void | Promise> = { loadData: params.loadData, - handleExport: params.handleExport, - ...(params.handleExportSelection ? { handleExportSelection: params.handleExportSelection } : {}), + ...bindExportToolbarActions(params), openColumnConfigPanel: params.openColumnConfigPanel, toggleDetailVisible: params.toggleDetailVisible } diff --git a/src/views/order/waveOrder/GroupWaveBatchListPanel.vue b/src/views/order/waveOrder/GroupWaveBatchListPanel.vue index 03c3ec5b..0044edb2 100644 --- a/src/views/order/waveOrder/GroupWaveBatchListPanel.vue +++ b/src/views/order/waveOrder/GroupWaveBatchListPanel.vue @@ -1903,6 +1903,7 @@ async function openBatchPrintDialog(rows: any[]) { Object.entries(waveGroupMap).forEach(([wid, orders]) => { const processedOrders = orders.map(normalizePrintOrder) const first = processedOrders[0] + if (!first) return nextMap[wid] = { ...first, wave_no: String(first.wave_no ?? first.wave_code ?? first.batch_no ?? wid), diff --git a/src/views/order/waveOrder/SandanWaveBatchListPanel.vue b/src/views/order/waveOrder/SandanWaveBatchListPanel.vue index 3edc1312..b6b49605 100644 --- a/src/views/order/waveOrder/SandanWaveBatchListPanel.vue +++ b/src/views/order/waveOrder/SandanWaveBatchListPanel.vue @@ -1421,6 +1421,7 @@ async function handleBatchPrint() { Object.entries(waveGroupMap).forEach(([wid, orders]) => { const processedOrders = orders.map(normalizePrintOrder) const first = processedOrders[0] + if (!first) return nextMap[wid] = { ...first, wave_no: String(first.wave_no ?? first.wave_code ?? first.batch_no ?? wid), details: processedOrders } }) @@ -1515,7 +1516,9 @@ async function handleBatchPrintInternal(rows: any[]) { const nextMap: Record = {} Object.entries(waveGroupMap).forEach(([wid, orders]) => { const p = orders.map(normalizePrintOrder) - nextMap[wid] = { ...p[0], wave_no: String(p[0].wave_no ?? p[0].wave_code ?? p[0].batch_no ?? wid), details: p } + const first = p[0] + if (!first) return + nextMap[wid] = { ...first, wave_no: String(first.wave_no ?? first.wave_code ?? first.batch_no ?? wid), details: p } }) wavePrintRows.value = rows.map((item: any) => ({ diff --git a/src/views/order/waveOrder/config/wave-config.ts b/src/views/order/waveOrder/config/wave-config.ts index c9c0d0fc..6e2f2e91 100644 --- a/src/views/order/waveOrder/config/wave-config.ts +++ b/src/views/order/waveOrder/config/wave-config.ts @@ -1,6 +1,6 @@ import { buyerMessageHasFilterOptions, - scanField, + scanBasicField, type ToolbarButtonConfig } from '@/views/order/orderManagement/config/order-common-config' import type { WavePlatformPrintDataPayload } from '@/api/order.print/orderprint' @@ -136,22 +136,22 @@ export const waveAvailableFields = [ /** 抓取散单候选:左侧筛选可用字段 */ export const fallbackOrderAvailableFields = [ - scanField('order', { label: '订单号', value: 'delivery_no', type: 'text' }), - scanField('logistics', { label: '物流单号', value: 'tracking_no', type: 'text' }), - scanField('shop', { label: '店铺名称', value: 'store_name', type: 'text' }), - scanField('shop', { label: '平台', value: 'sys_platform_name', type: 'select', options: [] }), - scanField('logistics', { label: '物流公司', value: 'sys_logistics_name', type: 'select', options: [] }), + scanBasicField({ label: '订单号', value: 'delivery_no', type: 'text' }), + scanBasicField({ label: '物流单号', value: 'tracking_no', type: 'text' }), + scanBasicField({ label: '店铺名称', value: 'store_name', type: 'text' }), + scanBasicField({ label: '平台', value: 'sys_platform_name', type: 'select', options: [] }), + scanBasicField({ label: '物流公司', value: 'sys_logistics_name', type: 'select', options: [] }), waveScanField('stats', { label: '商品种数最小值', value: 'items_count_min', type: 'number' }), waveScanField('stats', { label: '商品种数最大值', value: 'items_count_max', type: 'number' }), waveScanField('stats', { label: '商品总数最小值', value: 'items_total_min', type: 'number' }), waveScanField('stats', { label: '商品总数最大值', value: 'items_total_max', type: 'number' }), - scanField('receiver', { + scanBasicField({ label: '有无留言', value: 'buyer_message_has', type: 'select', options: buyerMessageHasFilterOptions }), - scanField('receiver', { label: '买家留言', value: 'buyer_message', type: 'text' }), + scanBasicField({ label: '买家留言', value: 'buyer_message', type: 'text' }), ] /** 不符合波次策略订单列表:UpperTable 列配置 */ diff --git a/src/views/stock/combo_stock/combo-stock-config.ts b/src/views/stock/combo_stock/combo-stock-config.ts index cac31c12..754fc332 100644 --- a/src/views/stock/combo_stock/combo-stock-config.ts +++ b/src/views/stock/combo_stock/combo-stock-config.ts @@ -16,6 +16,37 @@ export type ComboGoodsItemRow = { barcode?: string } +export function formatComboGoodsDateTime(value: unknown): string { + if (value == null || value === '') return '--' + + let normalizedValue: string | number + if (typeof value === 'string') { + const trimmed = value.trim() + if (!trimmed) return '--' + if (/^\d+$/.test(trimmed)) { + const numericValue = Number(trimmed) + normalizedValue = trimmed.length <= 10 ? numericValue * 1000 : numericValue + } else { + normalizedValue = trimmed + } + } else if (typeof value === 'number' && Number.isFinite(value) && value > 0 && value < 1_000_000_000_000) { + normalizedValue = value * 1000 + } else { + normalizedValue = value as string | number + } + + const date = new Date(normalizedValue) + if (Number.isNaN(date.getTime())) return String(value) + + const y = date.getFullYear() + const m = String(date.getMonth() + 1).padStart(2, '0') + const d = String(date.getDate()).padStart(2, '0') + const hh = String(date.getHours()).padStart(2, '0') + const mm = String(date.getMinutes()).padStart(2, '0') + const ss = String(date.getSeconds()).padStart(2, '0') + return `${y}-${m}-${d} ${hh}:${mm}:${ss}` +} + export const comboGoodsColumns = [ { prop: 'id', label: 'ID', width: '72', sortable: true }, { prop: 'combo_code', label: '组合编码', minWidth: '130', showOverflowTooltip: true }, @@ -24,20 +55,32 @@ export const comboGoodsColumns = [ { prop: 'simpleNotation', label: '子商品简记', minWidth: '160', showOverflowTooltip: true }, { prop: 'nameNotation', label: '名称简记', minWidth: '180', showOverflowTooltip: true }, { prop: 'remark', label: '备注', minWidth: '120', showOverflowTooltip: true }, - { prop: 'created_at', label: '创建时间', width: '160', showOverflowTooltip: true }, - { prop: 'updated_at', label: '更新时间', width: '160', showOverflowTooltip: true }, + { + prop: 'created_at', + label: '创建时间', + width: '160', + showOverflowTooltip: true, + formatter: (row: ComboGoodsRecord) => formatComboGoodsDateTime(row.created_at) + }, + { + prop: 'updated_at', + label: '更新时间', + width: '160', + showOverflowTooltip: true, + formatter: (row: ComboGoodsRecord) => formatComboGoodsDateTime(row.updated_at) + }, { prop: 'actions', label: '操作', width: '150', align: 'center', fixed: 'right' } ] export const comboGoodsScanFields = [ - { - value: 'keyword', - label: '关键词', - type: 'text', - placeholder: '组合编码 / 名称', - operators: ['contains'], - defaultOperator: 'contains' - }, + // { + // value: 'keyword', + // label: '关键词', + // type: 'text', + // placeholder: '组合编码 / 名称', + // operators: ['contains'], + // defaultOperator: 'contains' + // }, { value: 'combo_code', label: '组合编码', @@ -185,24 +228,33 @@ export function isComboGoodsApiSuccess(res: unknown) { return Boolean(r && (r.code === 1 || r.code === 200 || r.flag === 'success')) } +/** stock.warehouse.list 响应解析 */ +export function parseStockWarehouseListResponse(res: unknown): { list: unknown[]; total: number } { + if (!isComboGoodsApiSuccess(res)) { + return { list: [], total: 0 } + } + const data = (res as { data?: { list?: unknown[]; total?: number; pagination?: { total?: number } } })?.data + const list = Array.isArray(data?.list) ? data.list : Array.isArray(data) ? data : [] + const total = Number(data?.pagination?.total ?? data?.total ?? list.length) + return { list, total: Number.isFinite(total) ? total : list.length } +} + export function mapComboGoodsItemsFromRecord(items: unknown): ComboGoodsItemRow[] { if (!Array.isArray(items)) return [] - return items - .map((raw, index) => { - const row = raw && typeof raw === 'object' ? (raw as Record) : {} - const skuId = Number(row.item_goods_sku_id ?? row.goods_sku_id ?? row.stock_id ?? row.id) - const quantity = Number(row.item_quantity ?? row.quantity ?? 0) - if (!Number.isFinite(skuId) || skuId <= 0 || !Number.isFinite(quantity) || quantity <= 0) { - return null - } - return { - item_goods_sku_id: skuId, - item_quantity: Math.floor(quantity), - sort_order: Number(row.sort_order ?? index + 1), - item_code: String(row.item_code ?? row.goods_code ?? '').trim() || undefined, - item_name: String(row.item_name ?? row.goods_name ?? row.name ?? '').trim() || undefined, - barcode: String(row.barcode ?? '').trim() || undefined - } satisfies ComboGoodsItemRow - }) - .filter((item): item is ComboGoodsItemRow => item != null) + return items.flatMap((raw, index): ComboGoodsItemRow[] => { + const row = raw && typeof raw === 'object' ? (raw as Record) : {} + const skuId = Number(row.item_goods_sku_id ?? row.goods_sku_id ?? row.stock_id ?? row.id) + const quantity = Number(row.item_quantity ?? row.quantity ?? 0) + if (!Number.isFinite(skuId) || skuId <= 0 || !Number.isFinite(quantity) || quantity <= 0) { + return [] + } + return [{ + item_goods_sku_id: skuId, + item_quantity: Math.floor(quantity), + sort_order: Number(row.sort_order ?? index + 1), + item_code: String(row.item_code ?? row.goods_code ?? '').trim() || undefined, + item_name: String(row.item_name ?? row.goods_name ?? row.name ?? '').trim() || undefined, + barcode: String(row.barcode ?? '').trim() || undefined + }] + }) } diff --git a/src/views/stock/combo_stock/component/ComboGoodsFormDialog.vue b/src/views/stock/combo_stock/component/ComboGoodsFormDialog.vue index db0afb72..cf311058 100644 --- a/src/views/stock/combo_stock/component/ComboGoodsFormDialog.vue +++ b/src/views/stock/combo_stock/component/ComboGoodsFormDialog.vue @@ -24,6 +24,15 @@ + + + + + 0 ? Number(record.warehouse_id) @@ -181,6 +196,7 @@ function resetForm() { formData.id = undefined formData.combo_code = '' formData.combo_name = '' + formData.custom_code = '' formData.warehouse_id = undefined formData.remark = '' formData.status = 1 @@ -255,8 +271,10 @@ async function submitForm() { if (!valid || !validateItems()) return normalizeComboCode() + normalizeCustomCode() saving.value = true try { + const customCode = formData.custom_code.trim() if (props.mode === 'create') { const payload: Record = { combo_code: formData.combo_code, @@ -265,6 +283,7 @@ async function submitForm() { } const remark = formData.remark.trim() if (remark) payload.remark = remark + if (customCode) payload.custom_code = customCode if (formData.warehouse_id != null && formData.warehouse_id > 0) { payload.warehouse_id = formData.warehouse_id } @@ -284,6 +303,7 @@ async function submitForm() { } const remark = formData.remark.trim() payload.remark = remark + payload.custom_code = customCode || null if (formData.warehouse_id != null && formData.warehouse_id > 0) { payload.warehouse_id = formData.warehouse_id } else { diff --git a/src/views/stock/combo_stock/component/ComboGoodsSearchDialog.vue b/src/views/stock/combo_stock/component/ComboGoodsSearchDialog.vue index c63e6314..f4c3b036 100644 --- a/src/views/stock/combo_stock/component/ComboGoodsSearchDialog.vue +++ b/src/views/stock/combo_stock/component/ComboGoodsSearchDialog.vue @@ -8,14 +8,14 @@ :close-on-click-modal="!loading" @closed="emit('closed')" > - + /> --> diff --git a/src/views/stock/combo_stock/component/ComboStockPickerDialog.vue b/src/views/stock/combo_stock/component/ComboStockPickerDialog.vue index 71b7bd1d..679a1b89 100644 --- a/src/views/stock/combo_stock/component/ComboStockPickerDialog.vue +++ b/src/views/stock/combo_stock/component/ComboStockPickerDialog.vue @@ -8,14 +8,14 @@ destroy-on-close @closed="handleClosed" > - + /> -->
import { ref, watch } from 'vue' import { ElMessage } from 'element-plus' -import { warehouseSearch } from '@/api/stock/stock' +import { stockWarehouse, warehouseSearch } from '@/api/stock/stock' +import { isComboGoodsApiSuccess, parseStockWarehouseListResponse } from '../combo-stock-config' import { getStockItemCode, getStockItemName, @@ -78,6 +79,8 @@ export type ComboStockPickerItem = { store_id?: number } +const PICKER_LIST_PAGE_SIZE = 50 + const visible = defineModel({ default: false }) const emit = defineEmits<{ confirm: [items: ComboStockPickerItem[]] }>() @@ -90,8 +93,8 @@ const tableRef = ref(null) watch(visible, (opened) => { if (!opened) return keyword.value = '' - list.value = [] selectedItems.value = [] + loadInitialList() }) function resolveSkuId(row: any): number | undefined { @@ -116,6 +119,31 @@ function mapPickerRow(row: any): ComboStockPickerItem | null { } } +function mapRows(rawList: unknown[]): ComboStockPickerItem[] { + return rawList + .map((row) => mapPickerRow(row)) + .filter((item): item is ComboStockPickerItem => item != null) +} + +async function loadInitialList() { + loading.value = true + try { + const res: any = await stockWarehouse({ page: 1, pageSize: PICKER_LIST_PAGE_SIZE }, {}) + if (!isComboGoodsApiSuccess(res)) { + list.value = [] + ElMessage.error(res?.message || '获取商品列表失败') + return + } + const { list: rawList } = parseStockWarehouseListResponse(res) + list.value = mapRows(rawList) + } catch { + list.value = [] + ElMessage.error('获取商品列表失败') + } finally { + loading.value = false + } +} + async function handleSearch() { const text = keyword.value.trim() if (!text) { @@ -131,9 +159,7 @@ async function handleSearch() { return } const { list: rawList } = parseStockWarehouseSearch(res) - list.value = rawList - .map((row) => mapPickerRow(row)) - .filter((item): item is ComboStockPickerItem => item != null) + list.value = mapRows(rawList) } catch { list.value = [] ElMessage.error('搜索商品失败') diff --git a/src/views/stock/combo_stock/index.vue b/src/views/stock/combo_stock/index.vue index 056416d3..fefa23ab 100644 --- a/src/views/stock/combo_stock/index.vue +++ b/src/views/stock/combo_stock/index.vue @@ -17,7 +17,7 @@
刷新 - 共 {{ pagination.total }} 条 +
快速搜索 @@ -59,11 +59,11 @@ diff --git a/src/views/storage/entry/component/DirectInboundLogs.vue b/src/views/storage/entry/component/DirectInboundLogs.vue new file mode 100644 index 00000000..a6bc1984 --- /dev/null +++ b/src/views/storage/entry/component/DirectInboundLogs.vue @@ -0,0 +1,341 @@ + + + + + diff --git a/src/views/storage/entry/component/entrydetail.vue b/src/views/storage/entry/component/entrydetail.vue index 657df7ee..f7255b89 100644 --- a/src/views/storage/entry/component/entrydetail.vue +++ b/src/views/storage/entry/component/entrydetail.vue @@ -2,12 +2,30 @@
- 刷新 - EXCEL导出 - 导出 + 刷新 + + 提交完成入库 + + + 批量导入 +
待入库,可绑定收货明细 + 可导入/PDA 入库 + + 已导入 {{ directSummary.total_direct_inbound ?? 0 }} / 计划 {{ directSummary.total_planned ?? '—' }} +
@@ -32,6 +50,37 @@ > 绑定 + + + + + @@ -247,10 +492,27 @@ onMounted(() => { padding-bottom: 10px; border-bottom: 1px solid #ebeef5; margin-bottom: 10px; + + .left-actions { + display: flex; + gap: 8px; + } + + .right-actions { + display: flex; + align-items: center; + gap: 8px; + } + + .summary-text { + font-size: 12px; + color: #606266; + } } .table-content { flex: 1; + min-height: 200px; overflow: hidden; } } diff --git a/src/views/storage/entry/entry-config.ts b/src/views/storage/entry/entry-config.ts index fcc5ba1f..29344451 100644 --- a/src/views/storage/entry/entry-config.ts +++ b/src/views/storage/entry/entry-config.ts @@ -12,7 +12,7 @@ type EntryScanFieldGroupKey = keyof typeof ENTRY_SCAN_FIELD_GROUPS export function entryScanField( group: G, field: Record -) { +): Record & { group: (typeof ENTRY_SCAN_FIELD_GROUPS)[G] } { return { ...field, group: ENTRY_SCAN_FIELD_GROUPS[group] } } @@ -23,6 +23,63 @@ export const entryScanBoxConfig = { autoSubmit: false } +/** 入库单 order_status 枚举(与 storage.entry.list 及列表 tag 样式一致) */ +export const entryOrderStatusOptions = [ + { label: '已创建', value: 'CREATED' }, + { label: '待入库', value: 'PENDING' }, + { label: '入库中', value: 'PARTIAL' }, + { label: '部分收货', value: 'PARTIAL_RECEIVED' }, + { label: '已完成', value: 'COMPLETED' }, + { label: '已作废', value: 'CANCELLED' } +] as const + +const entryOrderStatusLabelMap: Record = { + ...Object.fromEntries(entryOrderStatusOptions.map((item) => [item.value, item.label])), + 待入库: '待入库', + 已完成: '已完成', + 已创建: '已创建' +} + +export function formatEntryOrderStatus(status: unknown): string { + if (status === null || status === undefined || status === '') return '--' + const normalized = String(status).trim() + const upper = normalized.toUpperCase() + const fromEnum = entryOrderStatusOptions.find( + (item) => item.value === upper || item.value === normalized + ) + if (fromEnum) return fromEnum.label + if (entryOrderStatusLabelMap[normalized]) return entryOrderStatusLabelMap[normalized] + return normalized +} + +export function getEntryOrderStatusTagType(status: unknown): string | undefined { + const upper = String(status ?? '').trim().toUpperCase() + const map: Record = { + CREATED: 'info', + PENDING: 'warning', + PARTIAL: 'primary', + PARTIAL_RECEIVED: 'primary', + COMPLETED: 'success', + CANCELLED: 'danger' + } + return map[upper] +} + +export function translateEntryField(fieldValue: string, value: unknown): string { + if (fieldValue === 'order_status') { + return formatEntryOrderStatus(value) + } + if (value === null || value === undefined || value === '') return '--' + const field = availableFields.find((f: any) => f.value === fieldValue) + if (!field?.options) return String(value) + const normalized = String(value).trim() + const option = field.options.find((opt: any) => { + if (opt.value === value) return true + return String(opt.value).toUpperCase() === normalized.toUpperCase() + }) + return option ? option.label : normalized +} + export const availableFields = [ entryScanField('owner', { label: '货主', @@ -35,11 +92,7 @@ export const availableFields = [ label: '状态', value: 'order_status', type: 'select', - options: [ - { label: '待入库', value: 'PENDING' }, - { label: '入库中', value: 'PARTIAL' }, - { label: '部分收货', value: 'PARTIAL_RECEIVED' }, - ] + options: [...entryOrderStatusOptions] }), entryScanField('status', { label: '入库单类型', @@ -168,7 +221,8 @@ function formatEntryInventoryType(_row: any, _col: any, value: unknown) { export function isPendingEntryOrderStatus(status: unknown): boolean { if (status === null || status === undefined || status === '') return false const normalized = String(status).trim() - return normalized === 'PENDING' || normalized === '待入库' + const upper = normalized.toUpperCase() + return upper === 'PENDING' || upper === 'CREATED' || normalized === '待入库' || normalized === '已创建' } export const entrydetail = [ @@ -178,13 +232,14 @@ export const entrydetail = [ { prop: 'order_line_no', label: '行号', width: '80', align: 'center' }, { prop: 'warehouse_item_code', label: '商品编码', width: '160' }, { prop: 'warehouse_item_name', label: '商品名称', minWidth: '200' }, - { prop: 'warehouse_item_spec', label: '规格', width: '140' }, - { prop: 'external_item_code', label: '外部商品编码', width: '160' }, + { prop: 'stock_id', label: 'SKU', width: '100' }, { prop: 'count', label: '应收数量', width: '100', align: 'right' }, { prop: 'received_quantity', label: '实收数量', width: '100', align: 'right' }, + { prop: 'warehouse_item_spec', label: '规格', width: '140' }, + { prop: 'external_item_code', label: '外部商品编码', width: '160' }, + { prop: 'confirm_quantity', label: '确认数量', width: '100', align: 'right' }, { prop: 'inventory_type', label: '库存类型', width: '100', align: 'center', formatter: formatEntryInventoryType }, - { prop: 'stock_id', label: '库存ID', width: '100' }, { prop: 'out_biz_code', label: '外部业务编码', width: '160' }, ] @@ -202,6 +257,95 @@ export const detailpanel = [ { label: '备注', prop: 'remark' } ] +export const directInboundInboundTypeOptions = [ + { label: '导入入库', value: 'import' }, + { label: 'PDA入库', value: 'pda' }, +] as const + +export function formatDirectInboundType(value: unknown): string { + if (value === null || value === undefined || value === '') return '--' + const normalized = String(value).trim().toLowerCase() + const option = directInboundInboundTypeOptions.find((item) => item.value === normalized) + return option?.label ?? String(value) +} + +/** 是否允许导入/PDA 入库操作(未完成、未作废) */ +export function canDirectInboundOperate(status: unknown): boolean { + if (status === null || status === undefined || status === '') return false + const upper = String(status).trim().toUpperCase() + return !['COMPLETED', 'CANCELLED'].includes(upper) && upper !== '已完成' && upper !== '已作废' +} + +export function formatDirectInboundDateTime( + row: unknown, + _col?: unknown, + value?: unknown +): string { + const raw = + value !== undefined && value !== null && value !== '' + ? value + : (row as Record)?.created_at + + if (raw === null || raw === undefined || raw === '') return '--' + if (typeof raw === 'object' && !(raw instanceof Date)) return '--' + + try { + let date: Date + if (raw instanceof Date) { + date = raw + } else if (typeof raw === 'number') { + const ms = String(raw).length === 10 ? raw * 1000 : raw + date = new Date(ms) + } else { + const text = String(raw).trim() + if (!text) return '--' + if (/^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}/.test(text)) { + return text.replace('T', ' ').slice(0, 19) + } + date = new Date(text.includes('-') ? text.replace(/-/g, '/') : text) + } + if (Number.isNaN(date.getTime())) return '--' + return formatEntryDateTime(date) + } catch { + return '--' + } +} + +function formatEntryDateTime(date: Date): string { + const year = date.getFullYear() + const month = String(date.getMonth() + 1).padStart(2, '0') + const day = String(date.getDate()).padStart(2, '0') + const hours = String(date.getHours()).padStart(2, '0') + const minutes = String(date.getMinutes()).padStart(2, '0') + const seconds = String(date.getSeconds()).padStart(2, '0') + return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}` +} + +export const directInboundLogColumns = [ + { prop: 'stock_id', label: 'SKU', width: '100' }, + { prop: 'warehouse_item_code', label: '商品编码', width: '150' }, + { prop: 'warehouse_item_name', label: '商品名称', minWidth: '160' }, + { prop: 'quantity', label: '入库数量', width: '100', align: 'right' }, + { prop: 'inbound_type', label: '入库方式', width: '100', align: 'center' }, + { prop: 'space_id', label: '库位ID', width: '100', align: 'right' }, + { prop: 'remark', label: '备注', minWidth: '160' }, + { + prop: 'created_at', + label: '操作时间', + width: '160', + formatter: formatDirectInboundDateTime, + }, +] + +/** 入库记录操作列(移除记录,仅未提交入库单可用) */ +export const directInboundLogActionColumn = { + prop: 'operation', + label: '操作', + width: '80', + fixed: 'right', + align: 'center', +} as const + export const addEntryFields = [ { label: '业务类型', prop: 'order_type', type: 'select', options: [ { label: '生产入库', value: 'SCRK' }, diff --git a/src/views/storage/entry/index.vue b/src/views/storage/entry/index.vue index 397ea28e..8b09abd8 100644 --- a/src/views/storage/entry/index.vue +++ b/src/views/storage/entry/index.vue @@ -20,7 +20,7 @@ 完成入库 批量作废 - 导出 + 导入 字段设置 {{ detailVisible ? '隐藏详情' : '显示详情' }} @@ -55,18 +55,18 @@ @selection-change="onSelectionChange" > @@ -84,7 +84,7 @@ @@ -105,6 +105,7 @@ +
@@ -113,9 +114,11 @@
@@ -174,16 +177,24 @@ import { availableFields, entryColums, addEntryFields, - entryScanBoxConfig + entryScanBoxConfig, + formatEntryOrderStatus, + getEntryOrderStatusTagType, + isPendingEntryOrderStatus, + translateEntryField } from './entry-config' import entrydetail from './component/entrydetail.vue' import log from './component/log.vue' import entryoperate from './component/entryoperate.vue' +import DirectInboundLogs from './component/DirectInboundLogs.vue' +import ExportModeDropdown from '@/components/ExportModeDropdown.vue' import { useVerticalSplitPane } from '@/composables/useVerticalSplitPane' const scanBox = ref(null) const upperTable = ref(null) +const detailComponentRef = ref<{ openBatchImportDialog?: () => void; reloadAll?: () => Promise } | null>(null) +const entryDetailRefreshTick = ref(0) const { splitStackRef, @@ -242,6 +253,7 @@ const currentSort = reactive({ prop: '', order: '' }) const componentMap: Record = { details: entrydetail, + directInboundLogs: DirectInboundLogs, logs: log, operate: entryoperate } @@ -253,12 +265,7 @@ const selectedRow = computed(() => { }) function translateField(fieldValue: string, value: any) { - const field = availableFieldsRef.find((f: any) => f.value === fieldValue) - if (field && field.options) { - const option = field.options.find((opt: any) => opt.value === value) - return option ? option.label : value - } - return value + return translateEntryField(fieldValue, value) } function pad(n: number) { @@ -344,18 +351,6 @@ function normalizeToWhere(condition: any) { return {} } -function getStatusType(status: string) { - const map: Record = { - 'CREATED': 'info', - 'PENDING': 'warning', - 'PARTIAL': 'primary', - 'PARTIAL_RECEIVED': 'primary', - 'COMPLETED': 'success', - 'CANCELLED': 'danger' - } - return map[status] || undefined -} - function getSyncStatusType(status: string) { const map: Record = { 'PENDING': 'info', @@ -528,6 +523,11 @@ async function loadData() { } } +async function handleDetailRefresh() { + await loadData() + entryDetailRefreshTick.value += 1 +} + async function loadFilterData() { try { const [storesRes, presetRes]: any = await Promise.all([ @@ -711,40 +711,71 @@ async function confirmBatchCancel() { } } -async function handleExport() { - if (list.value.length === 0) { +async function handleExport(mode: 'waybill' | 'item' = 'waybill') { + const sourceRows = selectionRows.value.length ? selectionRows.value : list.value + if (!sourceRows.length) { ElMessage.warning('当前无数据可导出') return } exportLoading.value = true try { - // 1. 过滤掉 prop 为主的空列 const exportColumns = columns.value.filter(col => col.prop && col.label) - const headers = exportColumns.map(col => col.label) - - // 2. 准备数据行,应用翻译逻辑 - const data = list.value.map(row => { - return exportColumns.map(col => { - const val = row[col.prop] - - // 尝试使用页面已有的 translateField 函数 - if (['order_status', 'order_type', 'sync_status'].includes(col.prop)) { - return translateField(col.prop, val) - } - - return val === null || val === undefined ? '' : val - }) - }) - // 3. 创建工作簿和工作表 - const ws = XLSX.utils.aoa_to_sheet([headers, ...data]) + if (mode === 'waybill') { + const headers = exportColumns.map(col => col.label) + const data = sourceRows.map(row => + exportColumns.map(col => { + const val = row[col.prop] + if (['order_status', 'order_type', 'sync_status'].includes(col.prop)) { + return translateField(col.prop, val) + } + return val === null || val === undefined ? '' : val + }) + ) + const ws = XLSX.utils.aoa_to_sheet([headers, ...data]) + const wb = XLSX.utils.book_new() + XLSX.utils.book_append_sheet(wb, ws, '入库单列表') + XLSX.writeFile(wb, `入库单列表_${new Date().getTime()}.xlsx`) + ElMessage.success('导出成功') + return + } + + const detailRows: any[] = [] + for (const row of sourceRows) { + try { + const res: any = await entryApi.getEntryDetail({ id: row.id }) + const payload = res?.data || res + const bindings = Array.isArray(payload?.bindings) + ? payload.bindings + : Array.isArray(payload?.details) + ? payload.details + : [] + bindings.forEach((item: any) => { + detailRows.push({ + '入库单号': row.entry_number || row.order_code || row.id, + '商品编码': item.item_code || item.product_code || '', + '商品名称': item.item_name || item.product_name || '', + '计划数量': item.plan_qty ?? item.quantity ?? '', + '实收数量': item.actual_qty ?? item.received_qty ?? '', + '批次号': item.batch_number || '', + '库位': item.space_id || item.space_name || '', + '备注': item.remark || '' + }) + }) + } catch (e) { + console.warn(`获取入库单 ${row.id} 明细失败`, e) + } + } + + if (!detailRows.length) { + ElMessage.warning('未获取到可导出的入库明细') + return + } + + const ws = XLSX.utils.json_to_sheet(detailRows) const wb = XLSX.utils.book_new() - XLSX.utils.book_append_sheet(wb, ws, '入库单列表') - - // 4. 导出文件 - const fileName = `入库单列表_${new Date().getTime()}.xlsx` - XLSX.writeFile(wb, fileName) - + XLSX.utils.book_append_sheet(wb, ws, '入库明细') + XLSX.writeFile(wb, `入库明细_${new Date().getTime()}.xlsx`) ElMessage.success('导出成功') } catch (e) { console.error('导出 Excel 失败:', e) @@ -754,8 +785,24 @@ async function handleExport() { } } +function handleExportAction(action: string) { + void handleExport(action === 'handleExportItem' ? 'item' : 'waybill') +} + function handleImport() { - ElMessage.info('导入功能') + if (!selectedEntryId.value) { + ElMessage.warning('请先在列表中选择一个入库单') + return + } + if (!isPendingEntryOrderStatus(selectedRow.value?.order_status)) { + ElMessage.warning('仅「待入库」状态可使用批量导入') + return + } + detailVisible.value = true + activeTab.value = 'details' + setTimeout(() => { + detailComponentRef.value?.openBatchImportDialog?.() + }, 0) } diff --git a/src/views/storage/entry/utils/direct-inbound-xlsx-import.ts b/src/views/storage/entry/utils/direct-inbound-xlsx-import.ts new file mode 100644 index 00000000..88d01474 --- /dev/null +++ b/src/views/storage/entry/utils/direct-inbound-xlsx-import.ts @@ -0,0 +1,264 @@ +import * as XLSX from 'xlsx' +import * as indexApi from '@/api/index/index' +import * as warehouseApi from '@/api/warehouse/warehouse' +import { entrydetail } from '../entry-config' + +export type DirectInboundImportRow = { + stock_id?: number + warehouse_item_code?: string + warehouse_item_name?: string + order_line_no?: string | number + count?: number + remaining_quantity?: number + [key: string]: unknown +} + +export type ParsedDirectInboundImportRow = { + stock_id?: number + quantity?: number + inbound_type: 'import' | 'pda' + space_id?: number + /** 库位条码或名称(展示与 Excel 导入字段) */ + space_keyword?: string + remark?: string + warehouse_item_code?: string + warehouse_item_name?: string + order_line_no?: string | number + remaining_quantity?: number + rowIndex: number +} + +const STOCK_ID_KEYS = ['SKU', '库存ID', 'stock_id', 'SKU ID'] +const QUANTITY_KEYS = ['入库数量', '实收数量', '确认数量', 'quantity', 'received_quantity', 'confirm_quantity'] +const SPACE_KEYWORD_KEYS = [ + '库位条码或名称', + '库位名称', + '库位条码', + '库位ID', + 'space_id', + 'space_code', + 'space_name', +] +const REMARK_KEYS = ['备注', 'remark'] +const INBOUND_TYPE_KEYS = ['入库方式', 'inbound_type'] +const ITEM_CODE_KEYS = ['商品编码', 'warehouse_item_code'] +const ITEM_NAME_KEYS = ['商品名称', 'warehouse_item_name'] +const LINE_NO_KEYS = ['行号', 'order_line_no'] + +function pickValue(row: Record, keys: string[]): unknown { + for (const key of keys) { + if (row[key] !== undefined && row[key] !== null && String(row[key]).trim() !== '') { + return row[key] + } + } + return undefined +} + +function toTrimmedString(value: unknown): string { + if (value === undefined || value === null) return '' + return String(value).trim() +} + +function toNumber(value: unknown): number | undefined { + if (value === undefined || value === null || toTrimmedString(value) === '') return undefined + const num = Number(value) + return Number.isFinite(num) ? num : undefined +} + +function toStringOrNumber(value: unknown): string | number | undefined { + if (value === undefined || value === null) return undefined + if (typeof value === 'string' || typeof value === 'number') return value + const text = toTrimmedString(value) + if (!text) return undefined + const num = Number(text) + return Number.isFinite(num) ? num : text +} + +function normalizeInboundType(value: unknown): 'import' | 'pda' | null { + const text = toTrimmedString(value).toLowerCase() + if (!text) return null + if (text === 'import' || text === '导入' || text === '导入入库') return 'import' + if (text === 'pda' || text === 'pda入库') return 'pda' + return null +} + +export function getSpaceDisplayName(space: Record | null | undefined): string { + const customName = toTrimmedString(space?.custom_name ?? space?.customName) + if (customName) return customName + return toTrimmedString(space?.space_name ?? space?.name ?? space?.space_code) +} + +/** 按库位条码、名称或 ID 解析库位 */ +export async function resolveSpaceByKeyword( + keyword: string +): Promise<{ id?: number; displayName?: string }> { + const text = toTrimmedString(keyword) + if (!text) return {} + + const numericId = Number(text) + if (Number.isFinite(numericId) && numericId > 0) { + try { + const info = (await warehouseApi.getSpaceInfo(numericId)) as unknown as Record + const direct = (info?.data || info) as Record + const resolvedId = Number(direct?.id ?? numericId) + return { + id: Number.isFinite(resolvedId) && resolvedId > 0 ? resolvedId : numericId, + displayName: getSpaceDisplayName(direct), + } + } catch (error) { + console.error('按ID获取库位信息失败', error) + } + } + + const res = (await indexApi.searchSpace({ keyword: text, page: 1, pageSize: 20 })) as unknown as Record< + string, + unknown + > + const data = (res?.data || res?.list || res) as Record + const list = Array.isArray(data?.list) ? data.list : Array.isArray(data) ? data : [] + if (!list.length) return {} + + const exact = + (list as Record[]).find((item) => { + const code = toTrimmedString(item?.space_code) + const customName = toTrimmedString(item?.custom_name ?? item?.customName) + const name = toTrimmedString(item?.space_name ?? item?.name) + return code === text || customName === text || name === text + }) || list[0] + + const item = exact as Record + const id = Number(item?.id) + return { + id: Number.isFinite(id) && id > 0 ? id : undefined, + displayName: getSpaceDisplayName(item), + } +} + +export async function resolveParsedRowSpaces(rows: ParsedDirectInboundImportRow[]): Promise { + for (const row of rows) { + const keyword = toTrimmedString(row.space_keyword) + if (!keyword) continue + const resolved = await resolveSpaceByKeyword(keyword) + if (resolved.id) row.space_id = resolved.id + if (resolved.displayName) row.space_keyword = resolved.displayName + } +} + +function buildEntryItemIndex(entryItems: DirectInboundImportRow[]) { + const byStockId = new Map() + const byCodeLine = new Map() + + entryItems.forEach((item) => { + const stockId = Number(item.stock_id) + if (Number.isInteger(stockId) && stockId > 0) { + byStockId.set(stockId, item) + } + const code = toTrimmedString(item.warehouse_item_code) + const lineNo = toTrimmedString(item.order_line_no) + if (code) { + byCodeLine.set(`${code}::${lineNo}`, item) + if (!lineNo) byCodeLine.set(code, item) + } + }) + + return { byStockId, byCodeLine } +} + +function findEntryItem( + row: Record, + stockId: number | undefined, + index: ReturnType +): DirectInboundImportRow | undefined { + if (stockId && index.byStockId.has(stockId)) { + return index.byStockId.get(stockId) + } + + const itemCode = toTrimmedString(pickValue(row, ITEM_CODE_KEYS)) + const lineNo = toTrimmedString(pickValue(row, LINE_NO_KEYS)) + if (!itemCode) return undefined + + return index.byCodeLine.get(`${itemCode}::${lineNo}`) || index.byCodeLine.get(itemCode) +} + +/** 解析 Excel 行数据并生成预览,不做业务校验 */ +export function parseDirectInboundXlsxRows( + rawRows: Record[], + options?: { + entryItems?: DirectInboundImportRow[] + defaultInboundType?: 'import' | 'pda' + } +): ParsedDirectInboundImportRow[] { + const parsedRows: ParsedDirectInboundImportRow[] = [] + const itemIndex = buildEntryItemIndex(options?.entryItems || []) + const defaultInboundType = options?.defaultInboundType || 'import' + + rawRows.forEach((row, index) => { + const hasContent = Object.values(row).some((value) => toTrimmedString(value) !== '') + if (!hasContent) return + + const stockId = toNumber(pickValue(row, STOCK_ID_KEYS)) + const entryItem = findEntryItem(row, stockId, itemIndex) + const resolvedStockId = stockId ?? toNumber(entryItem?.stock_id) + const quantity = toNumber(pickValue(row, QUANTITY_KEYS)) + const inboundType = normalizeInboundType(pickValue(row, INBOUND_TYPE_KEYS)) || defaultInboundType + const spaceKeyword = toTrimmedString(pickValue(row, SPACE_KEYWORD_KEYS)) + const remark = toTrimmedString(pickValue(row, REMARK_KEYS)) + const warehouseItemCode = + toTrimmedString(pickValue(row, ITEM_CODE_KEYS)) || toTrimmedString(entryItem?.warehouse_item_code) + const warehouseItemName = + toTrimmedString(pickValue(row, ITEM_NAME_KEYS)) || toTrimmedString(entryItem?.warehouse_item_name) + const orderLineNo = toStringOrNumber(pickValue(row, LINE_NO_KEYS)) ?? entryItem?.order_line_no + const remaining = Number(entryItem?.remaining_quantity ?? entryItem?.count ?? NaN) + + parsedRows.push({ + stock_id: resolvedStockId, + quantity, + inbound_type: inboundType, + space_keyword: spaceKeyword || undefined, + remark: remark || undefined, + warehouse_item_code: warehouseItemCode || undefined, + warehouse_item_name: warehouseItemName || undefined, + order_line_no: orderLineNo, + remaining_quantity: Number.isFinite(remaining) ? remaining : undefined, + rowIndex: index + 2, + }) + }) + + return parsedRows +} + +export async function readDirectInboundXlsxFile(file: File): Promise[]> { + const buffer = await file.arrayBuffer() + const workbook = XLSX.read(buffer, { type: 'array' }) + const sheetName = workbook.SheetNames[0] + if (!sheetName) return [] + const worksheet = workbook.Sheets[sheetName] + if (!worksheet) return [] + return XLSX.utils.sheet_to_json>(worksheet, { defval: '' }) +} + +export function downloadDirectInboundImportTemplate( + entryItems: DirectInboundImportRow[], + fileName?: string +) { + const exportData = entryItems.map((item) => { + const mapped: Record = {} + entrydetail.forEach((column) => { + const prop = String(column.prop) + const label = column.label || prop + const rawValue = item[prop] + mapped[label] = column.formatter + ? column.formatter(item, { property: prop }, rawValue) + : rawValue ?? '' + }) + mapped['入库数量'] = '' + mapped['库位条码或名称'] = '' + mapped['备注'] = '' + return mapped + }) + + const ws = XLSX.utils.json_to_sheet(exportData) + const wb = XLSX.utils.book_new() + XLSX.utils.book_append_sheet(wb, ws, '入库明细') + XLSX.writeFile(wb, fileName || `入库明细导入模板_${Date.now()}.xlsx`) +} diff --git a/src/views/storage/inventory/index.vue b/src/views/storage/inventory/index.vue index 248bf404..a3660bbb 100644 --- a/src/views/storage/inventory/index.vue +++ b/src/views/storage/inventory/index.vue @@ -19,7 +19,7 @@ 刷新 批量作废 - 导出 + 导入 字段设置 {{ detailVisible ? '隐藏详情' : '显示详情' }} @@ -209,6 +209,7 @@ import entrydetail from './component/panelstockdetail.vue' import log from './component/log.vue' import InventoryStockPickerDialog from './component/InventoryStockPickerDialog.vue' import type { InventoryStockPickerItem } from './component/InventoryStockPickerDialog.vue' +import ExportModeDropdown from '@/components/ExportModeDropdown.vue' import { useVerticalSplitPane } from '@/composables/useVerticalSplitPane' const scanBox = ref(null) @@ -546,19 +547,96 @@ async function confirmBatchCancel() { } catch (e) {} } -async function handleExport() { - if (!selectionRows.value.length) { - ElMessage.warning('请先勾选要导出的库存') - return - } +async function handleExport(mode: 'waybill' | 'item' = 'waybill') { exportLoading.value = true try { + if (mode === 'waybill') { + const sourceRows = selectionRows.value.length ? selectionRows.value : list.value + if (!sourceRows.length) { + ElMessage.warning('当前无数据可导出') + return + } + exportUpperTableRows({ + rows: sourceRows, + columns: inventoryExportColumns, + fileName: `库存列表-${Date.now()}.xlsx`, + transformCell: (prop, value) => { + if (prop === 'is_shelf_life_mgmt') return formatInventoryFlagLabel(value) + if (prop === 'remaining_threshold_days') return formatInventoryOptionalText(value) + if (prop === 'inventory_type') return formatInventoryTypeLabel(value) + return value + } + }) + ElMessage.success('导出成功') + return + } + + const params: any = { + pagination: { page: 1, pageSize: 10000 }, + where: scanBox.value?.getConditions?.() || {}, + group_by_batch: true + } + const res: any = await inventoryApi.getInventoryList(params) + if (!(res && (res.code === 200 || res.code === 1 || res.flag === 'success'))) { + ElMessage.error('获取库存明细失败') + return + } + + const data = res.data || res + const rawRows = Array.isArray(data.list) ? data.list : [] + let exportRows = rawRows.map((item: any) => { + const rowId = `${item.stock_id}-${item.space_id}-${item.batch_no || item.id || ''}` + const mockShelf = mockBatchShelfLifeFields(rowId) + return { + stock_id: item.stock_id, + item_code: item.stock?.item_code || '', + item_name: item.stock?.item_name || '', + barcodes: formatInventoryBarcodes(item.stock?.barcodes), + sku_property: formatInventoryOptionalText(item.stock?.sku_property), + stock_unit: formatInventoryOptionalText(item.stock?.stock_unit), + batch_no: item.batch_no || item.batch?.batch_no || '', + production_date: item.production_date || item.batch?.production_date || '', + expiry_date: item.expiry_date || item.batch?.expiry_date || '', + shelf_life_days: mockShelf.shelf_life_days, + sale_ban_period: mockShelf.sale_ban_period, + space_code: formatInventorySpaceLabel(item.space), + space_id: item.space_id ?? item.space?.id ?? '', + store_name: item.store_name || item.store?.store_remask || item.store?.store_name || '', + inventory_type: item.inventory_type, + quantity: item.quantity, + available_quantity: item.available_quantity, + locked_quantity: item.locked_quantity, + first_inbound_time: item.first_inbound_time || '', + last_inbound_time: item.last_inbound_time, + is_shelf_life_mgmt: item.stock?.is_shelf_life_mgmt ?? '', + remaining_threshold_days: item.stock?.remaining_threshold_days ?? '', + is_batch_mgmt_enabled: item.stock?.is_batch_mgmt_enabled, + batch_count: Number(item.batch_count || 0) + } + }) + + if (selectionRows.value.length) { + const selectedKeys = new Set( + selectionRows.value.map((row: any) => `${row.stock_id}-${row.space_id}`) + ) + exportRows = exportRows.filter((row: any) => + selectedKeys.has(`${row.stock_id}-${row.space_id}`) + ) + } + + if (!exportRows.length) { + ElMessage.warning('未获取到可导出的库存明细') + return + } + exportUpperTableRows({ - rows: selectionRows.value, - columns: inventoryExportColumns, - fileName: `库存列表-${Date.now()}.xlsx`, + rows: exportRows, + columns: productstockColums, + fileName: `库存明细-${Date.now()}.xlsx`, transformCell: (prop, value) => { - if (prop === 'is_shelf_life_mgmt') return formatInventoryFlagLabel(value) + if (prop === 'is_shelf_life_mgmt' || prop === 'is_batch_mgmt_enabled') { + return formatInventoryFlagLabel(value) + } if (prop === 'remaining_threshold_days') return formatInventoryOptionalText(value) if (prop === 'inventory_type') return formatInventoryTypeLabel(value) return value @@ -573,6 +651,10 @@ async function handleExport() { } } +function handleExportAction(action: string) { + void handleExport(action === 'handleExportItem' ? 'item' : 'waybill') +} + function handleImport() { ElMessage.info('导入功能') } diff --git a/src/views/storage/log/index.vue b/src/views/storage/log/index.vue index 76d0f029..827244ac 100644 --- a/src/views/storage/log/index.vue +++ b/src/views/storage/log/index.vue @@ -16,13 +16,7 @@
刷新 - - 导出 - + 字段设置 {{ detailVisible ? '隐藏详情' : '显示详情' }}
@@ -128,8 +122,11 @@ import { transactionColumns, availableFields, formatDateTime, - formatTransactionData + formatTransactionData, + inventoryTypeConfig, + transactionTypeConfig } from './log-config' +import ExportModeDropdown from '@/components/ExportModeDropdown.vue' import { useSettingsStore } from '@/stores/modules/settings' import { useVerticalSplitPane } from '@/composables/useVerticalSplitPane' import dayjs from 'dayjs' @@ -355,31 +352,38 @@ function handlePageSizeChange(newPageSize: number) { loadData() } -async function handleExport() { +async function handleExport(mode: 'waybill' | 'item' = 'waybill') { try { exportLoading.value = true const where = currentCondition.value || {} + const groupByBatchExport = mode === 'item' const response = await getTransactionList({ where: Object.keys(where).length > 0 ? where : undefined, pagination: { page: 1, - pageSize: 10000 // 导出最多10000条 + pageSize: 10000 }, - group_by_batch: groupByBatch.value + group_by_batch: groupByBatchExport }) const payload = response?.data || response - if ((response?.flag === 'success' || response?.code === 200) && payload?.list) { - // 生成CSV + if (!((response?.flag === 'success' || response?.code === 200) && payload?.list)) { + ElMessage.error('导出失败') + return + } + + const rows = payload.list as any[] + + if (mode === 'waybill') { const headers = ['商品ID', '库位ID', '仓库ID', '货主ID', '交易类型', '库存类型', '订单类型', '数量', '记录数', '首次创建时间', '最后创建时间', '操作人'] - const rows = payload.list.map((item: any) => [ + const csvRows = rows.map((item: any) => [ item.stock_id, item.space_id, item.warehouse_id, item.store_id, - item.transaction_type === 'INBOUND' ? '入库' : '出库', - inventoryTypeMap[item.inventory_type] || item.inventory_type, + transactionTypeConfig[item.transaction_type as keyof typeof transactionTypeConfig]?.text || item.transaction_type, + inventoryTypeConfig[item.inventory_type as keyof typeof inventoryTypeConfig]?.text || item.inventory_type, item.order_type, item.quantity, item.record_count || 1, @@ -390,7 +394,7 @@ async function handleExport() { const csvContent = [ headers.join(','), - ...rows.map((row: any[]) => row.map((cell: any) => `"${cell}"`).join(',')) + ...csvRows.map((row: any[]) => row.map((cell: any) => `"${cell ?? ''}"`).join(',')) ].join('\n') const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' }) @@ -398,17 +402,47 @@ async function handleExport() { link.href = URL.createObjectURL(blob) link.download = `出入库记录_${dayjs().format('YYYY-MM-DD_HHmmss')}.csv` link.click() - ElMessage.success('导出成功') - } else { - ElMessage.error('导出失败') + return } + + const headers = ['商品ID', '库位ID', '仓库ID', '货主ID', '交易类型', '库存类型', '订单类型', '订单号', '批次号', '数量', '创建时间', '操作人'] + const csvRows = rows.map((item: any) => [ + item.stock_id, + item.space_id, + item.warehouse_id, + item.store_id, + transactionTypeConfig[item.transaction_type as keyof typeof transactionTypeConfig]?.text || item.transaction_type, + inventoryTypeConfig[item.inventory_type as keyof typeof inventoryTypeConfig]?.text || item.inventory_type, + item.order_type, + item.order_no || '', + item.batch_no || item.batch?.batch_no || '', + item.quantity, + formatDateTime(item.created_at), + item.operator_name || '-' + ]) + + const csvContent = [ + headers.join(','), + ...csvRows.map((row: any[]) => row.map((cell: any) => `"${cell ?? ''}"`).join(',')) + ].join('\n') + + const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' }) + const link = document.createElement('a') + link.href = URL.createObjectURL(blob) + link.download = `出入库明细_${dayjs().format('YYYY-MM-DD_HHmmss')}.csv` + link.click() + ElMessage.success('导出成功') } catch (error: any) { ElMessage.error(error.message || '导出出错') } finally { exportLoading.value = false } } + +function handleExportAction(action: string) { + void handleExport(action === 'handleExportItem' ? 'item' : 'waybill') +}