622
This commit is contained in:
parent
3b7f21dc7d
commit
d1eecae3b1
BIN
dist.tar.gz
BIN
dist.tar.gz
Binary file not shown.
@ -19,6 +19,7 @@ export type ComboGoodsListItem = Record<string, unknown> & {
|
||||
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[]
|
||||
}
|
||||
|
||||
@ -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<string, any>
|
||||
sort?: OrderListParams['sort']
|
||||
/** 导出模式,默认 waybill */
|
||||
export_mode?: OrderExportMode
|
||||
exportMode?: OrderExportMode
|
||||
}
|
||||
|
||||
export type OrderExportTaskProgressParams = {
|
||||
|
||||
@ -399,7 +399,13 @@ export function stockStockWarehouse(data: { pagination?: any; where?: any }) {
|
||||
} as any)
|
||||
}
|
||||
|
||||
export function exportStockWarehouse(data: { where?: Record<string, any>; group_by_batch?: boolean; sort?: Record<string, any> }) {
|
||||
export function exportStockWarehouse(data: {
|
||||
where?: Record<string, any>
|
||||
group_by_batch?: boolean
|
||||
sort?: Record<string, any>
|
||||
export_mode?: 'waybill' | 'item'
|
||||
exportMode?: 'waybill' | 'item'
|
||||
}) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
|
||||
250
src/api/storage.directinbound/directinbound.ts
Normal file
250
src/api/storage.directinbound/directinbound.ts
Normal file
@ -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<string, unknown>
|
||||
[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<DirectInboundGetItemsResponse> {
|
||||
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<DirectInboundAddItemResponse>
|
||||
}
|
||||
|
||||
/** 按商品增量添加导入/PDA 入库记录(支持单条与批量) */
|
||||
export function addDirectInboundItem(
|
||||
data: DirectInboundAddItemParams
|
||||
): Promise<DirectInboundAddItemResponse> {
|
||||
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<DirectInboundCommitResponse>
|
||||
}
|
||||
|
||||
/** 提交确认完成导入/PDA 入库 */
|
||||
export function commitDirectInbound(
|
||||
data: DirectInboundCommitParams
|
||||
): Promise<DirectInboundCommitResponse> {
|
||||
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<DirectInboundRemoveItemResponse>
|
||||
}
|
||||
|
||||
/** 移除一条导入/PDA 入库记录(仅限未提交的入库单) */
|
||||
export function removeDirectInboundItem(
|
||||
data: DirectInboundRemoveItemParams
|
||||
): Promise<DirectInboundRemoveItemResponse> {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'storage.directInbound.removeItem',
|
||||
v,
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data
|
||||
})
|
||||
}
|
||||
@ -203,3 +203,39 @@ export function unbindReceivingDetails(
|
||||
data
|
||||
})
|
||||
}
|
||||
|
||||
export type GetEntryPrintDataParams = {
|
||||
/** 入库单ID */
|
||||
id: number
|
||||
}
|
||||
|
||||
/** 打印明细行(RECEIPT 模板 field_code 映射) */
|
||||
export type EntryPrintDataItem = Record<string, unknown>
|
||||
|
||||
/** 打印数据:扁平键值对 + 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<GetEntryPrintDataResponse> {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'storage.entry.getPrintData',
|
||||
v,
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data
|
||||
})
|
||||
}
|
||||
|
||||
@ -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
|
||||
|
||||
85
src/components/AsyncExportProgressDialog.vue
Normal file
85
src/components/AsyncExportProgressDialog.vue
Normal file
@ -0,0 +1,85 @@
|
||||
<template>
|
||||
<el-dialog
|
||||
:model-value="visible"
|
||||
:title="title"
|
||||
width="min(520px, 92vw)"
|
||||
append-to-body
|
||||
align-center
|
||||
:show-close="!loading"
|
||||
:close-on-click-modal="false"
|
||||
:close-on-press-escape="!loading"
|
||||
@update:model-value="emit('update:visible', $event)"
|
||||
>
|
||||
<div class="export-progress-panel">
|
||||
<div class="export-progress-panel__header">
|
||||
<span class="export-progress-panel__meta">任务ID:{{ taskId || '—' }}</span>
|
||||
</div>
|
||||
<el-progress :percentage="progressPercent" :status="progressStatus" :stroke-width="16" />
|
||||
<div class="export-progress-panel__info">
|
||||
<span>状态:{{ statusLabel }}</span>
|
||||
<span>进度:{{ progressPercent }}%</span>
|
||||
<span v-if="updateTime">更新时间:{{ formatDateTime(updateTime) }}</span>
|
||||
</div>
|
||||
<div v-if="message || error" class="export-progress-panel__message">
|
||||
{{ error || message }}
|
||||
</div>
|
||||
</div>
|
||||
</el-dialog>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
defineProps<{
|
||||
visible: boolean
|
||||
title?: string
|
||||
loading: boolean
|
||||
progressPercent: number
|
||||
progressStatus?: '' | 'success' | 'exception' | 'warning'
|
||||
statusLabel: string
|
||||
taskId: string
|
||||
message: string
|
||||
error: string
|
||||
updateTime?: number | string
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'update:visible', value: boolean): void
|
||||
}>()
|
||||
|
||||
function formatDateTime(value: string | number | null | undefined) {
|
||||
if (!value) return '—'
|
||||
let normalizedValue: string | number = value
|
||||
if (typeof value === 'string' && /^\d+$/.test(value.trim())) {
|
||||
normalizedValue = Number(value)
|
||||
}
|
||||
const date = typeof normalizedValue === 'number'
|
||||
? new Date(normalizedValue < 1000000000000 ? normalizedValue * 1000 : normalizedValue)
|
||||
: new Date(String(normalizedValue))
|
||||
if (Number.isNaN(date.getTime())) return String(value)
|
||||
const pad = (n: number) => String(n).padStart(2, '0')
|
||||
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped lang="scss">
|
||||
.export-progress-panel {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.export-progress-panel__header,
|
||||
.export-progress-panel__info {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 12px;
|
||||
color: #606266;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.export-progress-panel__message {
|
||||
color: #909399;
|
||||
font-size: 13px;
|
||||
line-height: 1.5;
|
||||
word-break: break-all;
|
||||
}
|
||||
</style>
|
||||
39
src/components/ExportModeDropdown.vue
Normal file
39
src/components/ExportModeDropdown.vue
Normal file
@ -0,0 +1,39 @@
|
||||
<template>
|
||||
<el-dropdown
|
||||
trigger="click"
|
||||
split-button
|
||||
size="small"
|
||||
:disabled="disabled || loading"
|
||||
@click="emit('action', defaultAction)"
|
||||
@command="emit('action', $event)"
|
||||
>
|
||||
{{ label }}
|
||||
<template #dropdown>
|
||||
<el-dropdown-menu>
|
||||
<el-dropdown-item command="handleExportWaybill">不含明细</el-dropdown-item>
|
||||
<el-dropdown-item command="handleExportItem" divided>含明细</el-dropdown-item>
|
||||
</el-dropdown-menu>
|
||||
</template>
|
||||
</el-dropdown>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
withDefaults(
|
||||
defineProps<{
|
||||
label?: string
|
||||
loading?: boolean
|
||||
disabled?: boolean
|
||||
defaultAction?: string
|
||||
}>(),
|
||||
{
|
||||
label: '导出',
|
||||
loading: false,
|
||||
disabled: false,
|
||||
defaultAction: 'handleExportWaybill'
|
||||
}
|
||||
)
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'action', action: string): void
|
||||
}>()
|
||||
</script>
|
||||
@ -54,7 +54,10 @@
|
||||
{{ field.extraAction.label }}
|
||||
</el-button>
|
||||
</div>
|
||||
<div class="field-control">
|
||||
<div
|
||||
class="field-control"
|
||||
:class="{ 'field-control--multi': isMultiValueTextOperator(customConditions[field.value].operator) }"
|
||||
>
|
||||
<el-select
|
||||
v-model="customConditions[field.value].operator"
|
||||
placeholder="条件类型"
|
||||
@ -70,6 +73,19 @@
|
||||
/>
|
||||
</el-select>
|
||||
<span v-if="isNullishOperator(customConditions[field.value].operator)" class="no-value-tip">无需填值</span>
|
||||
<el-input
|
||||
v-else-if="isMultiValueTextOperator(customConditions[field.value].operator)"
|
||||
v-model="customConditions[field.value].value"
|
||||
type="textarea"
|
||||
:autosize="{ minRows: 3, maxRows: 8 }"
|
||||
:placeholder="getTextPlaceholder(field)"
|
||||
size="small"
|
||||
clearable
|
||||
class="value-input value-input--multi"
|
||||
@change="handleCustomChange"
|
||||
@blur="normalizeTextValue(field)"
|
||||
@paste="handleMultiValuePaste($event, field)"
|
||||
/>
|
||||
<el-input
|
||||
v-else
|
||||
v-model="customConditions[field.value].value"
|
||||
@ -659,6 +675,20 @@ function isRangeOperator(op: string) {
|
||||
function isMultiOperator(op: string) {
|
||||
return ['in', 'notin'].includes(op)
|
||||
}
|
||||
function isMultiValueTextOperator(op: string) {
|
||||
return ['contains', 'in', 'notin'].includes(op)
|
||||
}
|
||||
function normalizeMultiValueText(raw: string): string {
|
||||
if (!raw) return raw
|
||||
const normalized = raw
|
||||
.replace(/[\r\n\t]+/g, ',')
|
||||
.replace(/[,;;、]+/g, ',')
|
||||
const values = normalized
|
||||
.split(',')
|
||||
.map((v) => 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%;
|
||||
|
||||
250
src/composables/useAsyncExportTask.ts
Normal file
250
src/composables/useAsyncExportTask.ts
Normal file
@ -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<string, unknown> & {
|
||||
export_mode?: ExportMode
|
||||
exportMode?: ExportMode
|
||||
}
|
||||
|
||||
export function useAsyncExportTask(options: {
|
||||
storageKey?: string
|
||||
submitExport: (payload: AsyncExportPayload) => Promise<unknown>
|
||||
queryProgress: (params: { task_id: string; taskId?: string }) => Promise<unknown>
|
||||
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<string, unknown>,
|
||||
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<string, string> = {
|
||||
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
|
||||
}
|
||||
}
|
||||
@ -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<string, unknown>
|
||||
sort?: Record<string, unknown>
|
||||
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 || '导出任务提交失败')
|
||||
|
||||
78
src/utils/asyncExportHelpers.ts
Normal file
78
src/utils/asyncExportHelpers.ts
Normal file
@ -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<string, unknown>).code))
|
||||
}
|
||||
|
||||
/** 解析 export / exportTaskProgress 响应体(兼容 data 嵌套) */
|
||||
export function parseExportTaskPayload(res: unknown): Record<string, any> {
|
||||
if (!res || typeof res !== 'object') return {}
|
||||
const root = res as Record<string, any>
|
||||
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, any>): 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<string, unknown>,
|
||||
exportMode: ExportMode = 'waybill'
|
||||
): Record<string, unknown> {
|
||||
return {
|
||||
...payload,
|
||||
export_mode: exportMode,
|
||||
exportMode
|
||||
}
|
||||
}
|
||||
@ -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
|
||||
|
||||
@ -1,18 +1,45 @@
|
||||
<template>
|
||||
<div ref="containerRef" class="order-toolbar-button-group">
|
||||
<div ref="mainRef" class="order-toolbar-button-group__main">
|
||||
<el-button
|
||||
v-for="button in visibleButtons"
|
||||
:key="button.key"
|
||||
:size="button.size || 'small'"
|
||||
:type="button.type"
|
||||
:plain="button.plain"
|
||||
:disabled="resolveDisabled(button.disabledKey)"
|
||||
:loading="resolveLoading(button.loadingKey)"
|
||||
@click="emitAction(button.action)"
|
||||
>
|
||||
{{ resolveLabel(button.label, button.dynamicLabelKey) }}
|
||||
</el-button>
|
||||
<template v-for="button in visibleButtons" :key="button.key">
|
||||
<el-dropdown
|
||||
v-if="button.buttonType === 'dropdown' && button.dropdownOptions?.length"
|
||||
trigger="click"
|
||||
split-button
|
||||
:size="button.size || 'small'"
|
||||
:type="button.type"
|
||||
:plain="button.plain"
|
||||
:disabled="resolveDisabled(button.disabledKey) || resolveLoading(button.loadingKey)"
|
||||
@click="emitAction(button.action)"
|
||||
@command="emitAction"
|
||||
>
|
||||
{{ resolveLabel(button.label, button.dynamicLabelKey) }}
|
||||
<template #dropdown>
|
||||
<el-dropdown-menu>
|
||||
<el-dropdown-item
|
||||
v-for="option in button.dropdownOptions"
|
||||
:key="option.action"
|
||||
:command="option.action"
|
||||
:divided="option.divided"
|
||||
>
|
||||
{{ option.label }}
|
||||
</el-dropdown-item>
|
||||
</el-dropdown-menu>
|
||||
</template>
|
||||
</el-dropdown>
|
||||
|
||||
<el-button
|
||||
v-else
|
||||
:size="button.size || 'small'"
|
||||
:type="button.type"
|
||||
:plain="button.plain"
|
||||
:disabled="resolveDisabled(button.disabledKey)"
|
||||
:loading="resolveLoading(button.loadingKey)"
|
||||
@click="emitAction(button.action)"
|
||||
>
|
||||
{{ resolveLabel(button.label, button.dynamicLabelKey) }}
|
||||
</el-button>
|
||||
</template>
|
||||
|
||||
<el-popover
|
||||
v-if="overflowButtons.length"
|
||||
@ -28,19 +55,35 @@
|
||||
</el-button>
|
||||
</template>
|
||||
<div class="order-toolbar-button-group__overflow-list">
|
||||
<el-button
|
||||
v-for="button in overflowButtons"
|
||||
:key="`overflow-${button.key}`"
|
||||
:size="button.size || 'small'"
|
||||
:type="button.type"
|
||||
:plain="button.plain"
|
||||
:disabled="resolveDisabled(button.disabledKey)"
|
||||
:loading="resolveLoading(button.loadingKey)"
|
||||
class="order-toolbar-button-group__overflow-item"
|
||||
@click="handleOverflowClick(button.action)"
|
||||
>
|
||||
{{ resolveLabel(button.label, button.dynamicLabelKey) }}
|
||||
</el-button>
|
||||
<template v-for="button in overflowButtons" :key="`overflow-${button.key}`">
|
||||
<template v-if="button.buttonType === 'dropdown' && button.dropdownOptions?.length">
|
||||
<el-button
|
||||
v-for="option in button.dropdownOptions"
|
||||
:key="`overflow-${button.key}-${option.action}`"
|
||||
:size="button.size || 'small'"
|
||||
:type="button.type"
|
||||
:plain="button.plain"
|
||||
:disabled="resolveDisabled(button.disabledKey)"
|
||||
:loading="resolveLoading(button.loadingKey)"
|
||||
class="order-toolbar-button-group__overflow-item"
|
||||
@click="handleOverflowClick(option.action)"
|
||||
>
|
||||
{{ resolveLabel(button.label, button.dynamicLabelKey) }} · {{ option.label }}
|
||||
</el-button>
|
||||
</template>
|
||||
<el-button
|
||||
v-else
|
||||
:size="button.size || 'small'"
|
||||
:type="button.type"
|
||||
:plain="button.plain"
|
||||
:disabled="resolveDisabled(button.disabledKey)"
|
||||
:loading="resolveLoading(button.loadingKey)"
|
||||
class="order-toolbar-button-group__overflow-item"
|
||||
@click="handleOverflowClick(button.action)"
|
||||
>
|
||||
{{ resolveLabel(button.label, button.dynamicLabelKey) }}
|
||||
</el-button>
|
||||
</template>
|
||||
</div>
|
||||
</el-popover>
|
||||
</div>
|
||||
@ -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;
|
||||
|
||||
@ -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<string, ToolbarButtonConfig> = {
|
||||
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<string, any>) {
|
||||
return { ...field, group: SCAN_BASIC_INFO_GROUP }
|
||||
}
|
||||
|
||||
/** 为 ScanBox 字段附加分组标签 */
|
||||
export function scanField<G extends ScanFieldGroupKey>(
|
||||
group: G,
|
||||
field: Record<string, any>
|
||||
) {
|
||||
return { ...field, group: SCAN_FIELD_GROUPS[group] }
|
||||
/** 为 ScanBox 工作流程字段附加分组标签(按字段 label 独立分组) */
|
||||
export function scanWorkflowField(field: Record<string, any>) {
|
||||
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 = [
|
||||
|
||||
@ -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
|
||||
|
||||
@ -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
|
||||
|
||||
@ -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
|
||||
|
||||
@ -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,
|
||||
|
||||
@ -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
|
||||
|
||||
@ -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,
|
||||
|
||||
@ -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,
|
||||
|
||||
@ -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<string, OrderExportScope> = {
|
||||
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<string, any> {
|
||||
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<string, unknown>) {
|
||||
const next = { ...where }
|
||||
delete next.warehouse_id
|
||||
|
||||
@ -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
|
||||
}
|
||||
}
|
||||
|
||||
@ -15,6 +15,20 @@ import { navigateToSandanWaveTab } from '@/utils/wave-order-nav'
|
||||
type ActionHandler = () => void | Promise<void>
|
||||
type OrderId = number | string
|
||||
|
||||
function bindExportToolbarActions(params: {
|
||||
handleExport: () => Promise<void>
|
||||
handleExportWaybill?: () => Promise<void>
|
||||
handleExportItem?: () => Promise<void>
|
||||
handleExportSelection?: () => Promise<void>
|
||||
}) {
|
||||
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<void>
|
||||
handleExport: () => Promise<void>
|
||||
handleExportWaybill?: () => Promise<void>
|
||||
handleExportItem?: () => Promise<void>
|
||||
handleExportSelection?: () => Promise<void>
|
||||
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<T = Record<string, any>>(response: any): T {
|
||||
export function createPendingToolbarController(params: {
|
||||
loadData: () => Promise<void>
|
||||
handleExport: () => Promise<void>
|
||||
handleExportWaybill?: () => Promise<void>
|
||||
handleExportItem?: () => Promise<void>
|
||||
handleExportSelection?: () => Promise<void>
|
||||
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<void>
|
||||
handleExport: () => Promise<void>
|
||||
handleExportWaybill?: () => Promise<void>
|
||||
handleExportItem?: () => Promise<void>
|
||||
handleExportSelection?: () => Promise<void>
|
||||
openColumnConfigPanel: () => void
|
||||
toggleDetailVisible: () => void
|
||||
}) {
|
||||
const actionMap: Record<string, () => void | Promise<void>> = {
|
||||
loadData: params.loadData,
|
||||
handleExport: params.handleExport,
|
||||
...(params.handleExportSelection ? { handleExportSelection: params.handleExportSelection } : {}),
|
||||
...bindExportToolbarActions(params),
|
||||
openColumnConfigPanel: params.openColumnConfigPanel,
|
||||
toggleDetailVisible: params.toggleDetailVisible
|
||||
}
|
||||
|
||||
@ -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),
|
||||
|
||||
@ -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<string, any> = {}
|
||||
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) => ({
|
||||
|
||||
@ -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 列配置 */
|
||||
|
||||
@ -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<string, unknown>) : {}
|
||||
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<string, unknown>) : {}
|
||||
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
|
||||
}]
|
||||
})
|
||||
}
|
||||
|
||||
@ -24,6 +24,15 @@
|
||||
<el-input v-model="formData.combo_name" placeholder="请输入组合名称" />
|
||||
</el-form-item>
|
||||
</el-col>
|
||||
<el-col :span="12">
|
||||
<el-form-item label="自定义编码" prop="custom_code">
|
||||
<el-input
|
||||
v-model="formData.custom_code"
|
||||
placeholder="可选,按货主唯一"
|
||||
@blur="normalizeCustomCode"
|
||||
/>
|
||||
</el-form-item>
|
||||
</el-col>
|
||||
<el-col :span="12">
|
||||
<el-form-item label="仓库 ID" prop="warehouse_id">
|
||||
<el-input-number
|
||||
@ -137,6 +146,7 @@ const formData = reactive({
|
||||
id: undefined as number | undefined,
|
||||
combo_code: '',
|
||||
combo_name: '',
|
||||
custom_code: '',
|
||||
warehouse_id: undefined as number | undefined,
|
||||
remark: '',
|
||||
status: 1
|
||||
@ -163,10 +173,15 @@ function normalizeComboCode() {
|
||||
formData.combo_code = String(formData.combo_code || '').trim()
|
||||
}
|
||||
|
||||
function normalizeCustomCode() {
|
||||
formData.custom_code = String(formData.custom_code || '').trim()
|
||||
}
|
||||
|
||||
function fillFromRecord(record: ComboGoodsRecord) {
|
||||
formData.id = record.id
|
||||
formData.combo_code = record.combo_code || ''
|
||||
formData.combo_name = record.combo_name || ''
|
||||
formData.custom_code = record.custom_code != null ? String(record.custom_code) : ''
|
||||
formData.warehouse_id =
|
||||
record.warehouse_id != null && Number(record.warehouse_id) > 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<string, unknown> = {
|
||||
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 {
|
||||
|
||||
@ -8,14 +8,14 @@
|
||||
:close-on-click-modal="!loading"
|
||||
@closed="emit('closed')"
|
||||
>
|
||||
<el-alert
|
||||
<!-- <el-alert
|
||||
type="info"
|
||||
:closable="false"
|
||||
show-icon
|
||||
class="search-alert"
|
||||
title="comboGoods.search"
|
||||
description="模糊匹配 combo_code / combo_name,仅返回启用状态记录,默认 20 条,上限 100 条。"
|
||||
/>
|
||||
/> -->
|
||||
|
||||
<el-form :inline="true" size="small" class="search-form" @submit.prevent="handleSearch">
|
||||
<el-form-item label="关键字">
|
||||
|
||||
@ -8,14 +8,14 @@
|
||||
destroy-on-close
|
||||
@closed="handleClosed"
|
||||
>
|
||||
<el-alert
|
||||
<!-- <el-alert
|
||||
type="info"
|
||||
:closable="false"
|
||||
show-icon
|
||||
class="picker-alert"
|
||||
title="stock.warehouse.search"
|
||||
description="搜索仓库商品后勾选加入组合明细;子商品须属于同一货主且库存记录有效。"
|
||||
/>
|
||||
/> -->
|
||||
|
||||
<div class="picker-toolbar">
|
||||
<el-input
|
||||
@ -59,7 +59,8 @@
|
||||
<script setup lang="ts">
|
||||
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<boolean>({ default: false })
|
||||
const emit = defineEmits<{ confirm: [items: ComboStockPickerItem[]] }>()
|
||||
|
||||
@ -90,8 +93,8 @@ const tableRef = ref<any>(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('搜索商品失败')
|
||||
|
||||
@ -17,7 +17,7 @@
|
||||
<div class="toolbar">
|
||||
<div class="toolbar-left">
|
||||
<el-button size="small" type="primary" :loading="loading" @click="loadList">刷新</el-button>
|
||||
<el-tag size="small" type="info">共 {{ pagination.total }} 条</el-tag>
|
||||
<!-- <el-tag size="small" type="info">共 {{ pagination.total }} 条</el-tag> -->
|
||||
</div>
|
||||
<div class="toolbar-right">
|
||||
<el-button size="small" type="primary" plain @click="searchDialogVisible = true">快速搜索</el-button>
|
||||
@ -59,11 +59,11 @@
|
||||
</template>
|
||||
|
||||
<template #column-created_at="{ row }">
|
||||
{{ formatDateTime(row.created_at) }}
|
||||
{{ formatComboGoodsDateTime(row.created_at) }}
|
||||
</template>
|
||||
|
||||
<template #column-updated_at="{ row }">
|
||||
{{ formatDateTime(row.updated_at) }}
|
||||
{{ formatComboGoodsDateTime(row.updated_at) }}
|
||||
</template>
|
||||
|
||||
<template #column-actions="{ row }">
|
||||
@ -101,6 +101,7 @@ import {
|
||||
buildComboGoodsListPayload,
|
||||
comboGoodsColumns,
|
||||
comboGoodsScanFields,
|
||||
formatComboGoodsDateTime,
|
||||
formatComboGoodsStatus,
|
||||
isComboGoodsApiSuccess,
|
||||
normalizeComboGoodsScanConditionToWhere,
|
||||
@ -133,20 +134,6 @@ const formDialogMode = ref<'create' | 'edit'>('create')
|
||||
const editingRecord = ref<ComboGoodsRecord | null>(null)
|
||||
const searchDialogVisible = ref(false)
|
||||
|
||||
function formatDateTime(value: unknown) {
|
||||
if (value == null || value === '') return '--'
|
||||
const text = String(value).trim()
|
||||
if (!text) return '--'
|
||||
const num = Number(text)
|
||||
if (Number.isFinite(num) && num > 1e11) {
|
||||
const date = new Date(num)
|
||||
if (!Number.isNaN(date.getTime())) {
|
||||
return date.toLocaleString('zh-CN', { hour12: false })
|
||||
}
|
||||
}
|
||||
return text
|
||||
}
|
||||
|
||||
async function loadList() {
|
||||
if (loading.value) return
|
||||
loading.value = true
|
||||
|
||||
@ -198,38 +198,25 @@
|
||||
<Recycle :drawer-visible="showRecycle" />
|
||||
</el-drawer>
|
||||
|
||||
<el-dialog
|
||||
v-model="exportDialogVisible"
|
||||
<AsyncExportProgressDialog
|
||||
v-model:visible="exportDialogVisible"
|
||||
title="商品导出进度"
|
||||
width="min(520px, 92vw)"
|
||||
append-to-body
|
||||
align-center
|
||||
:show-close="false"
|
||||
:close-on-click-modal="false"
|
||||
:close-on-press-escape="false"
|
||||
>
|
||||
<div class="export-progress-panel">
|
||||
<div class="export-progress-panel__header">
|
||||
<span class="export-progress-panel__meta">任务ID:{{ exportTaskProgress.taskId || '—' }}</span>
|
||||
</div>
|
||||
<el-progress :percentage="exportProgressPercent" :status="exportProgressBarStatus" :stroke-width="16" />
|
||||
<div class="export-progress-panel__info">
|
||||
<span>状态:{{ exportStatusText }}</span>
|
||||
<span>进度:{{ exportProgressPercent }}%</span>
|
||||
<span v-if="exportTaskProgress.updateTime">更新时间:{{ formatDateTime(exportTaskProgress.updateTime) }}</span>
|
||||
</div>
|
||||
<div v-if="exportTaskProgress.message || exportTaskProgress.error" class="export-progress-panel__message">
|
||||
{{ exportTaskProgress.error || exportTaskProgress.message }}
|
||||
</div>
|
||||
</div>
|
||||
</el-dialog>
|
||||
:loading="exportLoading"
|
||||
:progress-percent="exportProgressPercent"
|
||||
:progress-status="exportProgressStatus"
|
||||
:status-label="exportStatusLabel"
|
||||
:task-id="exportTaskProgress.taskId"
|
||||
:message="exportTaskProgress.message"
|
||||
:error="exportTaskProgress.error"
|
||||
:update-time="exportTaskProgress.updateTime"
|
||||
/>
|
||||
|
||||
<ImportDialog v-model="importDialogVisible" @success="handleImportSuccess" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, reactive, computed, onMounted, onBeforeUnmount, shallowRef, markRaw } from 'vue'
|
||||
import { ref, reactive, computed, onMounted, shallowRef, markRaw } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import {
|
||||
DeleteFilled, ArrowDown, User, InfoFilled
|
||||
@ -249,6 +236,8 @@ import Log from './component/log.vue'
|
||||
import Add from './component/add.vue'
|
||||
import Recycle from './component/recycle.vue'
|
||||
import ImportDialog from './component/ImportDialog.vue'
|
||||
import AsyncExportProgressDialog from '@/components/AsyncExportProgressDialog.vue'
|
||||
import { useAsyncExportTask } from '@/composables/useAsyncExportTask'
|
||||
import { stockColumns, availableFields as stockAvailableFields, stockBatchConfig, stockToolbarButtons, stockScanBoxConfig } from './stock-config'
|
||||
|
||||
// API
|
||||
@ -323,7 +312,6 @@ const showRecycle = ref(false)
|
||||
const activeTab = ref('info')
|
||||
const detailVisible = ref(true)
|
||||
const loading = ref(false)
|
||||
const exportLoading = ref(false)
|
||||
const showSelection = ref(true)
|
||||
const queryTime = ref(0)
|
||||
const selectionIds = ref<any[]>([])
|
||||
@ -340,18 +328,35 @@ const pagination = reactive({
|
||||
})
|
||||
|
||||
const batchConfig = reactive(JSON.parse(JSON.stringify(stockBatchConfig)))
|
||||
const exportDialogVisible = ref(false)
|
||||
const importDialogVisible = ref(false)
|
||||
const exportTaskProgress = reactive({
|
||||
taskId: '',
|
||||
status: 'submitted' as 'submitted' | 'running' | 'success' | 'failed' | 'not_found',
|
||||
progress: 0,
|
||||
message: '',
|
||||
error: '',
|
||||
downloadUrl: '',
|
||||
updateTime: 0
|
||||
|
||||
const {
|
||||
exportLoading,
|
||||
exportDialogVisible,
|
||||
exportTaskProgress,
|
||||
exportProgressPercent,
|
||||
exportProgressStatus,
|
||||
exportStatusLabel,
|
||||
submitExportTaskWithMode
|
||||
} = useAsyncExportTask({
|
||||
storageKey: 'stock:warehouse:exportTaskId',
|
||||
submitExport: (payload) => stockApi.exportStockWarehouse(payload as any),
|
||||
queryProgress: (params) => stockApi.getExportTaskProgress(params)
|
||||
})
|
||||
let exportPollingTimer: number | null = null
|
||||
|
||||
function buildExportPayload() {
|
||||
return {
|
||||
where: buildStockQuery(currentConditions.value)
|
||||
}
|
||||
}
|
||||
|
||||
async function handleExportWaybill() {
|
||||
await submitExportTaskWithMode(buildExportPayload(), 'waybill')
|
||||
}
|
||||
|
||||
async function handleExportItem() {
|
||||
await submitExportTaskWithMode(buildExportPayload(), 'item')
|
||||
}
|
||||
|
||||
const tableSize = ref('small')
|
||||
const { splitStackRef, beginSplitDrag, lowerPaneStyle, upperPaneStyle } = useVerticalSplitPane({
|
||||
@ -439,7 +444,8 @@ const toolbarActionMap: Record<string, () => void> = {
|
||||
handleAdd: () => handleAdd(),
|
||||
confirmBatchDelete: () => confirmBatchDelete(),
|
||||
handleClearData: () => handleClearData(),
|
||||
handleExport: () => handleExport(),
|
||||
handleExportWaybill: () => handleExportWaybill(),
|
||||
handleExportItem: () => handleExportItem(),
|
||||
openImportDialog: () => openImportDialog(),
|
||||
openColumnConfigPanel: () => openColumnConfigPanel(),
|
||||
toggleDetailVisible: () => toggleDetailVisible()
|
||||
@ -713,11 +719,6 @@ const handleImportSuccess = () => {
|
||||
loadData()
|
||||
}
|
||||
|
||||
const handleExport = () => {
|
||||
if (exportLoading.value) return
|
||||
void submitExportTask()
|
||||
}
|
||||
|
||||
const handleTabChange = () => {
|
||||
//
|
||||
}
|
||||
@ -752,10 +753,6 @@ onMounted(async () => {
|
||||
loadStockUnits()
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
stopExportPolling()
|
||||
})
|
||||
|
||||
const loadStockUnits = async () => {
|
||||
try {
|
||||
const res = await stockApi.getStockUnits()
|
||||
@ -780,177 +777,6 @@ const loadStockUnits = async () => {
|
||||
console.error(e)
|
||||
}
|
||||
}
|
||||
|
||||
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 normalizeDownloadUrl(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}`
|
||||
}
|
||||
|
||||
function downloadFile(url: string) {
|
||||
const finalUrl = normalizeDownloadUrl(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()
|
||||
}
|
||||
|
||||
function buildExportPayload() {
|
||||
return {
|
||||
where: buildStockQuery(currentConditions.value)
|
||||
}
|
||||
}
|
||||
|
||||
async function refreshExportTaskProgress() {
|
||||
if (!exportTaskProgress.taskId) return
|
||||
try {
|
||||
const res: any = await stockApi.getExportTaskProgress({ taskId: exportTaskProgress.taskId })
|
||||
if (!res) {
|
||||
scheduleExportPolling()
|
||||
return
|
||||
}
|
||||
exportTaskProgress.status = res.status || exportTaskProgress.status
|
||||
exportTaskProgress.progress = Number.isFinite(Number(res.progress)) ? Number(res.progress) : exportTaskProgress.progress
|
||||
exportTaskProgress.message = res.message || ''
|
||||
exportTaskProgress.error = res.error || ''
|
||||
exportTaskProgress.downloadUrl = res.download_url || ''
|
||||
exportTaskProgress.updateTime = Number(res.update_time || 0)
|
||||
|
||||
if (exportTaskProgress.status === 'success') {
|
||||
stopExportPolling()
|
||||
exportLoading.value = false
|
||||
try {
|
||||
if (exportTaskProgress.downloadUrl) {
|
||||
downloadFile(exportTaskProgress.downloadUrl)
|
||||
ElMessage.success(exportTaskProgress.message || '导出完成,文件已开始下载')
|
||||
} else {
|
||||
ElMessage.warning(exportTaskProgress.message || '导出完成,但未返回下载地址')
|
||||
}
|
||||
} finally {
|
||||
setTimeout(() => {
|
||||
exportDialogVisible.value = false
|
||||
resetExportProgress()
|
||||
}, 1200)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (exportTaskProgress.status === 'failed' || exportTaskProgress.status === 'not_found') {
|
||||
stopExportPolling()
|
||||
exportLoading.value = false
|
||||
ElMessage.error(exportTaskProgress.error || exportTaskProgress.message || '导出任务失败')
|
||||
return
|
||||
}
|
||||
|
||||
scheduleExportPolling()
|
||||
} catch (error) {
|
||||
console.error('查询商品导出进度失败:', error)
|
||||
scheduleExportPolling(2000)
|
||||
}
|
||||
}
|
||||
|
||||
async function submitExportTask() {
|
||||
exportLoading.value = true
|
||||
resetExportProgress()
|
||||
exportDialogVisible.value = true
|
||||
try {
|
||||
const res: any = await stockApi.exportStockWarehouse(buildExportPayload())
|
||||
if (!res || !res.task_id) {
|
||||
throw new Error(res?.message || '导出任务提交失败')
|
||||
}
|
||||
exportTaskProgress.taskId = res.task_id
|
||||
exportTaskProgress.status = res.status || 'submitted'
|
||||
exportTaskProgress.progress = Number.isFinite(Number(res.progress)) ? Number(res.progress) : 0
|
||||
exportTaskProgress.message = res.message || '任务已受理'
|
||||
exportTaskProgress.error = res.error || ''
|
||||
exportTaskProgress.updateTime = Number(res.update_time || 0)
|
||||
scheduleExportPolling(800)
|
||||
} catch (error: any) {
|
||||
exportLoading.value = false
|
||||
exportDialogVisible.value = false
|
||||
resetExportProgress()
|
||||
ElMessage.error(error?.message || '导出任务提交失败')
|
||||
}
|
||||
}
|
||||
|
||||
const exportProgressPercent = computed(() => {
|
||||
const value = Number(exportTaskProgress.progress || 0)
|
||||
if (!Number.isFinite(value)) return 0
|
||||
return Math.min(100, Math.max(0, Math.round(value)))
|
||||
})
|
||||
|
||||
const exportProgressBarStatus = computed(() => {
|
||||
if (exportTaskProgress.status === 'failed' || exportTaskProgress.status === 'not_found') return 'exception'
|
||||
if (exportTaskProgress.status === 'success' || exportProgressPercent.value >= 100) return 'success'
|
||||
return undefined
|
||||
})
|
||||
|
||||
const exportStatusText = computed(() => {
|
||||
const map: Record<string, string> = {
|
||||
submitted: '已受理',
|
||||
running: '进行中',
|
||||
success: '成功',
|
||||
failed: '失败',
|
||||
not_found: '未找到'
|
||||
}
|
||||
return map[exportTaskProgress.status] || exportTaskProgress.status || '—'
|
||||
})
|
||||
|
||||
function formatDateTime(value: string | number | null | undefined) {
|
||||
if (!value) return '—'
|
||||
let normalizedValue: string | number = value
|
||||
if (typeof value === 'string' && /^\d+$/.test(value.trim())) {
|
||||
const numericValue = Number(value.trim())
|
||||
normalizedValue = value.trim().length <= 10 ? numericValue * 1000 : numericValue
|
||||
} else if (typeof value === 'number' && Number.isFinite(value) && value > 0 && value < 1000000000000) {
|
||||
normalizedValue = value * 1000
|
||||
}
|
||||
|
||||
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}`
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped lang="scss">
|
||||
|
||||
@ -554,7 +554,12 @@ export const stockToolbarButtons: StockToolbarButtonConfig[] = [
|
||||
size: 'small',
|
||||
permissionKey: 'warehouseExport',
|
||||
loadingKey: 'exportLoading',
|
||||
action: 'handleExport'
|
||||
action: 'handleExportWaybill',
|
||||
buttonType: 'dropdown',
|
||||
dropdownOptions: [
|
||||
{ label: '不含明细', action: 'handleExportWaybill' },
|
||||
{ label: '含明细', action: 'handleExportItem', divided: true }
|
||||
]
|
||||
},
|
||||
{ key: 'import', label: '导入', type: 'primary', plain: true, size: 'small', action: 'openImportDialog' },
|
||||
{ key: 'columnConfig', label: '字段设置', size: 'small', action: 'openColumnConfigPanel' },
|
||||
|
||||
699
src/views/storage/entry/component/DirectInboundImportDialog.vue
Normal file
699
src/views/storage/entry/component/DirectInboundImportDialog.vue
Normal file
@ -0,0 +1,699 @@
|
||||
<template>
|
||||
<el-dialog
|
||||
v-model="visible"
|
||||
:title="isBatchMode ? '批量导入入库' : '导入入库'"
|
||||
:width="isBatchMode ? '980px' : '520px'"
|
||||
align-center
|
||||
append-to-body
|
||||
destroy-on-close
|
||||
:close-on-click-modal="!submitting"
|
||||
@closed="handleClosed"
|
||||
>
|
||||
<template v-if="!isBatchMode && singleTarget">
|
||||
<div class="item-summary">
|
||||
<div class="summary-item">
|
||||
<span class="summary-label">商品编码</span>
|
||||
<span class="summary-value">{{ singleTarget.warehouse_item_code || '—' }}</span>
|
||||
</div>
|
||||
<div class="summary-item">
|
||||
<span class="summary-label">商品名称</span>
|
||||
<span class="summary-value">{{ singleTarget.warehouse_item_name || '—' }}</span>
|
||||
</div>
|
||||
<div class="summary-item">
|
||||
<span class="summary-label">计划数量</span>
|
||||
<span class="summary-value">{{ singleTarget.count ?? '—' }}</span>
|
||||
</div>
|
||||
<div class="summary-item">
|
||||
<span class="summary-label">剩余可入</span>
|
||||
<span class="summary-value">{{ singleTarget.remaining_quantity ?? 0 }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<el-form ref="singleFormRef" :model="singleForm" :rules="singleFormRules" label-width="100px" size="small">
|
||||
<el-form-item label="SKU">
|
||||
<el-input :model-value="String(singleTarget.stock_id ?? '')" disabled />
|
||||
</el-form-item>
|
||||
<el-form-item label="入库数量" prop="quantity">
|
||||
<el-input-number
|
||||
v-model="singleForm.quantity"
|
||||
:min="1"
|
||||
:max="singleMaxQuantity"
|
||||
:precision="0"
|
||||
controls-position="right"
|
||||
style="width: 100%"
|
||||
/>
|
||||
</el-form-item>
|
||||
<el-form-item label="入库方式" prop="inbound_type">
|
||||
<el-radio-group v-model="singleForm.inbound_type">
|
||||
<el-radio
|
||||
v-for="opt in directInboundInboundTypeOptions"
|
||||
:key="opt.value"
|
||||
:label="opt.value"
|
||||
>
|
||||
{{ opt.label }}
|
||||
</el-radio>
|
||||
</el-radio-group>
|
||||
</el-form-item>
|
||||
<el-form-item label="库位">
|
||||
<el-input :model-value="singleSpaceDisplay" readonly>
|
||||
<template #append>
|
||||
<el-button @click="openSpacePicker('single')">选择系统库位</el-button>
|
||||
</template>
|
||||
</el-input>
|
||||
</el-form-item>
|
||||
<el-form-item label="备注" prop="remark">
|
||||
<el-input
|
||||
v-model="singleForm.remark"
|
||||
type="textarea"
|
||||
:rows="3"
|
||||
placeholder="如:导入文件名"
|
||||
/>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
</template>
|
||||
|
||||
<template v-else-if="isBatchMode">
|
||||
<div class="batch-import-panel">
|
||||
<el-alert
|
||||
type="info"
|
||||
:closable="false"
|
||||
show-icon
|
||||
title="请上传与入库明细表格字段一致的 Excel 文件,至少填写「SKU」和「入库数量」(或「实收数量」)。解析后可在下方表格中手动修改。"
|
||||
class="batch-tip"
|
||||
/>
|
||||
|
||||
<div class="batch-toolbar">
|
||||
<el-button size="small" @click="handleDownloadTemplate">下载模板</el-button>
|
||||
<el-upload
|
||||
accept=".xlsx,.xls"
|
||||
:auto-upload="false"
|
||||
:show-file-list="false"
|
||||
:disabled="submitting || parsing"
|
||||
@change="handleFileChange"
|
||||
>
|
||||
<el-button size="small" type="primary" :loading="parsing">选择 Excel 文件</el-button>
|
||||
</el-upload>
|
||||
<span v-if="importFileName" class="file-name">{{ importFileName }}</span>
|
||||
</div>
|
||||
|
||||
<el-table
|
||||
v-if="parsedRows.length"
|
||||
:data="parsedRows"
|
||||
border
|
||||
size="small"
|
||||
max-height="360"
|
||||
>
|
||||
<el-table-column prop="rowIndex" label="Excel行" width="72" align="center" />
|
||||
<el-table-column prop="stock_id" label="SKU" width="90" align="right" />
|
||||
<el-table-column prop="warehouse_item_code" label="商品编码" min-width="120" show-overflow-tooltip />
|
||||
<el-table-column prop="warehouse_item_name" label="商品名称" min-width="140" show-overflow-tooltip />
|
||||
<el-table-column prop="remaining_quantity" label="剩余可入" width="82" align="right" />
|
||||
<el-table-column label="入库数量" width="120" align="center">
|
||||
<template #default="{ row }">
|
||||
<el-input-number
|
||||
v-model="row.quantity"
|
||||
:min="1"
|
||||
:max="getBatchRowMaxQuantity(row)"
|
||||
:precision="0"
|
||||
size="small"
|
||||
controls-position="right"
|
||||
style="width: 100%"
|
||||
/>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="入库方式" width="110" align="center">
|
||||
<template #default="{ row }">
|
||||
<el-select v-model="row.inbound_type" size="small" style="width: 100%">
|
||||
<el-option
|
||||
v-for="opt in directInboundInboundTypeOptions"
|
||||
:key="opt.value"
|
||||
:label="opt.label"
|
||||
:value="opt.value"
|
||||
/>
|
||||
</el-select>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="库位ID" width="168">
|
||||
<template #default="{ row }">
|
||||
<div class="batch-cell-action">
|
||||
<span class="space-keyword-text">{{ row.space_keyword || '--' }}</span>
|
||||
<el-button type="primary" link size="small" @click="openBatchRowSpacePicker(row)">
|
||||
选择库位
|
||||
</el-button>
|
||||
</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="备注" min-width="120">
|
||||
<template #default="{ row }">
|
||||
<el-input v-model="row.remark" size="small" placeholder="可选" clearable />
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="操作" width="64" align="center" fixed="right">
|
||||
<template #default="{ $index }">
|
||||
<el-button link type="danger" size="small" @click="removeParsedRow($index)">删除</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template #footer>
|
||||
<el-button :disabled="submitting" @click="visible = false">取消</el-button>
|
||||
<el-button
|
||||
type="primary"
|
||||
:loading="submitting"
|
||||
:disabled="isBatchMode && !parsedRows.length"
|
||||
@click="handleSubmit"
|
||||
>
|
||||
确认导入
|
||||
</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
|
||||
<el-dialog
|
||||
v-model="spacePickerVisible"
|
||||
title="选择系统库位"
|
||||
align-center
|
||||
width="900px"
|
||||
append-to-body
|
||||
destroy-on-close
|
||||
>
|
||||
<div class="system-product-picker">
|
||||
<div class="picker-toolbar">
|
||||
<el-input
|
||||
v-model="spaceKeyword"
|
||||
placeholder="输入库位名称或编码"
|
||||
clearable
|
||||
style="width: 320px"
|
||||
@keyup.enter="querySpaces(1)"
|
||||
>
|
||||
<template #append>
|
||||
<el-button :icon="Search" :loading="spaceLoading" @click="querySpaces(1)">查询</el-button>
|
||||
</template>
|
||||
</el-input>
|
||||
</div>
|
||||
|
||||
<div class="picker-table-wrap">
|
||||
<UpperTable
|
||||
:data="spaceResults"
|
||||
:loading="spaceLoading"
|
||||
:show-selection="true"
|
||||
:multiple-selection="spaceSelection"
|
||||
:pagination="{
|
||||
currentPage: spacePagination.page,
|
||||
pageSize: spacePagination.pageSize,
|
||||
total: spacePagination.total,
|
||||
}"
|
||||
:columns="[
|
||||
{ prop: 'id', label: '库位ID', width: '120' },
|
||||
{ prop: 'display_name', label: '显示名称', minWidth: '220' },
|
||||
{ prop: 'space_name', label: '默认名称', minWidth: '220' },
|
||||
{ prop: 'space_code', label: '库位编码', width: '180' },
|
||||
]"
|
||||
@selection-change="handleSpaceSelectionChange"
|
||||
@row-click="handleSpaceRowClick"
|
||||
@page-change="querySpaces"
|
||||
@page-size-change="onSpacePageSizeChange"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<template #footer>
|
||||
<el-button @click="spacePickerVisible = false">取消</el-button>
|
||||
<el-button type="primary" @click="applySelectedSpace">使用选中库位</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, reactive, ref, watch } from 'vue'
|
||||
import { ElMessage, type FormInstance, type FormRules, type UploadFile } from 'element-plus'
|
||||
import { Search } from '@element-plus/icons-vue'
|
||||
import UpperTable from '@/components/UpperTable/index.vue'
|
||||
import * as indexApi from '@/api/index/index'
|
||||
import { addDirectInboundItem } from '@/api/storage.directinbound/directinbound'
|
||||
import { directInboundInboundTypeOptions } from '../entry-config'
|
||||
import {
|
||||
downloadDirectInboundImportTemplate,
|
||||
getSpaceDisplayName,
|
||||
parseDirectInboundXlsxRows,
|
||||
readDirectInboundXlsxFile,
|
||||
resolveParsedRowSpaces,
|
||||
resolveSpaceByKeyword,
|
||||
type DirectInboundImportRow,
|
||||
type ParsedDirectInboundImportRow,
|
||||
} from '../utils/direct-inbound-xlsx-import'
|
||||
|
||||
export type { DirectInboundImportRow }
|
||||
|
||||
const props = defineProps<{
|
||||
modelValue: boolean
|
||||
entryOrderCode?: string
|
||||
/** 单条导入目标 */
|
||||
targetItem?: DirectInboundImportRow | null
|
||||
/** Excel 批量导入模式 */
|
||||
batchFileMode?: boolean
|
||||
/** 当前入库单明细,用于 Excel 校验与模板导出 */
|
||||
entryItems?: DirectInboundImportRow[]
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:modelValue': [value: boolean]
|
||||
success: []
|
||||
}>()
|
||||
|
||||
const visible = computed({
|
||||
get: () => props.modelValue,
|
||||
set: (value) => emit('update:modelValue', value),
|
||||
})
|
||||
|
||||
const submitting = ref(false)
|
||||
const parsing = ref(false)
|
||||
const singleFormRef = ref<FormInstance>()
|
||||
const singleTarget = ref<DirectInboundImportRow | null>(null)
|
||||
const importFileName = ref('')
|
||||
const parsedRows = ref<ParsedDirectInboundImportRow[]>([])
|
||||
|
||||
const singleForm = reactive({
|
||||
quantity: 1,
|
||||
inbound_type: 'import' as 'import' | 'pda',
|
||||
space_id: undefined as number | undefined,
|
||||
space_keyword: '',
|
||||
remark: '',
|
||||
})
|
||||
|
||||
const spacePickerVisible = ref(false)
|
||||
const spaceLoading = ref(false)
|
||||
const spaceKeyword = ref('')
|
||||
const spaceResults = ref<Record<string, unknown>[]>([])
|
||||
const spaceSelection = ref<Record<string, unknown>[]>([])
|
||||
const spacePagination = reactive({ page: 1, pageSize: 10, total: 0 })
|
||||
const spacePickerTarget = ref<'single' | 'batch' | ''>('')
|
||||
const batchSpaceEditingRow = ref<ParsedDirectInboundImportRow | null>(null)
|
||||
|
||||
const singleSpaceDisplay = computed(() => {
|
||||
const keyword = singleForm.space_keyword.trim()
|
||||
if (keyword) return keyword
|
||||
return singleForm.space_id ? `ID ${singleForm.space_id}` : ''
|
||||
})
|
||||
|
||||
const isBatchMode = computed(() => {
|
||||
return !!props.batchFileMode && !props.targetItem
|
||||
})
|
||||
|
||||
const singleMaxQuantity = computed(() => {
|
||||
const remaining = Number(singleTarget.value?.remaining_quantity ?? 0)
|
||||
return Number.isFinite(remaining) && remaining > 0 ? remaining : 1
|
||||
})
|
||||
|
||||
const singleFormRules: FormRules = {
|
||||
quantity: [
|
||||
{ required: true, message: '请输入入库数量', trigger: 'blur' },
|
||||
{
|
||||
validator: (_rule, value, callback) => {
|
||||
const qty = Number(value)
|
||||
if (!Number.isInteger(qty) || qty <= 0) {
|
||||
callback(new Error('入库数量须为正整数'))
|
||||
return
|
||||
}
|
||||
if (qty > singleMaxQuantity.value) {
|
||||
callback(new Error(`不能超过剩余可入库数量 ${singleMaxQuantity.value}`))
|
||||
return
|
||||
}
|
||||
callback()
|
||||
},
|
||||
trigger: 'change',
|
||||
},
|
||||
],
|
||||
inbound_type: [{ required: true, message: '请选择入库方式', trigger: 'change' }],
|
||||
}
|
||||
|
||||
watch(
|
||||
() => [props.modelValue, props.targetItem, props.batchFileMode],
|
||||
() => {
|
||||
if (!props.modelValue) return
|
||||
|
||||
if (props.targetItem) {
|
||||
singleTarget.value = props.targetItem
|
||||
const remaining = Number(props.targetItem.remaining_quantity ?? 0)
|
||||
singleForm.quantity = Number.isFinite(remaining) && remaining > 0 ? Math.min(remaining, 1) : 1
|
||||
singleForm.inbound_type = 'import'
|
||||
singleForm.space_id = undefined
|
||||
singleForm.space_keyword = ''
|
||||
singleForm.remark = ''
|
||||
resetBatchState()
|
||||
return
|
||||
}
|
||||
|
||||
singleTarget.value = null
|
||||
if (props.batchFileMode) {
|
||||
resetBatchState()
|
||||
}
|
||||
},
|
||||
{ immediate: true }
|
||||
)
|
||||
|
||||
function resetBatchState() {
|
||||
importFileName.value = ''
|
||||
parsedRows.value = []
|
||||
}
|
||||
|
||||
function normalizeSpaceId(value: unknown): number | undefined {
|
||||
const spaceId = Number(value)
|
||||
return Number.isInteger(spaceId) && spaceId > 0 ? spaceId : undefined
|
||||
}
|
||||
|
||||
function getBatchRowMaxQuantity(row: ParsedDirectInboundImportRow): number {
|
||||
const remaining = Number(row.remaining_quantity ?? 0)
|
||||
return Number.isFinite(remaining) && remaining > 0 ? remaining : Number.MAX_SAFE_INTEGER
|
||||
}
|
||||
|
||||
function removeParsedRow(index: number) {
|
||||
parsedRows.value.splice(index, 1)
|
||||
}
|
||||
|
||||
function openSpacePicker(target: 'single' | 'batch') {
|
||||
spacePickerTarget.value = target
|
||||
spaceSelection.value = []
|
||||
spaceKeyword.value = ''
|
||||
spacePickerVisible.value = true
|
||||
void querySpaces(1)
|
||||
}
|
||||
|
||||
function openBatchRowSpacePicker(row: ParsedDirectInboundImportRow) {
|
||||
batchSpaceEditingRow.value = row
|
||||
openSpacePicker('batch')
|
||||
}
|
||||
|
||||
function handleSpaceSelectionChange(val: Record<string, unknown>[]) {
|
||||
spaceSelection.value = val
|
||||
}
|
||||
|
||||
function handleSpaceRowClick(row: Record<string, unknown>) {
|
||||
spaceSelection.value = [row]
|
||||
}
|
||||
|
||||
function onSpacePageSizeChange(size: number) {
|
||||
spacePagination.pageSize = size
|
||||
void querySpaces(1)
|
||||
}
|
||||
|
||||
async function querySpaces(page = 1) {
|
||||
spaceLoading.value = true
|
||||
try {
|
||||
const keyword = spaceKeyword.value.trim()
|
||||
const res = (await indexApi.searchSpace({
|
||||
keyword,
|
||||
page,
|
||||
pageSize: spacePagination.pageSize,
|
||||
})) as unknown as Record<string, unknown>
|
||||
const data = (res?.data || res?.list || res) as Record<string, unknown>
|
||||
const list = Array.isArray(data?.list) ? data.list : Array.isArray(data) ? data : []
|
||||
const pagination = data?.pagination as Record<string, unknown> | undefined
|
||||
|
||||
spaceResults.value = (list as Record<string, unknown>[]).map((item) => ({
|
||||
...item,
|
||||
display_name: getSpaceDisplayName(item),
|
||||
space_name: item.space_name || item.name || item.space_code || '',
|
||||
}))
|
||||
spacePagination.total = Number(pagination?.total ?? data?.total ?? spaceResults.value.length)
|
||||
spacePagination.page = page
|
||||
} catch (error) {
|
||||
console.error('查询库位失败:', error)
|
||||
ElMessage.error('查询库位失败')
|
||||
spaceResults.value = []
|
||||
spacePagination.total = 0
|
||||
} finally {
|
||||
spaceLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function applySelectedSpace() {
|
||||
if (spaceSelection.value.length !== 1) {
|
||||
ElMessage.warning('请选择一个库位')
|
||||
return
|
||||
}
|
||||
|
||||
const picked = spaceSelection.value[0]
|
||||
const display =
|
||||
getSpaceDisplayName(picked) || String(picked?.space_code ?? '').trim() || `ID ${picked?.id ?? ''}`
|
||||
const spaceId = Number(picked?.id)
|
||||
|
||||
if (spacePickerTarget.value === 'batch' && batchSpaceEditingRow.value) {
|
||||
batchSpaceEditingRow.value.space_keyword = display
|
||||
batchSpaceEditingRow.value.space_id =
|
||||
Number.isFinite(spaceId) && spaceId > 0 ? spaceId : undefined
|
||||
batchSpaceEditingRow.value = null
|
||||
} else if (spacePickerTarget.value === 'single') {
|
||||
singleForm.space_keyword = display
|
||||
singleForm.space_id = Number.isFinite(spaceId) && spaceId > 0 ? spaceId : undefined
|
||||
}
|
||||
|
||||
spacePickerTarget.value = ''
|
||||
spacePickerVisible.value = false
|
||||
}
|
||||
|
||||
async function resolveRowSpaceBeforeSubmit(
|
||||
row: { rowIndex?: number; space_id?: number; space_keyword?: string }
|
||||
): Promise<string | null> {
|
||||
const keyword = row.space_keyword?.trim()
|
||||
if (!row.space_id && keyword) {
|
||||
const resolved = await resolveSpaceByKeyword(keyword)
|
||||
if (!resolved.id) {
|
||||
const label = row.rowIndex ? `第 ${row.rowIndex} 行` : '当前行'
|
||||
return `${label}库位未匹配: ${keyword}`
|
||||
}
|
||||
row.space_id = resolved.id
|
||||
if (resolved.displayName) row.space_keyword = resolved.displayName
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function validateBatchRows(): string | null {
|
||||
for (const row of parsedRows.value) {
|
||||
const stockId = Number(row.stock_id)
|
||||
if (!Number.isInteger(stockId) || stockId <= 0) {
|
||||
return `第 ${row.rowIndex} 行缺少有效 SKU`
|
||||
}
|
||||
|
||||
const quantity = Number(row.quantity)
|
||||
if (!Number.isInteger(quantity) || quantity <= 0) {
|
||||
return `第 ${row.rowIndex} 行入库数量须为正整数`
|
||||
}
|
||||
|
||||
const maxQty = getBatchRowMaxQuantity(row)
|
||||
if (quantity > maxQty) {
|
||||
return `第 ${row.rowIndex} 行入库数量不能超过剩余可入 ${maxQty}`
|
||||
}
|
||||
|
||||
if (!row.inbound_type) {
|
||||
return `第 ${row.rowIndex} 行请选择入库方式`
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function handleDownloadTemplate() {
|
||||
const items = props.entryItems || []
|
||||
if (!items.length) {
|
||||
ElMessage.warning('当前入库单没有可导出的明细')
|
||||
return
|
||||
}
|
||||
downloadDirectInboundImportTemplate(items)
|
||||
}
|
||||
|
||||
async function handleFileChange(uploadFile: UploadFile) {
|
||||
const file = uploadFile.raw
|
||||
if (!file) return
|
||||
|
||||
parsing.value = true
|
||||
resetBatchState()
|
||||
importFileName.value = file.name
|
||||
|
||||
try {
|
||||
const rawRows = await readDirectInboundXlsxFile(file)
|
||||
parsedRows.value = parseDirectInboundXlsxRows(rawRows, {
|
||||
entryItems: props.entryItems || [],
|
||||
defaultInboundType: 'import',
|
||||
})
|
||||
await resolveParsedRowSpaces(parsedRows.value)
|
||||
|
||||
if (parsedRows.value.length) {
|
||||
ElMessage.success(`已解析 ${parsedRows.value.length} 条明细`)
|
||||
} else {
|
||||
ElMessage.warning('Excel 中未解析到数据行')
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('解析 Excel 失败:', error)
|
||||
ElMessage.error('Excel 文件解析失败')
|
||||
} finally {
|
||||
parsing.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function handleClosed() {
|
||||
singleTarget.value = null
|
||||
singleFormRef.value?.clearValidate()
|
||||
resetBatchState()
|
||||
spacePickerVisible.value = false
|
||||
spacePickerTarget.value = ''
|
||||
batchSpaceEditingRow.value = null
|
||||
}
|
||||
|
||||
async function handleSubmit() {
|
||||
const code = props.entryOrderCode
|
||||
if (!code) {
|
||||
ElMessage.warning('缺少入库单号')
|
||||
return
|
||||
}
|
||||
|
||||
submitting.value = true
|
||||
try {
|
||||
if (!isBatchMode.value) {
|
||||
if (!singleFormRef.value || !singleTarget.value?.stock_id) return
|
||||
const valid = await singleFormRef.value.validate().catch(() => false)
|
||||
if (!valid) return
|
||||
|
||||
const spaceError = await resolveRowSpaceBeforeSubmit(singleForm)
|
||||
if (spaceError) {
|
||||
ElMessage.warning(spaceError)
|
||||
return
|
||||
}
|
||||
|
||||
const res = await addDirectInboundItem({
|
||||
entry_order_code: code,
|
||||
stock_id: Number(singleTarget.value.stock_id),
|
||||
quantity: Number(singleForm.quantity),
|
||||
inbound_type: singleForm.inbound_type,
|
||||
space_id: normalizeSpaceId(singleForm.space_id),
|
||||
remark: singleForm.remark?.trim() || undefined,
|
||||
})
|
||||
if (res?.code !== 200 && res?.code !== undefined) {
|
||||
throw new Error(res?.message || '导入入库失败')
|
||||
}
|
||||
ElMessage.success('导入入库成功')
|
||||
} else {
|
||||
if (!parsedRows.value.length) {
|
||||
ElMessage.warning('请先上传 Excel 文件')
|
||||
return
|
||||
}
|
||||
|
||||
const validationError = validateBatchRows()
|
||||
if (validationError) {
|
||||
ElMessage.warning(validationError)
|
||||
return
|
||||
}
|
||||
|
||||
for (const row of parsedRows.value) {
|
||||
const spaceError = await resolveRowSpaceBeforeSubmit(row)
|
||||
if (spaceError) {
|
||||
ElMessage.warning(spaceError)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
const res = await addDirectInboundItem({
|
||||
entry_order_code: code,
|
||||
items: parsedRows.value.map((row) => ({
|
||||
stock_id: Number(row.stock_id),
|
||||
quantity: Number(row.quantity),
|
||||
inbound_type: row.inbound_type,
|
||||
space_id: normalizeSpaceId(row.space_id),
|
||||
remark: row.remark?.trim() || undefined,
|
||||
})),
|
||||
})
|
||||
if (res?.code !== 200 && res?.code !== undefined) {
|
||||
throw new Error(res?.message || '批量导入入库失败')
|
||||
}
|
||||
|
||||
const payload = res?.data && typeof res.data === 'object' ? res.data : res
|
||||
const count = payload?.count ?? parsedRows.value.length
|
||||
ElMessage.success(`批量导入成功,共 ${count} 条`)
|
||||
}
|
||||
|
||||
visible.value = false
|
||||
emit('success')
|
||||
} catch (error) {
|
||||
console.error('导入入库失败:', error)
|
||||
ElMessage.error(error instanceof Error ? error.message : '导入入库失败')
|
||||
} finally {
|
||||
submitting.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped lang="scss">
|
||||
.item-summary {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 8px 16px;
|
||||
margin-bottom: 16px;
|
||||
padding: 12px;
|
||||
background: #f5f7fa;
|
||||
border-radius: 4px;
|
||||
|
||||
.summary-item {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.summary-label {
|
||||
font-size: 12px;
|
||||
color: #909399;
|
||||
}
|
||||
|
||||
.summary-value {
|
||||
font-size: 13px;
|
||||
color: #303133;
|
||||
}
|
||||
}
|
||||
|
||||
.batch-import-panel {
|
||||
.batch-tip {
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.batch-toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.file-name {
|
||||
font-size: 12px;
|
||||
color: #606266;
|
||||
}
|
||||
}
|
||||
|
||||
.batch-cell-action {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
|
||||
.space-keyword-text {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
}
|
||||
|
||||
.system-product-picker {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.picker-toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.picker-table-wrap {
|
||||
height: 440px;
|
||||
}
|
||||
</style>
|
||||
341
src/views/storage/entry/component/DirectInboundLogs.vue
Normal file
341
src/views/storage/entry/component/DirectInboundLogs.vue
Normal file
@ -0,0 +1,341 @@
|
||||
<template>
|
||||
<div class="direct-inbound-logs-panel">
|
||||
<div class="header-actions">
|
||||
<div class="left-actions">
|
||||
<el-button size="small" :loading="loading" @click="loadLogs">刷新</el-button>
|
||||
<el-button
|
||||
v-if="canRemove"
|
||||
size="small"
|
||||
type="danger"
|
||||
plain
|
||||
:disabled="!selectedRows.length"
|
||||
:loading="removing"
|
||||
@click="handleBatchRemove"
|
||||
>
|
||||
批量移除
|
||||
</el-button>
|
||||
</div>
|
||||
<div class="right-actions">
|
||||
<el-tag v-if="canRemove" size="small" type="warning">未提交,可移除导入/PDA 记录</el-tag>
|
||||
<el-tag v-else size="small" type="info">已提交或已作废,不可移除</el-tag>
|
||||
<span v-if="directLogList.length" class="summary-text">共 {{ directLogList.length }} 条记录</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="table-content">
|
||||
<UpperTable
|
||||
:data="directLogList"
|
||||
:columns="logColumns"
|
||||
:show-selection="canRemove"
|
||||
:multiple-selection="selectedRows"
|
||||
:pagination="pagination"
|
||||
:loading="loading"
|
||||
@selection-change="handleSelectionChange"
|
||||
@page-size-change="handlePageSizeChange"
|
||||
@page-change="handlePageChange"
|
||||
>
|
||||
<template #column-inbound_type="{ row }">
|
||||
{{ formatDirectInboundType(row.inbound_type) }}
|
||||
</template>
|
||||
<template #column-created_at="{ row }">
|
||||
{{ formatDirectInboundDateTime(row, undefined, row.created_at) }}
|
||||
</template>
|
||||
<template v-if="canRemove" #column-operation="{ row }">
|
||||
<el-button
|
||||
link
|
||||
type="danger"
|
||||
size="small"
|
||||
:disabled="!canRemoveRow(row) || removing"
|
||||
@click="handleRemoveRow(row)"
|
||||
>
|
||||
移除
|
||||
</el-button>
|
||||
</template>
|
||||
<template #empty>
|
||||
<div class="empty-tip">暂无导入/PDA 入库记录</div>
|
||||
</template>
|
||||
</UpperTable>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, reactive, ref, watch, onActivated } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import UpperTable from '@/components/UpperTable/index.vue'
|
||||
import {
|
||||
getDirectInboundItems,
|
||||
removeDirectInboundItem,
|
||||
type DirectInboundLog,
|
||||
} from '@/api/storage.directinbound/directinbound'
|
||||
import {
|
||||
canDirectInboundOperate,
|
||||
directInboundLogActionColumn,
|
||||
directInboundLogColumns,
|
||||
formatDirectInboundDateTime,
|
||||
formatDirectInboundType,
|
||||
} from '../entry-config'
|
||||
|
||||
const props = defineProps<{
|
||||
id?: string | number
|
||||
row?: Record<string, unknown> | null
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
refresh: []
|
||||
}>()
|
||||
|
||||
const loading = ref(false)
|
||||
const removing = ref(false)
|
||||
const directLogList = ref<DirectInboundLog[]>([])
|
||||
const selectedRows = ref<DirectInboundLog[]>([])
|
||||
const pagination = reactive({ currentPage: 1, pageSize: 20, total: 0 })
|
||||
|
||||
const entryOrderCode = computed(() => {
|
||||
const code = props.row?.entry_order_code
|
||||
return code ? String(code) : ''
|
||||
})
|
||||
|
||||
const canRemove = computed(() => canDirectInboundOperate(props.row?.order_status))
|
||||
|
||||
const logColumns = computed(() => {
|
||||
if (!canRemove.value) return directInboundLogColumns
|
||||
return [...directInboundLogColumns, directInboundLogActionColumn]
|
||||
})
|
||||
|
||||
watch(
|
||||
() => [props.id, entryOrderCode.value],
|
||||
() => {
|
||||
selectedRows.value = []
|
||||
if (props.id && entryOrderCode.value) {
|
||||
void loadLogs()
|
||||
} else {
|
||||
directLogList.value = []
|
||||
pagination.total = 0
|
||||
}
|
||||
},
|
||||
{ immediate: true }
|
||||
)
|
||||
|
||||
onActivated(() => {
|
||||
if (props.id && entryOrderCode.value) {
|
||||
void loadLogs()
|
||||
}
|
||||
})
|
||||
|
||||
function unwrapPayload(res: Record<string, unknown> | null | undefined) {
|
||||
if (!res) return null
|
||||
if (res.data && typeof res.data === 'object') {
|
||||
return res.data as Record<string, unknown>
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
function canRemoveRow(row: DirectInboundLog): boolean {
|
||||
const logId = Number(row.id)
|
||||
return Number.isInteger(logId) && logId > 0
|
||||
}
|
||||
|
||||
function getRowLabel(row: DirectInboundLog): string {
|
||||
const code = row.warehouse_item_code ? String(row.warehouse_item_code) : ''
|
||||
const name = row.warehouse_item_name ? String(row.warehouse_item_name) : ''
|
||||
const sku = row.stock_id != null ? `SKU ${row.stock_id}` : '未知商品'
|
||||
if (code && name) return `${code} / ${name}`
|
||||
if (code) return code
|
||||
if (name) return name
|
||||
return sku
|
||||
}
|
||||
|
||||
async function loadLogs() {
|
||||
const code = entryOrderCode.value
|
||||
if (!code) {
|
||||
directLogList.value = []
|
||||
pagination.total = 0
|
||||
return
|
||||
}
|
||||
|
||||
loading.value = true
|
||||
try {
|
||||
const res = await getDirectInboundItems({ entry_order_code: code })
|
||||
if (res?.code !== 200 && res?.code !== undefined) {
|
||||
throw new Error(res?.message || '获取入库记录失败')
|
||||
}
|
||||
|
||||
const payload = unwrapPayload(res as Record<string, unknown>)
|
||||
directLogList.value = Array.isArray(payload?.direct_logs)
|
||||
? (payload.direct_logs as DirectInboundLog[])
|
||||
: []
|
||||
pagination.total = directLogList.value.length
|
||||
selectedRows.value = []
|
||||
} catch (error) {
|
||||
console.error('获取入库记录失败:', error)
|
||||
ElMessage.error(error instanceof Error ? error.message : '获取入库记录失败')
|
||||
directLogList.value = []
|
||||
pagination.total = 0
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function handleSelectionChange(rows: DirectInboundLog[]) {
|
||||
selectedRows.value = rows
|
||||
}
|
||||
|
||||
function handlePageSizeChange(size: number) {
|
||||
pagination.pageSize = size
|
||||
}
|
||||
|
||||
function handlePageChange(page: number) {
|
||||
pagination.currentPage = page
|
||||
}
|
||||
|
||||
async function removeLogRow(row: DirectInboundLog): Promise<boolean> {
|
||||
const logId = Number(row.id)
|
||||
if (!Number.isInteger(logId) || logId <= 0) {
|
||||
ElMessage.warning('记录 ID 无效,无法移除')
|
||||
return false
|
||||
}
|
||||
|
||||
const res = await removeDirectInboundItem({ id: logId })
|
||||
if (res?.code !== 200 && res?.code !== undefined) {
|
||||
throw new Error(res?.message || '移除入库记录失败')
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
async function handleRemoveRow(row: DirectInboundLog) {
|
||||
if (!canRemove.value) {
|
||||
ElMessage.warning('当前入库单状态不允许移除记录')
|
||||
return
|
||||
}
|
||||
if (!canRemoveRow(row)) {
|
||||
ElMessage.warning('记录 ID 无效,无法移除')
|
||||
return
|
||||
}
|
||||
|
||||
const label = getRowLabel(row)
|
||||
const quantity = row.quantity ?? '—'
|
||||
try {
|
||||
await ElMessageBox.confirm(
|
||||
`确认移除「${label}」的导入/PDA 入库记录(数量 ${quantity})?\n移除后对应商品的已导入数量将扣减。`,
|
||||
'移除入库记录',
|
||||
{ type: 'warning', confirmButtonText: '确认移除', cancelButtonText: '取消' }
|
||||
)
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
|
||||
removing.value = true
|
||||
try {
|
||||
await removeLogRow(row)
|
||||
ElMessage.success('入库记录已移除')
|
||||
await loadLogs()
|
||||
emit('refresh')
|
||||
} catch (error) {
|
||||
console.error('移除入库记录失败:', error)
|
||||
ElMessage.error(error instanceof Error ? error.message : '移除入库记录失败')
|
||||
} finally {
|
||||
removing.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function handleBatchRemove() {
|
||||
if (!canRemove.value) {
|
||||
ElMessage.warning('当前入库单状态不允许移除记录')
|
||||
return
|
||||
}
|
||||
|
||||
const rows = selectedRows.value.filter((row) => canRemoveRow(row))
|
||||
if (!rows.length) {
|
||||
ElMessage.warning('请先选择可移除的入库记录')
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
await ElMessageBox.confirm(
|
||||
`确认批量移除 ${rows.length} 条导入/PDA 入库记录?\n移除后对应商品的已导入数量将扣减。`,
|
||||
'批量移除入库记录',
|
||||
{ type: 'warning', confirmButtonText: '确认移除', cancelButtonText: '取消' }
|
||||
)
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
|
||||
removing.value = true
|
||||
let successCount = 0
|
||||
const failedMessages: string[] = []
|
||||
|
||||
try {
|
||||
for (const row of rows) {
|
||||
try {
|
||||
const ok = await removeLogRow(row)
|
||||
if (ok) successCount += 1
|
||||
} catch (error) {
|
||||
failedMessages.push(
|
||||
`${getRowLabel(row)}: ${error instanceof Error ? error.message : '移除失败'}`
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (successCount > 0) {
|
||||
ElMessage.success(`已移除 ${successCount} 条入库记录`)
|
||||
await loadLogs()
|
||||
emit('refresh')
|
||||
}
|
||||
|
||||
if (failedMessages.length) {
|
||||
ElMessage.error(failedMessages.slice(0, 3).join(';'))
|
||||
} else if (!successCount) {
|
||||
ElMessage.warning('没有记录被移除')
|
||||
}
|
||||
} finally {
|
||||
removing.value = false
|
||||
}
|
||||
}
|
||||
|
||||
defineExpose({
|
||||
loadLogs,
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped lang="scss">
|
||||
.direct-inbound-logs-panel {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
background: #fff;
|
||||
|
||||
.header-actions {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding-bottom: 10px;
|
||||
border-bottom: 1px solid #ebeef5;
|
||||
margin-bottom: 10px;
|
||||
|
||||
.left-actions,
|
||||
.right-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.summary-text {
|
||||
font-size: 12px;
|
||||
color: #606266;
|
||||
}
|
||||
}
|
||||
|
||||
.table-content {
|
||||
flex: 1;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.empty-tip {
|
||||
padding: 24px 0;
|
||||
text-align: center;
|
||||
color: #909399;
|
||||
font-size: 13px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@ -2,12 +2,30 @@
|
||||
<div class="entry-details">
|
||||
<div class="header-actions">
|
||||
<div class="left-actions">
|
||||
<el-button size="small" @click="loadEntryDetail">刷新</el-button>
|
||||
<el-button size="small" disabled>EXCEL导出</el-button>
|
||||
<el-button size="small" disabled>导出</el-button>
|
||||
<el-button size="small" @click="reloadAll">刷新</el-button>
|
||||
<el-button
|
||||
size="small"
|
||||
type="primary"
|
||||
:disabled="!canDirectInbound"
|
||||
:loading="commitLoading"
|
||||
@click="handleCommit"
|
||||
>
|
||||
提交完成入库
|
||||
</el-button>
|
||||
<el-button
|
||||
size="small"
|
||||
:disabled="!canBatchImport"
|
||||
@click="openBatchImportDialog"
|
||||
>
|
||||
批量导入
|
||||
</el-button>
|
||||
</div>
|
||||
<div class="right-actions">
|
||||
<el-tag v-if="canBindReceiving" size="small" type="warning">待入库,可绑定收货明细</el-tag>
|
||||
<el-tag v-if="canDirectInbound" size="small" type="success">可导入/PDA 入库</el-tag>
|
||||
<span v-if="directSummary.total_direct_inbound !== undefined" class="summary-text">
|
||||
已导入 {{ directSummary.total_direct_inbound ?? 0 }} / 计划 {{ directSummary.total_planned ?? '—' }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@ -32,6 +50,37 @@
|
||||
>
|
||||
绑定
|
||||
</el-button>
|
||||
<!-- <el-button
|
||||
v-if="canDirectInbound"
|
||||
link
|
||||
type="primary"
|
||||
size="small"
|
||||
:disabled="!canImportRow(row)"
|
||||
@click="openImportDialog(row)"
|
||||
>
|
||||
导入
|
||||
</el-button> -->
|
||||
</template>
|
||||
<template v-else-if="canDirectInbound" #column-operation="{ row }">
|
||||
<el-button
|
||||
link
|
||||
type="primary"
|
||||
size="small"
|
||||
:disabled="!canImportRow(row)"
|
||||
@click="openImportDialog(row)"
|
||||
>
|
||||
导入
|
||||
</el-button>
|
||||
</template>
|
||||
<template #column-direct_inbound_quantity="{ row }">
|
||||
<el-tag size="small" :type="Number(row.direct_inbound_quantity) > 0 ? 'success' : 'info'">
|
||||
{{ row.direct_inbound_quantity ?? 0 }}
|
||||
</el-tag>
|
||||
</template>
|
||||
<template #column-remaining_quantity="{ row }">
|
||||
<el-tag size="small" :type="Number(row.remaining_quantity) > 0 ? 'warning' : 'info'">
|
||||
{{ row.remaining_quantity ?? 0 }}
|
||||
</el-tag>
|
||||
</template>
|
||||
<template #column-pending_total="{ row }">
|
||||
<el-button
|
||||
@ -60,29 +109,57 @@
|
||||
:entry-order-id="props.id"
|
||||
@success="handleUnbindSuccess"
|
||||
/>
|
||||
|
||||
<DirectInboundImportDialog
|
||||
v-model="importDialogVisible"
|
||||
:entry-order-code="entryOrderCode"
|
||||
:target-item="importTargetItem"
|
||||
:batch-file-mode="batchFileMode"
|
||||
:entry-items="tableData as DirectInboundImportRow[]"
|
||||
@success="handleImportSuccess"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, reactive, ref, watch, onMounted } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import UpperTable from '@/components/UpperTable/index.vue'
|
||||
import * as entryApi from '@/api/storage.entry/entry'
|
||||
import {
|
||||
commitDirectInbound,
|
||||
getDirectInboundItems,
|
||||
type DirectInboundItem,
|
||||
} from '@/api/storage.directinbound/directinbound'
|
||||
import BindReceivingDetailsDialog, {
|
||||
type EntryDetailBindRow,
|
||||
} from './BindReceivingDetailsDialog.vue'
|
||||
import UnbindReceivingDetailsDialog from './UnbindReceivingDetailsDialog.vue'
|
||||
import { entrydetail, isPendingEntryOrderStatus } from '../entry-config'
|
||||
import DirectInboundImportDialog, {
|
||||
type DirectInboundImportRow,
|
||||
} from './DirectInboundImportDialog.vue'
|
||||
import {
|
||||
canDirectInboundOperate,
|
||||
entrydetail,
|
||||
isPendingEntryOrderStatus,
|
||||
} from '../entry-config'
|
||||
|
||||
const props = defineProps<{
|
||||
id?: string | number
|
||||
row?: any
|
||||
row?: Record<string, unknown> | null
|
||||
/** 由父级递增,用于跨 Tab 触发明细刷新 */
|
||||
entryDetailRefreshTick?: number
|
||||
}>()
|
||||
|
||||
const tableData = ref<any[]>([])
|
||||
const emit = defineEmits(['refresh'])
|
||||
|
||||
const tableData = ref<Record<string, unknown>[]>([])
|
||||
const loading = ref(false)
|
||||
const multipleSelection = ref<any[]>([])
|
||||
const commitLoading = ref(false)
|
||||
const multipleSelection = ref<Record<string, unknown>[]>([])
|
||||
const entryOrderStatus = ref('')
|
||||
const entryOrderCode = ref('')
|
||||
const directSummary = ref<Record<string, unknown>>({})
|
||||
|
||||
const pagination = reactive({
|
||||
currentPage: 1,
|
||||
@ -95,13 +172,26 @@ const canBindReceiving = computed(() => {
|
||||
return isPendingEntryOrderStatus(status)
|
||||
})
|
||||
|
||||
const canBatchImport = computed(() => canBindReceiving.value)
|
||||
|
||||
const canDirectInbound = computed(() => {
|
||||
const status = props.row?.order_status ?? entryOrderStatus.value
|
||||
return canDirectInboundOperate(status)
|
||||
})
|
||||
|
||||
const detailColumns = computed(() => {
|
||||
const columns = [...entrydetail]
|
||||
if (canBindReceiving.value) {
|
||||
const countIndex = columns.findIndex((col) => col.prop === 'count')
|
||||
const insertAt = countIndex >= 0 ? countIndex : columns.length
|
||||
columns.splice(insertAt, 0,
|
||||
{ prop: 'direct_inbound_quantity', label: '已导入', width: '90', align: 'right' },
|
||||
{ prop: 'remaining_quantity', label: '剩余可入', width: '90', align: 'right' },
|
||||
)
|
||||
if (canBindReceiving.value || canDirectInbound.value) {
|
||||
columns.push({
|
||||
prop: 'operation',
|
||||
label: '操作',
|
||||
width: '90',
|
||||
width: canBindReceiving.value && canDirectInbound.value ? '120' : '90',
|
||||
fixed: 'right',
|
||||
align: 'center',
|
||||
} as unknown as (typeof entrydetail)[number])
|
||||
@ -109,37 +199,85 @@ const detailColumns = computed(() => {
|
||||
return columns
|
||||
})
|
||||
|
||||
const emit = defineEmits(['refresh'])
|
||||
|
||||
const bindDialogVisible = ref(false)
|
||||
const bindTargetItem = ref<EntryDetailBindRow | null>(null)
|
||||
const unbindDialogVisible = ref(false)
|
||||
const unbindTargetItem = ref<EntryDetailBindRow | null>(null)
|
||||
const importDialogVisible = ref(false)
|
||||
const importTargetItem = ref<DirectInboundImportRow | null>(null)
|
||||
const batchFileMode = ref(false)
|
||||
|
||||
watch(importDialogVisible, (visible) => {
|
||||
if (!visible) {
|
||||
batchFileMode.value = false
|
||||
importTargetItem.value = null
|
||||
}
|
||||
})
|
||||
|
||||
watch(
|
||||
() => props.entryDetailRefreshTick,
|
||||
() => {
|
||||
if (props.id && props.entryDetailRefreshTick) {
|
||||
void reloadAll()
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
watch(
|
||||
() => props.id,
|
||||
(newVal) => {
|
||||
if (newVal) {
|
||||
loadEntryDetail()
|
||||
void reloadAll()
|
||||
}
|
||||
},
|
||||
{ immediate: true }
|
||||
)
|
||||
|
||||
function unwrapPayload(res: Record<string, unknown> | null | undefined) {
|
||||
if (!res) return null
|
||||
if (res.data && typeof res.data === 'object') {
|
||||
return res.data as Record<string, unknown>
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
function mergeDirectInboundFields(
|
||||
items: Record<string, unknown>[],
|
||||
directItems: DirectInboundItem[]
|
||||
) {
|
||||
const directMap = new Map<number, DirectInboundItem>()
|
||||
directItems.forEach((item) => {
|
||||
if (item.stock_id != null) {
|
||||
directMap.set(Number(item.stock_id), item)
|
||||
}
|
||||
})
|
||||
|
||||
return items.map((item) => {
|
||||
const stockId = item.stock_id != null ? Number(item.stock_id) : NaN
|
||||
const direct = Number.isFinite(stockId) ? directMap.get(stockId) : undefined
|
||||
return {
|
||||
...item,
|
||||
direct_inbound_quantity: direct?.direct_inbound_quantity ?? 0,
|
||||
remaining_quantity: direct?.remaining_quantity ?? item.count ?? 0,
|
||||
pending_total: direct?.pending_binding_total ?? item.pending_total ?? 0,
|
||||
bindings: direct?.bindings ?? item.bindings,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async function loadEntryDetail() {
|
||||
if (!props.id) return
|
||||
loading.value = true
|
||||
try {
|
||||
const res = await entryApi.getEntryDetail({
|
||||
id: Number(props.id),
|
||||
})
|
||||
const res = await entryApi.getEntryDetail({ id: Number(props.id) })
|
||||
|
||||
if (res && res.code === 200 && res.data?.entryOrder) {
|
||||
const entryOrder = res.data.entryOrder
|
||||
entryOrderStatus.value = entryOrder.order_status || ''
|
||||
entryOrderCode.value = entryOrder.entry_order_code || ''
|
||||
const items = entryOrder.items || []
|
||||
|
||||
tableData.value = items.map((item: any) => ({
|
||||
tableData.value = items.map((item: Record<string, unknown>) => ({
|
||||
...item,
|
||||
entry_order_code: entryOrder.entry_order_code || '',
|
||||
purchase_order_code: entryOrder.purchase_order_code || '',
|
||||
@ -156,11 +294,115 @@ async function loadEntryDetail() {
|
||||
tableData.value = []
|
||||
pagination.total = 0
|
||||
entryOrderStatus.value = ''
|
||||
entryOrderCode.value = ''
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function loadDirectInboundMeta() {
|
||||
const code = entryOrderCode.value || (props.row?.entry_order_code ? String(props.row.entry_order_code) : '')
|
||||
if (!code) {
|
||||
directSummary.value = {}
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await getDirectInboundItems({ entry_order_code: code })
|
||||
if (res?.code !== 200 && res?.code !== undefined) {
|
||||
throw new Error(res?.message || '获取导入入库信息失败')
|
||||
}
|
||||
|
||||
const payload = unwrapPayload(res as Record<string, unknown>)
|
||||
const directItems = Array.isArray(payload?.items) ? (payload.items as DirectInboundItem[]) : []
|
||||
directSummary.value = (payload?.summary as Record<string, unknown>) || {}
|
||||
|
||||
if (tableData.value.length) {
|
||||
tableData.value = mergeDirectInboundFields(tableData.value, directItems)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('获取导入入库信息失败:', error)
|
||||
}
|
||||
}
|
||||
|
||||
async function reloadAll() {
|
||||
await loadEntryDetail()
|
||||
await loadDirectInboundMeta()
|
||||
}
|
||||
|
||||
function canImportRow(row: DirectInboundImportRow) {
|
||||
if (!canDirectInbound.value || !row.stock_id) return false
|
||||
const remaining = Number(row.remaining_quantity ?? 0)
|
||||
return Number.isFinite(remaining) && remaining > 0
|
||||
}
|
||||
|
||||
function openImportDialog(row: DirectInboundImportRow) {
|
||||
if (!canImportRow(row)) {
|
||||
ElMessage.warning('该商品无可导入数量')
|
||||
return
|
||||
}
|
||||
batchFileMode.value = false
|
||||
importTargetItem.value = row
|
||||
importDialogVisible.value = true
|
||||
}
|
||||
|
||||
function openBatchImportDialog() {
|
||||
if (!canBatchImport.value) {
|
||||
ElMessage.warning('仅「待入库」状态可使用批量导入')
|
||||
return
|
||||
}
|
||||
importTargetItem.value = null
|
||||
batchFileMode.value = true
|
||||
importDialogVisible.value = true
|
||||
}
|
||||
|
||||
async function handleImportSuccess() {
|
||||
await reloadAll()
|
||||
emit('refresh')
|
||||
}
|
||||
|
||||
async function handleCommit() {
|
||||
const code = entryOrderCode.value
|
||||
if (!code) {
|
||||
ElMessage.warning('缺少入库单号')
|
||||
return
|
||||
}
|
||||
if (!canDirectInbound.value) {
|
||||
ElMessage.warning('当前入库单状态不允许提交')
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
await ElMessageBox.confirm(
|
||||
`确认提交并完成入库单「${code}」的导入/PDA 入库?提交后将写入库存并更新入库单状态为已完成。`,
|
||||
'提交完成入库',
|
||||
{ type: 'warning', confirmButtonText: '确认提交', cancelButtonText: '取消' }
|
||||
)
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
|
||||
commitLoading.value = true
|
||||
try {
|
||||
const res = await commitDirectInbound({ entry_order_code: code })
|
||||
if (res?.code !== 200 && res?.code !== undefined) {
|
||||
throw new Error(res?.message || '提交完成入库失败')
|
||||
}
|
||||
|
||||
const payload = unwrapPayload(res as Record<string, unknown>)
|
||||
ElMessage.success(
|
||||
`入库完成:共 ${payload?.items_count ?? '—'} 种商品,总量 ${payload?.total_quantity ?? '—'}`
|
||||
)
|
||||
await reloadAll()
|
||||
emit('refresh')
|
||||
} catch (error) {
|
||||
console.error('提交完成入库失败:', error)
|
||||
ElMessage.error(error instanceof Error ? error.message : '提交完成入库失败')
|
||||
} finally {
|
||||
commitLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function openBindDialog(row: EntryDetailBindRow) {
|
||||
if (!canBindReceiving.value) {
|
||||
ElMessage.warning('仅待入库状态的入库单支持绑定收货明细')
|
||||
@ -196,12 +438,12 @@ function openUnbindDialog(row: EntryDetailBindRow) {
|
||||
}
|
||||
|
||||
async function handleBindSuccess() {
|
||||
await loadEntryDetail()
|
||||
await reloadAll()
|
||||
emit('refresh')
|
||||
}
|
||||
|
||||
async function handleUnbindSuccess() {
|
||||
await loadEntryDetail()
|
||||
await reloadAll()
|
||||
emit('refresh')
|
||||
}
|
||||
|
||||
@ -212,23 +454,26 @@ function hasPendingBindings(row: EntryDetailBindRow): boolean {
|
||||
return Array.isArray(bindings) && bindings.length > 0
|
||||
}
|
||||
|
||||
const handleSelectionChange = (val: any[]) => {
|
||||
const handleSelectionChange = (val: Record<string, unknown>[]) => {
|
||||
multipleSelection.value = val
|
||||
}
|
||||
|
||||
const handlePageSizeChange = (val: number) => {
|
||||
pagination.pageSize = val
|
||||
loadEntryDetail()
|
||||
const handlePageSizeChange = () => {
|
||||
void reloadAll()
|
||||
}
|
||||
|
||||
const handlePageChange = (val: number) => {
|
||||
pagination.currentPage = val
|
||||
loadEntryDetail()
|
||||
const handlePageChange = () => {
|
||||
void reloadAll()
|
||||
}
|
||||
|
||||
defineExpose({
|
||||
openBatchImportDialog,
|
||||
reloadAll,
|
||||
})
|
||||
|
||||
onMounted(() => {
|
||||
if (props.id) {
|
||||
loadEntryDetail()
|
||||
void reloadAll()
|
||||
}
|
||||
})
|
||||
</script>
|
||||
@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@ -12,7 +12,7 @@ type EntryScanFieldGroupKey = keyof typeof ENTRY_SCAN_FIELD_GROUPS
|
||||
export function entryScanField<G extends EntryScanFieldGroupKey>(
|
||||
group: G,
|
||||
field: Record<string, any>
|
||||
) {
|
||||
): Record<string, any> & { 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<string, string> = {
|
||||
...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<string, string> = {
|
||||
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<string, unknown>)?.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' },
|
||||
|
||||
@ -20,7 +20,7 @@
|
||||
<!-- <el-button size="small" @click="handleCreateEntry">新建入库单</el-button> -->
|
||||
<el-button size="small" @click="handleCompleteEntry">完成入库</el-button>
|
||||
<el-button size="small" :disabled="!hasSelection" @click="confirmBatchCancel">批量作废</el-button>
|
||||
<el-button size="small" :loading="exportLoading" @click="handleExport">导出</el-button>
|
||||
<ExportModeDropdown :loading="exportLoading" @action="handleExportAction" />
|
||||
<el-button size="small" @click="handleImport">导入</el-button>
|
||||
<el-button size="small" @click="openColumnConfigPanel">字段设置</el-button>
|
||||
<el-button size="small" @click="toggleDetailVisible">{{ detailVisible ? '隐藏详情' : '显示详情' }}</el-button>
|
||||
@ -55,18 +55,18 @@
|
||||
@selection-change="onSelectionChange"
|
||||
>
|
||||
<template #column-order_status="{ row }">
|
||||
<el-tag :type="getStatusType(row.order_status)" size="small">
|
||||
{{ translateField('order_status', row.order_status) }}
|
||||
<el-tag :type="getEntryOrderStatusTagType(row.order_status)" size="small">
|
||||
{{ formatEntryOrderStatus(row.order_status) }}
|
||||
</el-tag>
|
||||
</template>
|
||||
|
||||
<template #column-order_type="{ row }">
|
||||
<span>{{ translateField('order_type', row.order_type) }}</span>
|
||||
<span>{{ translateEntryField('order_type', row.order_type) }}</span>
|
||||
</template>
|
||||
|
||||
<template #column-sync_status="{ row }">
|
||||
<el-tag :type="getSyncStatusType(row.sync_status)" size="small">
|
||||
{{ translateField('sync_status', row.sync_status) }}
|
||||
{{ translateEntryField('sync_status', row.sync_status) }}
|
||||
</el-tag>
|
||||
</template>
|
||||
|
||||
@ -84,7 +84,7 @@
|
||||
|
||||
<template #column-source_type="{ row }">
|
||||
<el-tag size="small" :type="row.source_type === 'WMS' ? '' : row.source_type === 'QM' ? 'warning' : 'success'">
|
||||
{{ translateField('source_type', row.source_type) }}
|
||||
{{ translateEntryField('source_type', row.source_type) }}
|
||||
</el-tag>
|
||||
</template>
|
||||
|
||||
@ -105,6 +105,7 @@
|
||||
<el-tabs v-model="activeTab" class="detail-tab">
|
||||
<el-tab-pane label="表单操作" name="operate" />
|
||||
<el-tab-pane label="入库明细" name="details" />
|
||||
<el-tab-pane label="入库记录" name="directInboundLogs" />
|
||||
<el-tab-pane label="操作日志" name="logs" />
|
||||
</el-tabs>
|
||||
</div>
|
||||
@ -113,9 +114,11 @@
|
||||
<KeepAlive>
|
||||
<component
|
||||
:is="activeComponent"
|
||||
ref="detailComponentRef"
|
||||
:id="selectedEntryId"
|
||||
:row="selectedRow"
|
||||
@refresh="loadData"
|
||||
:entry-detail-refresh-tick="entryDetailRefreshTick"
|
||||
@refresh="handleDetailRefresh"
|
||||
/>
|
||||
</KeepAlive>
|
||||
</div>
|
||||
@ -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<any>(null)
|
||||
const upperTable = ref<any>(null)
|
||||
const detailComponentRef = ref<{ openBatchImportDialog?: () => void; reloadAll?: () => Promise<void> } | null>(null)
|
||||
const entryDetailRefreshTick = ref(0)
|
||||
|
||||
const {
|
||||
splitStackRef,
|
||||
@ -242,6 +253,7 @@ const currentSort = reactive({ prop: '', order: '' })
|
||||
|
||||
const componentMap: Record<string, any> = {
|
||||
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<string, string> = {
|
||||
'CREATED': 'info',
|
||||
'PENDING': 'warning',
|
||||
'PARTIAL': 'primary',
|
||||
'PARTIAL_RECEIVED': 'primary',
|
||||
'COMPLETED': 'success',
|
||||
'CANCELLED': 'danger'
|
||||
}
|
||||
return map[status] || undefined
|
||||
}
|
||||
|
||||
function getSyncStatusType(status: string) {
|
||||
const map: Record<string, string> = {
|
||||
'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)
|
||||
}
|
||||
</script>
|
||||
|
||||
|
||||
264
src/views/storage/entry/utils/direct-inbound-xlsx-import.ts
Normal file
264
src/views/storage/entry/utils/direct-inbound-xlsx-import.ts
Normal file
@ -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<string, unknown>, 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<string, unknown> | 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<string, unknown>
|
||||
const direct = (info?.data || info) as Record<string, unknown>
|
||||
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<string, unknown>
|
||||
const list = Array.isArray(data?.list) ? data.list : Array.isArray(data) ? data : []
|
||||
if (!list.length) return {}
|
||||
|
||||
const exact =
|
||||
(list as Record<string, unknown>[]).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<string, unknown>
|
||||
const id = Number(item?.id)
|
||||
return {
|
||||
id: Number.isFinite(id) && id > 0 ? id : undefined,
|
||||
displayName: getSpaceDisplayName(item),
|
||||
}
|
||||
}
|
||||
|
||||
export async function resolveParsedRowSpaces(rows: ParsedDirectInboundImportRow[]): Promise<void> {
|
||||
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<number, DirectInboundImportRow>()
|
||||
const byCodeLine = new Map<string, DirectInboundImportRow>()
|
||||
|
||||
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<string, unknown>,
|
||||
stockId: number | undefined,
|
||||
index: ReturnType<typeof buildEntryItemIndex>
|
||||
): 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<string, unknown>[],
|
||||
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<Record<string, unknown>[]> {
|
||||
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<Record<string, unknown>>(worksheet, { defval: '' })
|
||||
}
|
||||
|
||||
export function downloadDirectInboundImportTemplate(
|
||||
entryItems: DirectInboundImportRow[],
|
||||
fileName?: string
|
||||
) {
|
||||
const exportData = entryItems.map((item) => {
|
||||
const mapped: Record<string, unknown> = {}
|
||||
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`)
|
||||
}
|
||||
@ -19,7 +19,7 @@
|
||||
<el-button size="small" type="primary" @click="loadData">刷新</el-button>
|
||||
<!-- <el-button size="small" @click="handleCreateEntry">新建入库单</el-button> -->
|
||||
<el-button size="small" :disabled="!hasSelection" @click="confirmBatchCancel">批量作废</el-button>
|
||||
<el-button size="small" :disabled="!hasSelection" :loading="exportLoading" @click="handleExport">导出</el-button>
|
||||
<ExportModeDropdown :loading="exportLoading" @action="handleExportAction" />
|
||||
<el-button size="small" @click="handleImport">导入</el-button>
|
||||
<el-button size="small" @click="openColumnConfigPanel">字段设置</el-button>
|
||||
<el-button size="small" @click="toggleDetailVisible">{{ detailVisible ? '隐藏详情' : '显示详情' }}</el-button>
|
||||
@ -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<any>(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('导入功能')
|
||||
}
|
||||
|
||||
@ -16,13 +16,7 @@
|
||||
<div class="toolbar">
|
||||
<div class="toolbar-left">
|
||||
<el-button size="small" type="primary" @click="loadData">刷新</el-button>
|
||||
<el-button
|
||||
size="small"
|
||||
:loading="exportLoading"
|
||||
@click="handleExport"
|
||||
>
|
||||
导出
|
||||
</el-button>
|
||||
<ExportModeDropdown :loading="exportLoading" @action="handleExportAction" />
|
||||
<el-button size="small" @click="openColumnConfigPanel">字段设置</el-button>
|
||||
<el-button size="small" @click="toggleDetailVisible">{{ detailVisible ? '隐藏详情' : '显示详情' }}</el-button>
|
||||
</div>
|
||||
@ -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')
|
||||
}
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
|
||||
@ -443,8 +443,11 @@ const toolbarActionMap: Record<string, () => void> = {
|
||||
void loadData()
|
||||
},
|
||||
handleCreateReceiving: () => handleCreateReceiving(),
|
||||
handleExport: () => {
|
||||
void handleExport()
|
||||
handleExportWaybill: () => {
|
||||
void handleExport('waybill')
|
||||
},
|
||||
handleExportItem: () => {
|
||||
void handleExport('item')
|
||||
},
|
||||
openColumnConfigPanel: () => openColumnConfigPanel(),
|
||||
toggleDetailVisible: () => toggleDetailVisible(),
|
||||
@ -1456,19 +1459,19 @@ async function handleQuickPutaway() {
|
||||
}
|
||||
}
|
||||
|
||||
async function handleExport() {
|
||||
async function handleExport(mode: 'waybill' | 'item' = 'waybill') {
|
||||
if (selectionRows.value.length === 0) {
|
||||
ElMessage.warning('请先勾选要导出的收货单')
|
||||
return
|
||||
}
|
||||
exportLoading.value = true
|
||||
try {
|
||||
// 遍历勾选的收货单,每个收货单生成一个 excel 文件
|
||||
for (const row of selectionRows.value) {
|
||||
const productExportData: any[] = [] // 商品明细行
|
||||
const receivingExportData: any[] = [] // 收货单摘要行(无明细时回退)
|
||||
const allExportData: any[] = []
|
||||
|
||||
for (const row of selectionRows.value) {
|
||||
const productExportData: any[] = []
|
||||
const receivingExportData: any[] = []
|
||||
|
||||
// 收货单摘要行(按 receivingColumns 字段)
|
||||
receivingExportData.push({
|
||||
'收货单号': row.receiving_number,
|
||||
'收货状态': statusConfig[row.status as keyof typeof statusConfig]?.text || row.status || '',
|
||||
@ -1490,64 +1493,71 @@ async function handleExport() {
|
||||
'备注': row.remark || ''
|
||||
})
|
||||
|
||||
// 获取该收货单的商品明细
|
||||
try {
|
||||
const res: any = await receivingApi.getReceivingDetail({
|
||||
id: row.id,
|
||||
pagination: { page: 1, pageSize: 10000 }
|
||||
})
|
||||
|
||||
if (res && res.code === 200 && res.data) {
|
||||
// 兼容多种返回结构
|
||||
const receivingData = res.data.receiving || {}
|
||||
const list = Array.isArray(receivingData.details)
|
||||
? receivingData.details
|
||||
: Array.isArray(res.data.list)
|
||||
? res.data.list
|
||||
: Array.isArray(res.data.details)
|
||||
? res.data.details
|
||||
: []
|
||||
|
||||
// 按 productquick 列导出商品明细,附带收货单号作为关联
|
||||
list.forEach((item: any) => {
|
||||
productExportData.push({
|
||||
'收货单号': row.receiving_number,
|
||||
'货主': row.store_name || '',
|
||||
'商品名称': item.product_name || '',
|
||||
'条码': item.barcode || '',
|
||||
'匹配状态': item.system_product_id ? '已匹配' : '未匹配',
|
||||
'实收数量': item.actual_quantity ?? '',
|
||||
'箱数': item.box_quantity ?? '',
|
||||
'箱规': item.boxes_per_pallet ?? '',
|
||||
'重量': item.weight ?? '',
|
||||
'批次号': item.batch_number || '',
|
||||
'生产日期': item.production_date || '',
|
||||
'有效期': item.expiry_date || '',
|
||||
'入库状态': storageStatusConfig[item.storage_status as keyof typeof storageStatusConfig]?.text || item.storage_status || '',
|
||||
'库位': item.space_id || '',
|
||||
'备注': item.remark || ''
|
||||
})
|
||||
if (mode === 'item') {
|
||||
try {
|
||||
const res: any = await receivingApi.getReceivingDetail({
|
||||
id: row.id,
|
||||
pagination: { page: 1, pageSize: 10000 }
|
||||
})
|
||||
|
||||
if (res && res.code === 200 && res.data) {
|
||||
const receivingData = res.data.receiving || {}
|
||||
const detailList = Array.isArray(receivingData.details)
|
||||
? receivingData.details
|
||||
: Array.isArray(res.data.list)
|
||||
? res.data.list
|
||||
: Array.isArray(res.data.details)
|
||||
? res.data.details
|
||||
: []
|
||||
|
||||
detailList.forEach((item: any) => {
|
||||
productExportData.push({
|
||||
'收货单号': row.receiving_number,
|
||||
'货主': row.store_name || '',
|
||||
'商品名称': item.product_name || '',
|
||||
'条码': item.barcode || '',
|
||||
'匹配状态': item.system_product_id ? '已匹配' : '未匹配',
|
||||
'实收数量': item.actual_quantity ?? '',
|
||||
'箱数': item.box_quantity ?? '',
|
||||
'箱规': item.boxes_per_pallet ?? '',
|
||||
'重量': item.weight ?? '',
|
||||
'批次号': item.batch_number || '',
|
||||
'生产日期': item.production_date || '',
|
||||
'有效期': item.expiry_date || '',
|
||||
'入库状态': storageStatusConfig[item.storage_status as keyof typeof storageStatusConfig]?.text || item.storage_status || '',
|
||||
'库位': item.space_id || '',
|
||||
'备注': item.remark || ''
|
||||
})
|
||||
})
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn(`获取收货单 ${row.receiving_number} 商品明细失败,跳过`, e)
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn(`获取收货单 ${row.receiving_number} 商品明细失败,跳过`, e)
|
||||
}
|
||||
|
||||
// 优先导出商品明细;若该收货单无明细,则回退导出收货单摘要
|
||||
const exportData = productExportData.length > 0 ? productExportData : receivingExportData
|
||||
const sheetName = productExportData.length > 0 ? '收货单商品明细' : '收货单摘要'
|
||||
|
||||
if (exportData.length > 0) {
|
||||
const ws = XLSX.utils.json_to_sheet(exportData)
|
||||
const wb = XLSX.utils.book_new()
|
||||
XLSX.utils.book_append_sheet(wb, ws, sheetName)
|
||||
|
||||
// 文件名使用收货单号
|
||||
const fileName = `${row.receiving_number}.xlsx`
|
||||
XLSX.writeFile(wb, fileName)
|
||||
}
|
||||
const rowExportData = mode === 'item'
|
||||
? (productExportData.length > 0 ? productExportData : receivingExportData)
|
||||
: receivingExportData
|
||||
allExportData.push(...rowExportData)
|
||||
}
|
||||
|
||||
if (allExportData.length === 0) {
|
||||
ElMessage.warning('没有可导出的数据')
|
||||
return
|
||||
}
|
||||
|
||||
const hasProductDetail = mode === 'item' && allExportData.some((row) => '商品名称' in row)
|
||||
const sheetName = hasProductDetail ? '收货单商品明细' : '收货单摘要'
|
||||
const suffix = mode === 'item' ? '-含明细' : ''
|
||||
const fileName = selectionRows.value.length === 1
|
||||
? `${selectionRows.value[0].receiving_number}${suffix}.xlsx`
|
||||
: `收货单导出_${Date.now()}${suffix}.xlsx`
|
||||
|
||||
const ws = XLSX.utils.json_to_sheet(allExportData)
|
||||
const wb = XLSX.utils.book_new()
|
||||
XLSX.utils.book_append_sheet(wb, ws, sheetName)
|
||||
XLSX.writeFile(wb, fileName)
|
||||
|
||||
ElMessage.success('导出完成')
|
||||
} catch (e) {
|
||||
console.error('导出 Excel 失败:', e)
|
||||
|
||||
@ -17,7 +17,7 @@ type ReceivingScanFieldGroupKey = keyof typeof RECEIVING_SCAN_FIELD_GROUPS
|
||||
export function receivingScanField<G extends ReceivingScanFieldGroupKey>(
|
||||
group: G,
|
||||
field: Record<string, any>
|
||||
) {
|
||||
): Record<string, any> & { group: (typeof RECEIVING_SCAN_FIELD_GROUPS)[G] } {
|
||||
return { ...field, group: RECEIVING_SCAN_FIELD_GROUPS[group] }
|
||||
}
|
||||
|
||||
@ -501,7 +501,18 @@ export const addReceivingFields = [
|
||||
export const receivingToolbarButtons: ToolbarButtonConfig[] = [
|
||||
{ key: 'refresh', label: '刷新', type: 'primary', size: 'small', loadingKey: 'loading', action: 'loadData' },
|
||||
{ key: 'create', label: '添加收货单', type: 'primary', size: 'small', action: 'handleCreateReceiving' },
|
||||
{ key: 'export', label: '导出', size: 'small', loadingKey: 'exportLoading', action: 'handleExport' },
|
||||
{
|
||||
key: 'export',
|
||||
label: '导出',
|
||||
size: 'small',
|
||||
loadingKey: 'exportLoading',
|
||||
action: 'handleExportWaybill',
|
||||
buttonType: 'dropdown',
|
||||
dropdownOptions: [
|
||||
{ label: '不含明细', action: 'handleExportWaybill' },
|
||||
{ label: '含明细', action: 'handleExportItem', divided: true }
|
||||
]
|
||||
},
|
||||
{ key: 'columnConfig', label: '字段设置', size: 'small', action: 'openColumnConfigPanel' },
|
||||
{
|
||||
key: 'toggleDetail',
|
||||
|
||||
@ -16,11 +16,11 @@
|
||||
<div class="toolbar">
|
||||
<div class="toolbar-left">
|
||||
<el-button size="small" type="primary" @click="loadData">刷新</el-button>
|
||||
<el-button size="small" :loading="exportLoading" @click="handleExportDetail">导出库存明细</el-button>
|
||||
<ExportModeDropdown :loading="exportLoading" @action="handleExportAction" />
|
||||
<el-button size="small" @click="openColumnConfigPanel">字段设置</el-button>
|
||||
<el-button size="small" @click="toggleDetailVisible">{{ detailVisible ? '隐藏详情' : '显示详情' }}</el-button>
|
||||
<span class="toolbar-title">库存报表</span>
|
||||
<el-tag size="small" type="info">共 {{ pagination.total }} 条</el-tag>
|
||||
<!-- <span class="toolbar-title">库存报表</span>
|
||||
<el-tag size="small" type="info">共 {{ pagination.total }} 条</el-tag> -->
|
||||
<template v-if="pagination.total > 0">
|
||||
<el-tag size="small" effect="plain">入库合计 {{ formatNumber(sumInbound) }}</el-tag>
|
||||
<el-tag size="small" effect="plain">出库合计 {{ formatNumber(sumOutbound) }}</el-tag>
|
||||
@ -86,40 +86,30 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<el-dialog
|
||||
v-model="exportDialogVisible"
|
||||
<AsyncExportProgressDialog
|
||||
v-model:visible="exportDialogVisible"
|
||||
title="库存报表导出进度"
|
||||
width="min(520px, 92vw)"
|
||||
append-to-body
|
||||
align-center
|
||||
:show-close="false"
|
||||
:close-on-click-modal="false"
|
||||
:close-on-press-escape="false"
|
||||
>
|
||||
<div class="export-progress-panel">
|
||||
<div class="export-progress-panel__header">
|
||||
<span class="export-progress-panel__meta">任务ID:{{ exportTaskProgress.taskId || '—' }}</span>
|
||||
</div>
|
||||
<el-progress :percentage="exportProgressPercent" :status="exportProgressBarStatus" :stroke-width="16" />
|
||||
<div class="export-progress-panel__info">
|
||||
<span>状态:{{ exportStatusText }}</span>
|
||||
<span>进度:{{ exportProgressPercent }}%</span>
|
||||
<span v-if="exportTaskProgress.updateTime">更新时间:{{ formatDateTime(exportTaskProgress.updateTime) }}</span>
|
||||
</div>
|
||||
<div v-if="exportTaskProgress.message || exportTaskProgress.error" class="export-progress-panel__message">
|
||||
{{ exportTaskProgress.error || exportTaskProgress.message }}
|
||||
</div>
|
||||
</div>
|
||||
</el-dialog>
|
||||
:loading="exportLoading"
|
||||
:progress-percent="exportProgressPercent"
|
||||
:progress-status="exportProgressStatus"
|
||||
:status-label="exportStatusLabel"
|
||||
:task-id="exportTaskProgress.taskId"
|
||||
:message="exportTaskProgress.message"
|
||||
:error="exportTaskProgress.error"
|
||||
:update-time="exportTaskProgress.updateTime"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, onMounted, reactive, ref } from 'vue'
|
||||
import { computed, onMounted, reactive, ref } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import dayjs from 'dayjs'
|
||||
import ScanBox from '@/components/ScanBox/index.vue'
|
||||
import UpperTable from '@/components/UpperTable/index.vue'
|
||||
import ExportModeDropdown from '@/components/ExportModeDropdown.vue'
|
||||
import AsyncExportProgressDialog from '@/components/AsyncExportProgressDialog.vue'
|
||||
import { useAsyncExportTask } from '@/composables/useAsyncExportTask'
|
||||
import {
|
||||
exportInventoryReport,
|
||||
getExportTaskProgress,
|
||||
@ -179,9 +169,24 @@ function openColumnConfigPanel() {
|
||||
|
||||
const tableSize = ref<'small' | 'default' | 'large'>('small')
|
||||
const loading = ref(false)
|
||||
const exportLoading = ref(false)
|
||||
const queryTime = ref(0)
|
||||
|
||||
const {
|
||||
exportLoading,
|
||||
exportDialogVisible,
|
||||
exportTaskProgress,
|
||||
exportProgressPercent,
|
||||
exportProgressStatus,
|
||||
exportStatusLabel,
|
||||
submitExportTaskWithMode,
|
||||
resumeExportTaskFromStorage,
|
||||
hasPendingExportTask
|
||||
} = useAsyncExportTask({
|
||||
storageKey: 'storage.report.export.taskId',
|
||||
submitExport: (payload) => exportInventoryReport(payload as StorageReportExportBody),
|
||||
queryProgress: (params) => getExportTaskProgress(params)
|
||||
})
|
||||
|
||||
const fullList = ref<any[]>([])
|
||||
const list = ref<any[]>([])
|
||||
const columns = ref(buildReportTableColumns([]))
|
||||
@ -198,18 +203,6 @@ const currentSort = reactive<{ prop: string; order: '' | 'ascending' | 'descendi
|
||||
|
||||
const selectedRid = ref<string | null>(null)
|
||||
const currentConditionRaw = ref<any>({})
|
||||
const exportDialogVisible = ref(false)
|
||||
const exportTaskProgress = reactive({
|
||||
taskId: '',
|
||||
status: 'submitted' as 'submitted' | 'running' | 'success' | 'failed' | 'not_found',
|
||||
progress: 0,
|
||||
message: '',
|
||||
error: '',
|
||||
downloadUrl: '',
|
||||
updateTime: 0
|
||||
})
|
||||
let exportPollingTimer: number | null = null
|
||||
const STORAGE_REPORT_EXPORT_TASK_ID_KEY = 'storage.report.export.taskId'
|
||||
|
||||
const selectedRow = computed(() => fullList.value.find((r) => r.__rid === selectedRid.value) || null)
|
||||
|
||||
@ -304,129 +297,30 @@ function buildReportQueryPayload(): StorageReportSearchBody {
|
||||
return body
|
||||
}
|
||||
|
||||
function normalizeDownloadUrl(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}`
|
||||
async function handleExportWaybill() {
|
||||
if (hasPendingExportTask()) {
|
||||
ElMessage.warning('检测到未完成导出任务,请等待当前任务完成后再试')
|
||||
resumeExportTaskFromStorage()
|
||||
return
|
||||
}
|
||||
return `${window.location.origin}${normalizedPath}`
|
||||
await submitExportTaskWithMode(buildReportQueryPayload() as Record<string, unknown>, 'waybill')
|
||||
}
|
||||
|
||||
function resetExportProgress() {
|
||||
exportTaskProgress.taskId = ''
|
||||
exportTaskProgress.status = 'submitted'
|
||||
exportTaskProgress.progress = 0
|
||||
exportTaskProgress.message = ''
|
||||
exportTaskProgress.error = ''
|
||||
exportTaskProgress.downloadUrl = ''
|
||||
exportTaskProgress.updateTime = 0
|
||||
}
|
||||
|
||||
function saveExportTaskId(taskId: string) {
|
||||
if (!taskId) return
|
||||
try {
|
||||
window.localStorage.setItem(STORAGE_REPORT_EXPORT_TASK_ID_KEY, taskId)
|
||||
} catch (error) {
|
||||
console.warn('保存导出任务ID失败:', error)
|
||||
async function handleExportItem() {
|
||||
if (hasPendingExportTask()) {
|
||||
ElMessage.warning('检测到未完成导出任务,请等待当前任务完成后再试')
|
||||
resumeExportTaskFromStorage()
|
||||
return
|
||||
}
|
||||
await submitExportTaskWithMode(buildReportQueryPayload() as Record<string, unknown>, 'item')
|
||||
}
|
||||
|
||||
function getSavedExportTaskId() {
|
||||
try {
|
||||
return String(window.localStorage.getItem(STORAGE_REPORT_EXPORT_TASK_ID_KEY) || '').trim()
|
||||
} catch (error) {
|
||||
console.warn('读取导出任务ID失败:', error)
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
function clearSavedExportTaskId() {
|
||||
try {
|
||||
window.localStorage.removeItem(STORAGE_REPORT_EXPORT_TASK_ID_KEY)
|
||||
} catch (error) {
|
||||
console.warn('清理导出任务ID失败:', error)
|
||||
}
|
||||
}
|
||||
|
||||
function stopExportPolling() {
|
||||
if (exportPollingTimer) {
|
||||
window.clearTimeout(exportPollingTimer)
|
||||
exportPollingTimer = null
|
||||
}
|
||||
}
|
||||
|
||||
function scheduleExportPolling(delay = 1500) {
|
||||
stopExportPolling()
|
||||
exportPollingTimer = window.setTimeout(() => {
|
||||
void refreshExportTaskProgress()
|
||||
}, delay)
|
||||
}
|
||||
|
||||
function downloadFile(url: string) {
|
||||
const finalUrl = normalizeDownloadUrl(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()
|
||||
}
|
||||
|
||||
async function refreshExportTaskProgress() {
|
||||
if (!exportTaskProgress.taskId) return
|
||||
try {
|
||||
const res: any = await getExportTaskProgress({ taskId: exportTaskProgress.taskId })
|
||||
if (!res) {
|
||||
scheduleExportPolling()
|
||||
return
|
||||
}
|
||||
exportTaskProgress.status = res.status || exportTaskProgress.status
|
||||
exportTaskProgress.progress = Number.isFinite(Number(res.progress)) ? Number(res.progress) : exportTaskProgress.progress
|
||||
exportTaskProgress.message = res.message || ''
|
||||
exportTaskProgress.error = res.error || ''
|
||||
exportTaskProgress.downloadUrl = res.download_url || ''
|
||||
exportTaskProgress.updateTime = Number(res.update_time || 0)
|
||||
|
||||
if (exportTaskProgress.status === 'success') {
|
||||
stopExportPolling()
|
||||
exportLoading.value = false
|
||||
clearSavedExportTaskId()
|
||||
try {
|
||||
if (exportTaskProgress.downloadUrl) {
|
||||
downloadFile(exportTaskProgress.downloadUrl)
|
||||
ElMessage.success(exportTaskProgress.message || '导出完成,文件已开始下载')
|
||||
} else {
|
||||
ElMessage.warning(exportTaskProgress.message || '导出完成,但未返回下载地址')
|
||||
}
|
||||
} finally {
|
||||
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 (error: any) {
|
||||
console.error('查询库存报表导出进度失败:', error)
|
||||
scheduleExportPolling(2000)
|
||||
function handleExportAction(action: string) {
|
||||
if (action === 'handleExportItem') {
|
||||
void handleExportItem()
|
||||
return
|
||||
}
|
||||
void handleExportWaybill()
|
||||
}
|
||||
|
||||
async function loadFilterData() {
|
||||
@ -515,56 +409,6 @@ function handleSortChange({ prop, order }: { prop: string; order: '' | 'ascendin
|
||||
loadData()
|
||||
}
|
||||
|
||||
async function handleExportDetail() {
|
||||
const savedTaskId = getSavedExportTaskId()
|
||||
if (savedTaskId) {
|
||||
ElMessage.warning('检测到未完成导出任务,请等待当前任务完成后再试')
|
||||
resumeExportTaskFromStorage()
|
||||
return
|
||||
}
|
||||
|
||||
if (exportLoading.value) return
|
||||
exportLoading.value = true
|
||||
resetExportProgress()
|
||||
exportDialogVisible.value = true
|
||||
try {
|
||||
const body: StorageReportExportBody = buildReportQueryPayload()
|
||||
const res: any = await exportInventoryReport(body)
|
||||
if (!res || !res.task_id) {
|
||||
throw new Error(res?.message || '导出任务提交失败')
|
||||
}
|
||||
exportTaskProgress.taskId = res.task_id
|
||||
exportTaskProgress.status = res.status || 'submitted'
|
||||
exportTaskProgress.progress = Number.isFinite(Number(res.progress)) ? Number(res.progress) : 0
|
||||
exportTaskProgress.message = res.message || '任务已受理'
|
||||
exportTaskProgress.error = res.error || ''
|
||||
exportTaskProgress.updateTime = Number(res.update_time || 0)
|
||||
saveExportTaskId(exportTaskProgress.taskId)
|
||||
scheduleExportPolling(800)
|
||||
} catch (error: any) {
|
||||
exportLoading.value = false
|
||||
exportDialogVisible.value = false
|
||||
resetExportProgress()
|
||||
clearSavedExportTaskId()
|
||||
ElMessage.error(error?.message || '导出任务提交失败')
|
||||
}
|
||||
}
|
||||
|
||||
function resumeExportTaskFromStorage() {
|
||||
const savedTaskId = getSavedExportTaskId()
|
||||
if (!savedTaskId) 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 handlePageChange(page: number) {
|
||||
pagination.currentPage = page
|
||||
applyClientPage()
|
||||
@ -580,59 +424,11 @@ function handleRowClick(row: any) {
|
||||
selectedRid.value = row?.__rid ?? null
|
||||
}
|
||||
|
||||
const exportProgressPercent = computed(() => {
|
||||
const value = Number(exportTaskProgress.progress || 0)
|
||||
if (!Number.isFinite(value)) return 0
|
||||
return Math.min(100, Math.max(0, Math.round(value)))
|
||||
})
|
||||
|
||||
const exportProgressBarStatus = computed(() => {
|
||||
if (exportTaskProgress.status === 'failed' || exportTaskProgress.status === 'not_found') return 'exception'
|
||||
if (exportTaskProgress.status === 'success' || exportProgressPercent.value >= 100) return 'success'
|
||||
return undefined
|
||||
})
|
||||
|
||||
const exportStatusText = computed(() => {
|
||||
const map: Record<string, string> = {
|
||||
submitted: '已受理',
|
||||
running: '进行中',
|
||||
success: '成功',
|
||||
failed: '失败',
|
||||
not_found: '未找到'
|
||||
}
|
||||
return map[exportTaskProgress.status] || exportTaskProgress.status || '—'
|
||||
})
|
||||
|
||||
function formatDateTime(value: string | number | null | undefined) {
|
||||
if (!value) return '—'
|
||||
let normalizedValue: string | number = value
|
||||
if (typeof value === 'string' && /^\d+$/.test(value.trim())) {
|
||||
const numericValue = Number(value.trim())
|
||||
normalizedValue = value.trim().length <= 10 ? numericValue * 1000 : numericValue
|
||||
} else if (typeof value === 'number' && Number.isFinite(value) && value > 0 && value < 1000000000000) {
|
||||
normalizedValue = value * 1000
|
||||
}
|
||||
|
||||
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}`
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
loadFilterData()
|
||||
loadData()
|
||||
resumeExportTaskFromStorage()
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
stopExportPolling()
|
||||
})
|
||||
</script>
|
||||
|
||||
|
||||
|
||||
@ -20,7 +20,7 @@
|
||||
<el-button size="small" type="primary" @click="loadData">刷新</el-button>
|
||||
<el-button size="small" @click="handleCreateStockout">新建出库单</el-button>
|
||||
<el-button size="small" :disabled="!hasSelection" @click="confirmBatchCancel">批量作废</el-button>
|
||||
<el-button size="small" :loading="exportLoading" @click="handleExport">导出</el-button>
|
||||
<ExportModeDropdown :loading="exportLoading" @action="handleExportAction" />
|
||||
<el-button size="small" @click="handleImport">导入</el-button>
|
||||
<el-button size="small" @click="openColumnConfigPanel">字段设置</el-button>
|
||||
<el-button size="small" @click="toggleDetailVisible">{{ detailVisible ? '隐藏详情' : '显示详情' }}</el-button>
|
||||
@ -131,6 +131,8 @@ import {
|
||||
import stockoutdetail from './component/stockoutdetail.vue'
|
||||
import product from './component/product.vue'
|
||||
import log from './component/log.vue'
|
||||
import ExportModeDropdown from '@/components/ExportModeDropdown.vue'
|
||||
import * as XLSX from 'xlsx'
|
||||
import { useVerticalSplitPane } from '@/composables/useVerticalSplitPane'
|
||||
|
||||
const scanBox = ref<any>(null)
|
||||
@ -425,12 +427,80 @@ async function confirmBatchCancel() {
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
async function handleExport() {
|
||||
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
|
||||
setTimeout(() => {
|
||||
exportLoading.value = false
|
||||
try {
|
||||
const exportColumns = columns.value.filter((col: any) => col.prop && col.label)
|
||||
|
||||
if (mode === 'waybill') {
|
||||
const headers = exportColumns.map((col: any) => col.label)
|
||||
const data = sourceRows.map((row: any) =>
|
||||
exportColumns.map((col: any) => {
|
||||
const val = row[col.prop]
|
||||
if (col.prop === 'status') {
|
||||
return statusConfig[val as keyof typeof statusConfig]?.text || val || ''
|
||||
}
|
||||
if (col.prop === 'sync_status') {
|
||||
return syncStatusConfig[val as keyof typeof syncStatusConfig]?.text || 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, `出库单列表_${Date.now()}.xlsx`)
|
||||
ElMessage.success('导出成功')
|
||||
return
|
||||
}
|
||||
|
||||
const detailRows: any[] = []
|
||||
for (const row of sourceRows) {
|
||||
try {
|
||||
const res: any = await stockoutApi.stockoutListItems({ id: row.id })
|
||||
const items = res?.data?.list || res?.list || res?.data || []
|
||||
const listData = Array.isArray(items) ? items : []
|
||||
listData.forEach((item: any) => {
|
||||
detailRows.push({
|
||||
'出库单号': row.stockout_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.shipped_qty ?? '',
|
||||
'库位': 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, '出库明细')
|
||||
XLSX.writeFile(wb, `出库明细_${Date.now()}.xlsx`)
|
||||
ElMessage.success('导出成功')
|
||||
}, 1000)
|
||||
} catch (e) {
|
||||
console.error('导出失败:', e)
|
||||
ElMessage.error('导出失败')
|
||||
} finally {
|
||||
exportLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function handleExportAction(action: string) {
|
||||
void handleExport(action === 'handleExportItem' ? 'item' : 'waybill')
|
||||
}
|
||||
|
||||
function handleImport() {
|
||||
|
||||
@ -13,7 +13,7 @@ type StockoutScanFieldGroupKey = keyof typeof STOCKOUT_SCAN_FIELD_GROUPS
|
||||
export function stockoutScanField<G extends StockoutScanFieldGroupKey>(
|
||||
group: G,
|
||||
field: Record<string, any>
|
||||
) {
|
||||
): Record<string, any> & { group: (typeof STOCKOUT_SCAN_FIELD_GROUPS)[G] } {
|
||||
return { ...field, group: STOCKOUT_SCAN_FIELD_GROUPS[group] }
|
||||
}
|
||||
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user