This commit is contained in:
yin 2026-07-15 18:15:56 +08:00
parent 8981807258
commit 7e83aae2c0
14 changed files with 2049 additions and 58 deletions

Binary file not shown.

View File

@ -0,0 +1,110 @@
import request from '@/utils/request'
const v = '1.0'
/** 查询工作台列表(仓库隔离,支持分页与关键词筛选) */
export function list(data?: {
pagination?: { page?: number; pageSize?: number }
where?: { name?: string; barcode?: string; status?: number }
}) {
return request({
url: '/system',
method: 'post',
params: {
method: 'workbench.list',
v,
timestamp: new Date().getTime()
},
data: data || {},
isSystemApi: true
} as any)
}
/** 查询单个工作台详情(仓库隔离) */
export function detail(data: { id: number }) {
return request({
url: '/system',
method: 'post',
params: {
method: 'workbench.detail',
v,
timestamp: new Date().getTime()
},
data,
isSystemApi: true
} as any)
}
/** 新增工作台(仓库隔离,条码仓库内唯一) */
export function create(data: {
name: string
barcode?: string
status?: number
remark?: string
}) {
return request({
url: '/system',
method: 'post',
params: {
method: 'workbench.create',
v,
timestamp: new Date().getTime()
},
data,
isSystemApi: true
} as any)
}
/** 更新工作台信息(仓库隔离) */
export function update(data: {
id: number
name?: string
barcode?: string
status?: number
remark?: string
}) {
return request({
url: '/system',
method: 'post',
params: {
method: 'workbench.update',
v,
timestamp: new Date().getTime()
},
data,
isSystemApi: true
} as any)
}
/** 删除工作台(软删除,仓库隔离) */
export function del(data: { id: number }) {
return request({
url: '/system',
method: 'post',
params: {
method: 'workbench.delete',
v,
timestamp: new Date().getTime()
},
data,
isSystemApi: true
} as any)
}
/** 检查条码在仓库内是否已存在 */
export function checkBarcode(data: {
barcode: string
excludeId?: number
}) {
return request({
url: '/system',
method: 'post',
params: {
method: 'workbench.checkBarcode',
v,
timestamp: new Date().getTime()
},
data,
isSystemApi: true
} as any)
}

View File

@ -69,6 +69,8 @@ export default {
'shipperSigning':'Shipper Signing',
'Product Flow':'Product Flow',
'Externalwarehouse':'External Warehouse',
'workbench':'Workbench',
// 'OwnerReceiving':'Owner Receiving',
},
"login": {
"title": "Login",

View File

@ -71,6 +71,8 @@ export default {
'Productflow':'商品流水',
'Externalwarehouse':'外部仓库',
'StoreReport':'门店报告',
'workbench':'工作台',
// 'OwnerReceiving':'仓库收货单',
},
"login": {
"title": "登录",

View File

@ -39,7 +39,7 @@ export const componentMap: Record<string, any> = {
'store/productflow': () => import('@/views/storage/productflow/index.vue'),
'store/index': () => import('@/views/store/stores/index.vue'),
'Externalwarehouse/shipperSigning/index': () => import('@/views/Externalwarehouse/shipperSigning/index.vue'),
'wave/index': () => import('@/views/order/waveOrder2/index.vue'),
'wave/index': () => import('@/views/order/waveOrder/index.vue'),
/** 与后端菜单 component 字段兼容 */
'order/waveOrder': () => import('@/views/order/waveOrder/index.vue'),
'orderreview/index': () => import('@/views/order/orderreview/index.vue'),
@ -54,6 +54,7 @@ export const componentMap: Record<string, any> = {
'system/print/station': () => import('@/views/system/setting/printStation/index.vue'),
'storage/log': () => import('@/views/storage/log/index.vue'),
'storage/validityperiod':() =>import('@/views/storage/validityperiod/index.vue'),
'system/setting/workbench/index':() => import('@/views/system/setting/workbench/index.vue'),
'system/setting/expressinterface/index':() => import('@/views/system/setting/expressinterface/index.vue'),
'system/setting/encoding/index':() => import('@/views/system/setting/encoding/index.vue'),
'system/setting/shops/index':() => import('@/views/system/setting/shops/index.vue'),

View File

@ -1246,3 +1246,354 @@ export const waveOrder2Columns = (() => {
export const generateMockWaveList = waveOrder2TabPages[0]?.mock?.generateList ?? makeBaseMockWaveList
export const generateMockDetail = waveOrder2TabPages[0]?.mock?.generateDetail ?? makeBaseMockDetail
// ============================================================
// 十一、工具栏按钮系统(参照 orderManagement 设计)
// ============================================================
//
// 按钮分为三类:
// 公共按钮 — 刷新、导出(不同页面调用不同接口)
// 功能按钮 — 点击后打开 pages/ 下对应表单组件
// 基础接口 — 字段设置、隐藏详情
//
// 按钮定义集中在 WAVEORDER2_TOOLBAR_BUTTONS,各标签页通过
// getTabToolbarButtons(name) 获取属于该标签页的按钮列表。
export interface WaveOrder2ToolbarButtonConfig {
key: string
label: string
/** 按钮类别 */
category: 'common' | 'function' | 'basic'
size?: '' | 'default' | 'small' | 'large'
type?: '' | 'primary' | 'success' | 'warning' | 'info' | 'danger'
plain?: boolean
loadingKey?: string
disabledKey?: string
action: string
/** 动态标签 key(如 detailToggleLabel) */
dynamicLabelKey?: string
/** 仅指定标签页可见 */
onlyForTabs?: string[]
/** 下拉按钮配置 */
buttonType?: 'default' | 'dropdown'
dropdownOptions?: Array<{ label: string; action: string; divided?: boolean }>
/** 功能按钮关联的表单组件 key(查 FUNCTION_FORM_REGISTRY,可选) */
formKey?: string
}
/** 按钮类别常量 */
export const TOOLBAR_CATEGORY = {
common: 'common',
function: 'function',
basic: 'basic'
} as const
/** 工具栏按钮注册表(唯一真相来源) */
export const WAVEORDER2_TOOLBAR_BUTTONS: Record<string, WaveOrder2ToolbarButtonConfig> = {
// ===== 公共按钮 =====
refresh: {
key: 'refresh',
label: '刷新',
category: 'common',
type: 'primary',
size: 'small',
loadingKey: 'loading',
action: 'loadData'
},
export: {
key: 'export',
label: '导出',
category: 'common',
size: 'small',
loadingKey: 'exportLoading',
action: 'handleExportWaybill',
buttonType: 'dropdown',
dropdownOptions: [
{ label: '不含明细', action: 'handleExportWaybill' },
{ label: '含明细', action: 'handleExportItem', divided: true }
]
},
// ===== 基础接口 =====
columnConfig: {
key: 'columnConfig',
label: '字段设置',
category: 'basic',
size: 'small',
action: 'openColumnConfigPanel'
},
toggleDetail: {
key: 'toggleDetail',
label: '显示详情',
category: 'basic',
dynamicLabelKey: 'detailToggleLabel',
size: 'small',
action: 'toggleDetailVisible'
},
// ===== 功能按钮(打开表单/确认窗口) =====
fetchGroupOrder: {
key: 'fetchGroupOrder',
label: '抓取团购单',
category: 'function',
type: 'warning',
size: 'small',
action: 'openFetchGroupOrderForm',
onlyForTabs: ['tab1'],
formKey: 'FetchGroupOrderForm'
},
batchAutoGrouping: {
key: 'batchAutoGrouping',
label: '批量改为自动加团',
category: 'function',
type: 'warning',
size: 'small',
disabledKey: 'noSelection',
loadingKey: 'batchAutoGroupingLoading',
action: 'openBatchAutoGroupingForm',
formKey: 'BatchOperationForm'
},
batchFinishAutoGrouping: {
key: 'batchFinishAutoGrouping',
label: '批量结束自动加团',
category: 'function',
type: 'success',
size: 'small',
disabledKey: 'noSelection',
loadingKey: 'batchFinishAutoGroupingLoading',
action: 'openBatchFinishAutoGroupingForm',
formKey: 'BatchOperationForm'
},
batchCancel: {
key: 'batchCancel',
label: '批量取消波次',
category: 'function',
type: 'danger',
size: 'small',
disabledKey: 'noSelection',
loadingKey: 'batchCancelLoading',
action: 'openBatchCancelForm',
formKey: 'BatchOperationForm'
},
batchAllocateExpress: {
key: 'batchAllocateExpress',
label: '快速分配快递号',
category: 'function',
type: 'success',
size: 'small',
disabledKey: 'noSelection',
loadingKey: 'batchAllocateExpressLoading',
action: 'openBatchAllocateExpressForm',
formKey: 'BatchOperationForm'
},
batchAllocateStorage: {
key: 'batchAllocateStorage',
label: '批量分配储位',
category: 'function',
type: 'primary',
plain: true,
size: 'small',
disabledKey: 'noSelection',
loadingKey: 'batchAllocateStorageLoading',
action: 'openBatchAllocateStorageForm',
formKey: 'BatchOperationForm'
},
batchRemoveExceptionOrders: {
key: 'batchRemoveExceptionOrders',
label: '批量移除异常订单',
category: 'function',
type: 'danger',
plain: true,
size: 'small',
disabledKey: 'noSelection',
loadingKey: 'batchRemoveExceptionOrdersLoading',
action: 'openBatchRemoveExceptionOrdersForm',
formKey: 'BatchOperationForm'
}
}
/** 按标签页名称获取工具栏按钮列表 */
export function getTabToolbarButtons(tabName: string): WaveOrder2ToolbarButtonConfig[] {
return Object.values(WAVEORDER2_TOOLBAR_BUTTONS).filter((btn) => {
if (btn.onlyForTabs && !btn.onlyForTabs.includes(tabName)) return false
return true
})
}
/** 按类别获取工具栏按钮 */
export function getToolbarButtonsByCategory(
tabName: string,
category: string
): WaveOrder2ToolbarButtonConfig[] {
return getTabToolbarButtons(tabName).filter((btn) => btn.category === category)
}
// ============================================================
// 十二、功能按钮表单注册表
// ============================================================
// 功能按钮 → 表单组件的映射,组件放在 pages/ 目录下。
// 新增功能按钮表单步骤:
// 1. 在 pages/ 下创建表单组件
// 2. import 组件
// 3. 在 FUNCTION_FORM_REGISTRY 添加一条
// 4. 在 WAVEORDER2_TOOLBAR_BUTTONS 中设置 formKey
import FetchGroupOrderForm from '../pages/FetchGroupOrderForm.vue'
import BatchOperationForm from '../pages/BatchOperationForm.vue'
import {
orderWaveBatchAutoGrouping,
orderWaveBatchFinishAutoGrouping,
orderWaveBatchCancel,
orderWaveBatchCancelTaskProgress,
orderWaveBatchAllocateExpress,
orderWaveBatchAllocateExpressTaskProgress,
orderWaveBatchAllocateStorage,
orderWaveBatchAllocateStorageTaskProgress,
orderWaveBatchRemoveExceptionOrders,
orderWaveBatchRemoveExceptionOrdersTaskProgress
} from '@/api/order.wave/orderwave'
export const FUNCTION_FORM_REGISTRY: Record<string, Component> = {
FetchGroupOrderForm,
BatchOperationForm
}
// ============================================================
// 十三、批量操作表单配置(BatchOperationForm 用)
// ============================================================
export interface BatchOperationConfig {
/** 操作标识 */
action: string
/** 弹窗标题 */
title: string
/** 确认提示文本({count} 替换为选中数量) */
confirmText: string
/** 确认按钮类型 */
confirmType?: 'warning' | 'error' | 'info' | 'success'
/** 确认按钮文本 */
confirmButtonText: string
/** 成功提示文本 */
successText: string
/** 失败提示文本 */
failText: string
/** API 方法(接收 ids 数组) */
apiMethod: (...args: any[]) => Promise<any>
/** 请求参数 key(默认 'ids') */
payloadKey?: string
/**
* 从选中行提取 ID 的字段名。
*
* 单字段(字符串):提取单个字段值组成一维数组。
* 例 'wave_id' → [101, 102, 103]
* 支持 fallback:'wave_id,wave_no' → 优先 wave_id,无则取 wave_no
*
* 多字段(字符串数组):提取多个字段,组成 Record 数组。
* 例 ['wave_id', 'wave_no'] → { wave_id: [101,102], wave_no: ['WV001','WV002'] }
* 此时会直接作为请求体传给 API,payloadKey 不再生效。
*
* 未配置时默认使用 'wave_id'。
*/
idField?: string | string[]
/**
* 自定义请求体构建函数。
* 当需要多字段传参时使用(如同时传 wave_ids + warehouse_id),
* 传入完整的选中行数组,返回自定义 payload 对象。
* 配置此项后,payloadKey / idField 仅用于 UI 展示。
*
* @example
* payloadBuilder: (rows) => ({
* wave_ids: rows.map(r => r.wave_id),
* warehouse_id: rows[0]?.warehouse_id
* })
*/
payloadBuilder?: (rows: Record<string, any>[]) => Record<string, any>
/** 是否需要任务进度轮询 */
useProgress?: boolean
/** 进度查询 API */
progressApiMethod?: (...args: any[]) => Promise<any>
}
/** 各操作的配置映射 */
export const BATCH_OPERATION_CONFIGS: Record<string, BatchOperationConfig> = {
batchAutoGrouping: {
action: 'batchAutoGrouping',
title: '批量改为自动加团',
confirmText: '确定将选中的 {count} 个波次改为自动加团状态吗?',
confirmType: 'warning',
confirmButtonText: '确认修改',
successText: '批量改为自动加团成功',
failText: '批量改为自动加团失败',
apiMethod: orderWaveBatchAutoGrouping,
payloadKey: 'ids',
idField: 'wave_id'
},
batchFinishAutoGrouping: {
action: 'batchFinishAutoGrouping',
title: '批量结束自动加团',
confirmText: '确定结束选中的 {count} 个波次的自动加团吗?',
confirmType: 'success',
confirmButtonText: '确认结束',
successText: '批量结束自动加团成功',
failText: '批量结束自动加团失败',
apiMethod: orderWaveBatchFinishAutoGrouping,
payloadKey: 'ids',
idField: 'wave_id'
},
batchCancel: {
action: 'batchCancel',
title: '批量取消波次',
confirmText: '确定取消选中的 {count} 个波次吗?此操作不可撤销。',
confirmType: 'error',
confirmButtonText: '确认取消',
successText: '批量取消波次成功',
failText: '批量取消波次失败',
apiMethod: orderWaveBatchCancel,
payloadKey: 'wave_ids',
idField: 'wave_id',
useProgress: true,
progressApiMethod: orderWaveBatchCancelTaskProgress
},
batchAllocateExpress: {
action: 'batchAllocateExpress',
title: '快速分配快递号',
confirmText: '确定为选中的 {count} 个波次快速分配快递号吗?',
confirmType: 'success',
confirmButtonText: '确认分配',
successText: '快递号分配任务已提交',
failText: '快递号分配失败',
apiMethod: orderWaveBatchAllocateExpress,
payloadKey: 'wave_ids',
idField: 'wave_id',
useProgress: true,
progressApiMethod: orderWaveBatchAllocateExpressTaskProgress
},
batchAllocateStorage: {
action: 'batchAllocateStorage',
title: '批量分配储位',
confirmText: '确定为选中的 {count} 个波次批量分配储位吗?',
confirmType: 'warning',
confirmButtonText: '确认分配',
successText: '储位分配任务已提交',
failText: '储位分配失败',
apiMethod: orderWaveBatchAllocateStorage,
payloadKey: 'wave_ids',
idField: 'wave_id',
useProgress: true,
progressApiMethod: orderWaveBatchAllocateStorageTaskProgress
},
batchRemoveExceptionOrders: {
action: 'batchRemoveExceptionOrders',
title: '批量移除异常订单',
confirmText: '确定移除选中的 {count} 个波次中的异常订单吗?',
confirmType: 'error',
confirmButtonText: '确认移除',
successText: '异常订单移除任务已提交',
failText: '移除异常订单失败',
apiMethod: orderWaveBatchRemoveExceptionOrders,
payloadKey: 'wave_ids',
idField: 'wave_id',
useProgress: true,
progressApiMethod: orderWaveBatchRemoveExceptionOrdersTaskProgress
}
}

View File

@ -40,32 +40,14 @@
<div :key="activeTabName" class="tab-content-inner">
<div class="toolbar">
<div class="toolbar-left">
<!-- 默认刷新按钮 -->
<el-button
v-if="currentTabConfig?.toolbar?.showRefresh !== false"
type="primary" size="small" @click="handleRefresh"
>
<el-icon><Refresh /></el-icon>
刷新
</el-button>
<!-- 自定义工具栏按钮 -->
<el-button
v-for="btn in currentToolbarButtons"
:key="btn.key"
:type="btn.type || ''"
size="small"
:disabled="btn.disabled"
@click="handleToolbarAction(btn.key)"
>
{{ btn.label }}
</el-button>
<!-- 默认导出按钮 -->
<el-button
v-if="currentTabConfig?.toolbar?.showExport !== false"
size="small" @click="handleExport"
>
导出
</el-button>
<order-toolbar-button-group
:buttons="currentToolbarButtons"
:resolve-disabled="resolveButtonDisabled"
:resolve-loading="resolveButtonLoading"
:resolve-label="resolveButtonLabel"
:layout-key="toolbarLayoutKey"
@action="handleToolbarButtonClick"
/>
</div>
</div>
@ -79,7 +61,7 @@
:column-config-schema-version="1"
:table-id="`wave-order2-table-${activeTabName}`"
:data="mockList"
:row-key="'id'"
:row-key="'wave_no'"
:columns="currentColumns"
table-size="small"
:pagination="pagination"
@ -152,6 +134,21 @@
</div>
</div>
</div>
<!-- ===== 功能按钮表单(pages/ 目录下的组件) ===== -->
<FetchGroupOrderForm
v-model:visible="fetchGroupOrderFormVisible"
@success="handleFormSuccess"
/>
<BatchOperationForm
v-model:visible="batchOperationFormVisible"
:config="batchOperationConfig"
:selected-ids="batchOperationSelectedIds"
:selected-rows="selectedRows"
:extracted-payload="batchOperationExtractedPayload"
@success="handleFormSuccess"
/>
</div>
</template>
@ -164,13 +161,24 @@ import ScanBox from '@/components/ScanBox/index.vue'
import UpperTable from '@/components/UpperTable/index.vue'
import TabArea from './components/TabArea.vue'
import ColumnCellRenderer from './components/ColumnCellRenderer.vue'
import OrderToolbarButtonGroup from '@/views/order/orderManagement/component/OrderToolbarButtonGroup.vue'
import type { ToolbarButtonConfig } from '@/views/order/orderManagement/config/order-common-config'
import FetchGroupOrderForm from './pages/FetchGroupOrderForm.vue'
import BatchOperationForm from './pages/BatchOperationForm.vue'
import {
WAVEORDER2_PAGE_CONFIG,
waveOrder2Tabs,
waveOrder2TabPages,
resolveTabConfig
resolveTabConfig,
getTabToolbarButtons,
BATCH_OPERATION_CONFIGS
} from './config/waveorder-config'
import type {
TabPageConfig,
DetailTabConfig,
WaveOrder2ToolbarButtonConfig,
BatchOperationConfig
} from './config/waveorder-config'
import type { TabPageConfig, DetailTabConfig } from './config/waveorder-config'
defineOptions({ name: 'WaveOrder2' })
@ -258,11 +266,200 @@ const currentDetailTabApiMethod = computed(() => {
return undefined
})
/** 当前标签页的自定义工具栏按钮 */
const currentToolbarButtons = computed(() => {
return currentTabConfig.value?.toolbar?.left ?? []
// ============================================================
// 工具栏按钮系统(参照 orderManagement 设计)
// ============================================================
/** 当前标签页的工具栏按钮列表(从 WAVEORDER2_TOOLBAR_BUTTONS 获取) */
const currentToolbarButtons = computed<ToolbarButtonConfig[]>(() => {
const btns = getTabToolbarButtons(activeTabName.value)
return btns.map((btn: WaveOrder2ToolbarButtonConfig) => ({
key: btn.key,
label: btn.label,
size: btn.size,
type: btn.type,
plain: btn.plain,
loadingKey: btn.loadingKey,
disabledKey: btn.disabledKey,
action: btn.action,
dynamicLabelKey: btn.dynamicLabelKey,
buttonType: btn.buttonType,
dropdownOptions: btn.dropdownOptions
}))
})
/** 按钮禁用状态映射 */
const buttonDisabledMap = computed<Record<string, boolean>>(() => ({
noSelection: selectedRows.value.length === 0
}))
/** 按钮加载状态映射 */
const buttonLoadingMap = computed<Record<string, boolean>>(() => ({
loading: loading.value,
exportLoading: false,
batchAutoGroupingLoading: batchOpLoading.value && currentBatchOpAction.value === 'batchAutoGrouping',
batchFinishAutoGroupingLoading: batchOpLoading.value && currentBatchOpAction.value === 'batchFinishAutoGrouping',
batchCancelLoading: batchOpLoading.value && currentBatchOpAction.value === 'batchCancel',
batchAllocateExpressLoading: batchOpLoading.value && currentBatchOpAction.value === 'batchAllocateExpress',
batchAllocateStorageLoading: batchOpLoading.value && currentBatchOpAction.value === 'batchAllocateStorage',
batchRemoveExceptionOrdersLoading: batchOpLoading.value && currentBatchOpAction.value === 'batchRemoveExceptionOrders'
}))
/** 按钮动态标签映射 */
const buttonLabelMap = computed<Record<string, string>>(() => ({
detailToggleLabel: detailVisible.value ? '隐藏详情' : '显示详情'
}))
/** 工具栏布局 key(变化时触发 OrderToolbarButtonGroup 重排) */
const toolbarLayoutKey = computed(() =>
JSON.stringify({
loading: buttonLoadingMap.value,
disabled: buttonDisabledMap.value,
labels: buttonLabelMap.value
})
)
function resolveButtonLoading(loadingKey?: string) {
if (!loadingKey) return false
return Boolean(buttonLoadingMap.value[loadingKey])
}
function resolveButtonDisabled(disabledKey?: string) {
if (!disabledKey) return false
return Boolean(buttonDisabledMap.value[disabledKey])
}
function resolveButtonLabel(defaultLabel: string, dynamicLabelKey?: string) {
if (!dynamicLabelKey) return defaultLabel
return buttonLabelMap.value[dynamicLabelKey] || defaultLabel
}
// ============================================================
// 工具栏动作分发
// ============================================================
/** 基础工具栏动作映射 */
const toolbarActionMap: Record<string, () => void> = {
loadData: () => { void loadMockData() },
openColumnConfigPanel: () => { upperTableRef.value?.openColumnConfig?.() },
toggleDetailVisible: () => { detailVisible.value = !detailVisible.value },
handleExportWaybill: () => { console.log('[WaveOrder2] 导出(不含明细)', activeTabName.value) },
handleExportItem: () => { console.log('[WaveOrder2] 导出(含明细)', activeTabName.value) }
}
/** 统一工具栏按钮点击处理 */
function handleToolbarButtonClick(action: ToolbarButtonConfig['action']) {
const handler = toolbarActionMap[action]
if (handler) {
handler()
return
}
// 功能按钮:打开对应表单
handleFunctionButtonAction(action)
}
// ============================================================
// 功能按钮表单状态
// ============================================================
/** 团购单抓取表单 */
const fetchGroupOrderFormVisible = ref(false)
/** 批量操作表单 */
const batchOperationFormVisible = ref(false)
const batchOperationConfig = ref<BatchOperationConfig | null>(null)
const batchOperationSelectedIds = ref<string[] | number[]>([])
/** 多字段提取结果(idField 为数组时使用),直接作为请求体 */
const batchOperationExtractedPayload = ref<Record<string, any[]> | null>(null)
const batchOpLoading = ref(false)
const currentBatchOpAction = ref('')
/** 功能按钮 action → 表单打开逻辑 */
function handleFunctionButtonAction(action: string) {
switch (action) {
case 'openFetchGroupOrderForm':
openFetchGroupOrderForm()
break
case 'openBatchAutoGroupingForm':
case 'openBatchFinishAutoGroupingForm':
case 'openBatchCancelForm':
case 'openBatchAllocateExpressForm':
case 'openBatchAllocateStorageForm':
case 'openBatchRemoveExceptionOrdersForm':
openBatchOperationForm(action)
break
default:
console.warn('[WaveOrder2] 未处理的工具栏动作:', action)
}
}
function openFetchGroupOrderForm() {
fetchGroupOrderFormVisible.value = true
}
function openBatchOperationForm(action: string) {
if (!selectedRows.value.length) {
ElMessage.warning('请先选择波次')
return
}
// 根据 action 推导对应的批量操作 key
const opKey = action.replace('open', '').replace('Form', '')
// openBatchAutoGroupingForm → BatchAutoGrouping → batchAutoGrouping
const configKey = opKey.charAt(0).toLowerCase() + opKey.slice(1)
const cfg = BATCH_OPERATION_CONFIGS[configKey]
if (!cfg) {
console.warn('[WaveOrder2] 未找到批量操作配置:', configKey)
return
}
currentBatchOpAction.value = cfg.action
batchOperationConfig.value = { ...cfg }
const idField = cfg.idField ?? 'wave_id'
if (Array.isArray(idField)) {
// 多字段模式:提取所有字段,组装为 { field1: [...], field2: [...] }
const payload: Record<string, any[]> = {}
for (const field of idField) {
payload[field] = []
}
for (const row of selectedRows.value) {
for (const field of idField) {
const val = (row as any)[field]
payload[field]!.push(val !== undefined && val !== null ? val : null)
}
}
batchOperationExtractedPayload.value = payload
// selectedIds 用第一个字段的值供 UI 展示
const firstField = idField[0]
batchOperationSelectedIds.value = firstField ? (payload[firstField]?.filter((v: any) => v !== null) ?? []) : []
} else {
// 单字段模式(支持逗号分隔 fallback)
batchOperationExtractedPayload.value = null
const idFields = (idField as string).split(',').map((f: string) => f.trim())
batchOperationSelectedIds.value = selectedRows.value
.map((r: any) => {
for (const field of idFields) {
const val = r[field]
if (val !== undefined && val !== null && val !== '') return val
}
return null
})
.filter((v: any) => v !== null)
}
batchOperationFormVisible.value = true
}
/** 表单操作成功后刷新列表 */
function handleFormSuccess() {
selectedRows.value = []
pagination.currentPage = 1
loadMockData()
}
/** 切换标签页时重置状态并加载新数据 */
const handleTabChange = (tabName: string) => {
if (activeTabName.value === tabName) return
@ -392,29 +589,6 @@ const handlePageSizeChange = (size: number) => {
loadMockData()
}
// ===== 工具栏 =====
const handleRefresh = () => {
pagination.currentPage = 1
loadMockData()
}
const handleExport = () => {
console.log('[WaveOrder2] 导出数据', activeTabName.value)
}
/** 自定义工具栏按钮点击 */
const handleToolbarAction = (key: string) => {
console.log('[WaveOrder2] 工具栏操作:', key, activeTabName.value)
// 各标签页可在此扩展处理逻辑
switch (key) {
case 'batchAssign': // 示例:批量分配
console.log('批量分配选中行:', selectedRows.value)
break
default:
break
}
}
// ===== UpperTable =====
const upperTableRef = ref<any>(null)
const selectedRows = ref<Record<string, any>[]>([])

View File

@ -0,0 +1,246 @@
<!--
BatchOperationForm — 批量操作表单(确认弹窗)
支持的批量操作:
- batchAutoGrouping 批量改为自动加团
- batchFinishAutoGrouping 批量结束自动加团
- batchCancel 批量取消波次
- batchAllocateExpress 快速分配快递号
- batchAllocateStorage 批量分配储位
- batchRemoveExceptionOrders 批量移除异常订单
使用方式:index.vue 中通过 v-model:visible 控制显示,
:config 传入对应的 BatchOperationConfig。
-->
<template>
<el-dialog
:model-value="visible"
:title="config?.title ?? '确认操作'"
width="480px"
align-center
destroy-on-close
:close-on-click-modal="false"
@closed="handleClosed"
>
<div class="batch-op-body">
<el-alert
:type="config?.confirmType ?? 'warning'"
:closable="false"
show-icon
:title="confirmMessage"
/>
<div class="batch-op-info">
<span>已选波次数:<strong>{{ selectedIds.length }}</strong></span>
<div v-if="selectedIds.length <= 10" class="batch-op-ids">
{{ selectedIds.join('、') }}
</div>
</div>
<!-- 进度显示 -->
<template v-if="showProgress">
<el-divider />
<div class="batch-op-progress">
<el-progress
:percentage="progressPercent"
:status="progressStatus"
:stroke-width="16"
/>
<p class="batch-op-progress-text">
{{ progressLabel }}
<template v-if="resultCount > 0">
(已完成 {{ resultCount }} 个波次)
</template>
</p>
</div>
</template>
</div>
<template #footer>
<el-button size="small" @click="handleClosed">取消</el-button>
<el-button
size="small"
:type="config?.confirmType === 'error' ? 'danger' : 'primary'"
:loading="submitting"
:disabled="showProgress && progressStatus === 'success'"
@click="handleSubmit"
>
{{ config?.confirmButtonText ?? '确认' }}
</el-button>
</template>
</el-dialog>
</template>
<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import type { BatchOperationConfig } from '../config/waveorder-config'
const props = defineProps<{
visible: boolean
config: BatchOperationConfig | null
selectedIds: string[] | number[]
/** 完整的选中行数据,供 payloadBuilder 使用 */
selectedRows?: Record<string, any>[]
/** 多字段提取结果(idField 配置为数组时),直接作为请求体 */
extractedPayload?: Record<string, any[]> | null
}>()
const emit = defineEmits<{
(e: 'update:visible', v: boolean): void
(e: 'success'): void
}>()
const submitting = ref(false)
const showProgress = ref(false)
const progressPercent = ref(0)
const progressStatus = ref<'success' | 'exception' | 'warning' | ''>('')
const progressLabel = ref('')
const resultCount = ref(0)
let pollingTimer: ReturnType<typeof setInterval> | null = null
const confirmMessage = computed(() => {
if (!props.config) return ''
return props.config.confirmText.replace('{count}', String(props.selectedIds.length))
})
function handleClosed() {
stopPolling()
emit('update:visible', false)
}
function stopPolling() {
if (pollingTimer) {
clearInterval(pollingTimer)
pollingTimer = null
}
}
/** 重置内部状态 */
function reset() {
submitting.value = false
showProgress.value = false
progressPercent.value = 0
progressStatus.value = ''
progressLabel.value = ''
resultCount.value = 0
stopPolling()
}
watch(
() => props.visible,
(v) => {
if (!v) reset()
}
)
/** 开始轮询任务进度 */
function startProgressPolling(taskId: string | number) {
if (!props.config?.progressApiMethod) return
showProgress.value = true
progressStatus.value = ''
progressLabel.value = '任务处理中…'
pollingTimer = setInterval(async () => {
try {
const res = await props.config!.progressApiMethod!({ task_id: taskId })
const data = res?.data ?? res
const status = data?.status ?? data?.task_status ?? ''
const percent = Number(data?.progress ?? data?.progress_percent ?? 0)
progressPercent.value = Math.min(100, Math.round(percent))
if (status === 'success' || status === 'completed' || status === 'fin' || percent >= 100) {
progressStatus.value = 'success'
progressLabel.value = '任务已完成'
resultCount.value = Number(data?.success_count ?? data?.total ?? 0)
stopPolling()
} else if (status === 'failed' || status === 'error') {
progressStatus.value = 'exception'
progressLabel.value = data?.message ?? '任务执行失败'
stopPolling()
} else {
progressLabel.value = data?.message ?? `处理中… ${percent}%`
}
} catch {
// 忽略轮询错误
}
}, 2000)
}
async function handleSubmit() {
if (submitting.value) return
if (!props.config) return
if (!props.selectedIds.length) {
ElMessage.warning('没有可操作的波次')
return
}
const cfg = props.config
submitting.value = true
try {
// 1. payloadBuilder 最高优先:完全自定义
// 2. extractedPayload 次之:多字段自动提取结果
// 3. 兜底:payloadKey + selectedIds 单字段拼接
const payload = cfg.payloadBuilder
? cfg.payloadBuilder(props.selectedRows ?? [])
: props.extractedPayload
? { ...props.extractedPayload }
: { [cfg.payloadKey ?? 'ids']: props.selectedIds }
const res = await cfg.apiMethod(payload)
const ok = res && (res.code === 1 || res.code === 200 || res.flag === 'success')
if (!ok) {
ElMessage.error(res?.message || cfg.failText)
return
}
// 如果配置了进度轮询
const taskId = res?.data?.task_id
if (cfg.useProgress && taskId) {
ElMessage.success(cfg.successText)
startProgressPolling(taskId)
} else {
const count = Number(res?.data?.updated_count ?? props.selectedIds.length) || 0
ElMessage.success(`${cfg.successText}(${count} 个波次)`)
emit('success')
handleClosed()
}
} catch {
ElMessage.error(cfg.failText)
} finally {
submitting.value = false
if (!showProgress.value) {
submitting.value = false
}
}
}
</script>
<style scoped lang="scss">
.batch-op-body {
padding: 4px 0;
}
.batch-op-info {
margin-top: 12px;
font-size: 13px;
color: #606266;
line-height: 1.6;
}
.batch-op-ids {
margin-top: 6px;
font-size: 12px;
color: #909399;
word-break: break-all;
}
.batch-op-progress {
.batch-op-progress-text {
margin-top: 8px;
font-size: 12px;
color: #909399;
text-align: center;
}
}
</style>

View File

@ -0,0 +1,490 @@
<!--
FetchGroupOrderForm — 抓取团购单表单
对应 waveOrder 中 GroupWaveBatchListPanel 的团购单抓取对话框。
提供货主筛选、最小同组订单数、店铺名称、包含SKU、区分快递等条件,
查询可抓取的团购单结构并提交抓取。
-->
<template>
<el-dialog
:model-value="visible"
title="抓取团购单"
width="1280px"
align-center
destroy-on-close
:close-on-click-modal="false"
@closed="handleClosed"
>
<div class="fetch-group-order-body">
<!-- 筛选区域 -->
<el-form :inline="true" size="small" class="fetch-filters">
<el-form-item label="货主">
<el-select
v-model="filters.storeId"
placeholder="全部"
clearable
filterable
style="width: 180px"
@change="handleFilterChange"
>
<el-option
v-for="store in storeOptions"
:key="String(store.value)"
:label="store.label"
:value="store.value"
/>
</el-select>
</el-form-item>
<el-form-item label="最小同组订单数">
<el-input-number
v-model="filters.sameOrderQuantity"
:min="1"
:controls="false"
style="width: 150px"
@change="handleFilterChange"
/>
</el-form-item>
<el-form-item label="店铺名称">
<el-input
v-model="filters.shopName"
clearable
placeholder="模糊匹配店铺名称"
style="width: 180px"
@keyup.enter="fetchList"
/>
</el-form-item>
<el-form-item label="包含 SKU">
<el-input
v-model="filters.includeSku"
clearable
placeholder="仅保留包含该 SKU 的分组"
style="width: 180px"
@keyup.enter="fetchList"
/>
</el-form-item>
<el-form-item>
<el-switch
v-model="filters.distinguishExpress"
active-text="区分快递"
inactive-text="不区分快递"
@change="handleFilterChange"
/>
</el-form-item>
<el-form-item>
<el-button type="primary" :loading="listLoading" @click="fetchList">查询</el-button>
<el-button @click="resetFilters">重置</el-button>
</el-form-item>
</el-form>
<!-- 工具栏 -->
<div class="fetch-toolbar">
<div class="fetch-toolbar__left">
<span>已选 {{ selectionRows.length }} 个结构</span>
</div>
</div>
<!-- 列表 -->
<el-table
ref="tableRef"
:data="list"
v-loading="listLoading"
border
size="small"
row-key="item_detail_machine"
max-height="400"
@selection-change="handleSelectionChange"
>
<el-table-column type="selection" width="48" reserve-selection />
<el-table-column prop="item_detail" label="商品结构" min-width="260" show-overflow-tooltip />
<el-table-column prop="logistics_name" label="快递" min-width="130" show-overflow-tooltip />
<el-table-column prop="group_count" label="同组订单数" min-width="100" align="right" />
<el-table-column prop="items_total" label="商品总数" min-width="100" align="right" />
<el-table-column label="货主" min-width="110">
<template #default="{ row }">
{{ row.store_name || row.store_short_name || '—' }}
</template>
</el-table-column>
<el-table-column label="首单时间" min-width="168">
<template #default="{ row }">
{{ formatTime(row.first_order_time) }}
</template>
</el-table-column>
<el-table-column label="末单时间" min-width="168">
<template #default="{ row }">
{{ formatTime(row.last_order_time) }}
</template>
</el-table-column>
<template #empty>
<div class="empty-tip">暂无可抓取的团购单结构</div>
</template>
</el-table>
<!-- 分页 -->
<div class="fetch-pagination">
<el-pagination
v-model:current-page="pagination.currentPage"
v-model:page-size="pagination.pageSize"
:page-sizes="[10, 20, 50, 100]"
:total="pagination.total"
layout="total, sizes, prev, pager, next, jumper"
background
size="small"
@size-change="handlePageSizeChange"
@current-change="handlePageChange"
/>
</div>
</div>
<template #footer>
<el-button size="small" @click="handleClosed">取消</el-button>
<el-button size="small" type="primary" :loading="submitting" @click="handleSubmit">
抓取选中结构
</el-button>
</template>
</el-dialog>
</template>
<script setup lang="ts">
import { reactive, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import {
orderWaveGroupOrderFetchList,
orderWaveGroupFetch
} from '@/api/order.wave/orderwave'
import type {
WaveGroupOrderFetchListResponse,
WaveFetchResponse
} from '@/api/order.wave/orderwave'
import { loadStores } from '@/api/index/index'
const props = defineProps<{
visible: boolean
/** 查询接口(可选覆盖,默认 orderWaveGroupOrderFetchList) */
fetchListApi?: (...args: any[]) => Promise<any>
/** 提交抓取接口(可选覆盖,默认 orderWaveGroupFetch) */
submitApi?: (...args: any[]) => Promise<any>
/** 货主选项(可选覆盖,默认自动加载) */
storeOptions?: Array<{ label: string; value: any }>
}>()
const emit = defineEmits<{
(e: 'update:visible', v: boolean): void
(e: 'success'): void
}>()
const filters = reactive({
distinguishExpress: true,
storeId: undefined as number | string | undefined,
sameOrderQuantity: undefined as number | undefined,
shopName: '',
includeSku: ''
})
const storeOptions = ref<Array<{ label: string; value: any }>>([])
const list = ref<any[]>([])
const listLoading = ref(false)
const submitting = ref(false)
const selectionRows = ref<any[]>([])
const pagination = reactive({
currentPage: 1,
pageSize: 20,
total: 0
})
/** 判断响应码是否成功 */
const okCode = (code: unknown) => code === 1 || code === 200 || code === 0
/** 格式化时间戳 */
function formatTime(value: any): string {
if (!value) return '—'
try {
const d = new Date(value)
if (isNaN(d.getTime())) return String(value)
const pad = (n: number) => String(n).padStart(2, '0')
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
} catch {
return String(value)
}
}
// ============================================================
// 货主选项加载(参照 GroupWaveBatchListPanel.loadGroupOrderStoreOptions)
// ============================================================
async function loadStoreOptions() {
if (props.storeOptions?.length) {
storeOptions.value = props.storeOptions
return
}
if (storeOptions.value.length > 0) return
try {
const res: any = await loadStores({ type: 'order' })
const stores = Array.isArray(res?.stores) ? res.stores : []
storeOptions.value = stores.map((item: any) => ({
label: item.label || item.name || String(item.value || item.id),
value: item.value ?? item.id
}))
} catch (error) {
console.error('[FetchGroupOrderForm] 加载货主列表失败:', error)
storeOptions.value = []
}
}
// 监听外部传入的 storeOptions
watch(
() => props.storeOptions,
(val) => {
if (val && val.length) storeOptions.value = val
}
)
// ============================================================
// 构建查询参数(对齐 waveOrder buildStructureFetchListPayload)
// ============================================================
function buildListPayload(): Record<string, any> {
const payload: Record<string, any> = {
pagination: {
page: pagination.currentPage,
pageSize: pagination.pageSize
},
distinguish_express: filters.distinguishExpress
}
if (filters.storeId !== undefined && filters.storeId !== null && filters.storeId !== '') {
payload.store_id = Number(filters.storeId)
}
if (filters.sameOrderQuantity !== undefined && filters.sameOrderQuantity !== null) {
payload.same_order_quantity = Number(filters.sameOrderQuantity)
}
if (filters.shopName.trim()) {
payload.shop_name = filters.shopName.trim()
}
if (filters.includeSku.trim()) {
payload.include_sku = filters.includeSku.trim()
}
return payload
}
// ============================================================
// 查询列表(对齐 waveOrder fetchGroupOrderList)
// ============================================================
async function fetchList() {
listLoading.value = true
try {
const fetchApi = props.fetchListApi ?? orderWaveGroupOrderFetchList
const res = await fetchApi(buildListPayload()) as
WaveGroupOrderFetchListResponse & { code?: number; message?: string; data?: Partial<WaveGroupOrderFetchListResponse> }
if (!res || !okCode(res.code)) {
throw new Error(res?.message || '获取可抓取团购单列表失败')
}
const responseList = Array.isArray(res.list)
? res.list
: Array.isArray(res.data?.list)
? res.data.list
: []
const responsePagination = res.pagination || res.data?.pagination || {}
list.value = responseList
pagination.currentPage = responsePagination.page || pagination.currentPage
pagination.pageSize = responsePagination.pageSize || pagination.pageSize
pagination.total = responsePagination.total || 0
} catch (error: any) {
console.error('[FetchGroupOrderForm] 获取列表失败:', error)
list.value = []
pagination.total = 0
ElMessage.error(error?.message || '获取可抓取团购单列表失败')
} finally {
listLoading.value = false
}
}
// ============================================================
// 筛选 & 分页
// ============================================================
function handleClosed() {
emit('update:visible', false)
}
function handleFilterChange() {
pagination.currentPage = 1
}
function resetFilters() {
filters.distinguishExpress = true
filters.storeId = undefined
filters.sameOrderQuantity = undefined
filters.shopName = ''
filters.includeSku = ''
pagination.currentPage = 1
list.value = []
pagination.total = 0
selectionRows.value = []
}
function handleSelectionChange(rows: any[]) {
selectionRows.value = rows
}
function handlePageChange(page: number) {
pagination.currentPage = page
fetchList()
}
function handlePageSizeChange(size: number) {
pagination.pageSize = size
pagination.currentPage = 1
fetchList()
}
// ============================================================
// 提交抓取(对齐 waveOrder submitGroupOrderDialog)
// ============================================================
/**
* 解析抓取接口返回的 fetch_state,给出对应提示
* (对齐 GroupWaveBatchListPanel.applyWaveStrategyFetchUiResult)
*/
function applyFetchResult(
payload: WaveFetchResponse & { code?: number; message?: string; tip?: string },
successHint?: string
) {
const fs = (payload as any).fetch_state
// 验证错误
const validationErrors = (payload as any).validation_errors
if (Array.isArray(validationErrors) && validationErrors.length) {
const detail = validationErrors
.map((e: any) => [e?.field, e?.message].filter(Boolean).join(': ') || '')
.filter(Boolean)
.join(';')
ElMessage.warning(detail || payload?.message || '入参校验未通过')
return false
}
// fetch_state === 2 → 失败
if (fs === 2) {
ElMessage.warning((payload as any).tip || payload?.message || '抓取任务创建失败')
return false
}
// fetch_state === 3 → 已有进行中任务
if (fs === 3) {
const taskNo = String((payload as any).task_no ?? (payload as any).existing_task_no ?? '')
const taskId = String(payload.task_id ?? (payload as any).existing_task_id ?? '')
const tip = (payload as any).tip || payload?.message || '存在未完成的抓取任务'
const suffix = [taskNo ? `任务编号:${taskNo}` : '', taskId ? `任务ID:${taskId}` : ''].filter(Boolean).join(',')
ElMessage.success(suffix ? `${tip}(${suffix})` : tip)
emit('success')
handleClosed()
return true
}
// fetch_state === 1 或 undefined → 成功创建
if (fs === 1 || fs === undefined || fs === null) {
const taskId = String(payload?.task_id ?? '')
const taskNo = String((payload as any).task_no ?? '')
const planSummary = String((payload as any).plan_summary ?? '')
const hint = planSummary || payload?.message || successHint || '抓取任务已创建'
const suffix = [taskNo ? `任务编号:${taskNo}` : '', taskId ? `任务ID:${taskId}` : ''].filter(Boolean).join(',')
ElMessage.success(suffix ? `${hint}(${suffix})` : hint)
emit('success')
handleClosed()
return true
}
ElMessage.warning(payload?.message || `未知抓取状态(fetch_state=${String(fs)})`)
return false
}
async function handleSubmit() {
if (!selectionRows.value.length) {
ElMessage.warning('请先勾选要抓取的结构')
return
}
submitting.value = true
try {
const submitApi = props.submitApi ?? orderWaveGroupFetch
const structureList = selectionRows.value.map((row: any) => ({
item_detail_machine: String(row?.item_detail_machine || '')
}))
const res = await submitApi({ structure_list: structureList }) as
WaveFetchResponse & { code?: number; message?: string; tip?: string }
if (!res || !okCode(res.code)) {
throw new Error(res?.message || '抓取团购单失败')
}
// 处理 fetch_state 逻辑
applyFetchResult(res, '抓取任务已创建')
} catch (error: any) {
console.error('[FetchGroupOrderForm] 提交抓取失败:', error)
ElMessage.error(error?.message || '抓取团购单失败')
} finally {
submitting.value = false
}
}
// ============================================================
// 打开时自动加载
// ============================================================
watch(
() => props.visible,
(v) => {
if (v) {
filters.distinguishExpress = true
pagination.currentPage = 1
selectionRows.value = []
loadStoreOptions()
fetchList()
}
}
)
</script>
<style scoped lang="scss">
.fetch-group-order-body {
display: flex;
flex-direction: column;
gap: 0;
}
.fetch-filters {
flex-shrink: 0;
padding-bottom: 8px;
border-bottom: 1px solid #ebeef5;
}
.fetch-toolbar {
display: flex;
align-items: center;
justify-content: space-between;
padding: 8px 0;
&__left {
font-size: 13px;
color: #606266;
}
}
.fetch-pagination {
display: flex;
justify-content: flex-end;
padding-top: 8px;
}
.empty-tip {
text-align: center;
font-size: 13px;
color: #909399;
padding: 24px 0;
}
</style>

View File

@ -168,6 +168,7 @@ export const REPORT_SCAN_FIELD_GROUPS = {
time: '统计配置',
owner: '货主信息',
options: '统计选项',
keyword: '关键字搜索',
} as const
type ReportScanFieldGroupKey = keyof typeof REPORT_SCAN_FIELD_GROUPS

View File

@ -910,7 +910,7 @@ import { storeWarehouseList, storeWarehouseUnbind,
storeWarehouseSavePolicyConfig, saveApiConfig, storeWarehouseDeleteQimenConfig,
storeWarehouseAdjustPrintQuantity, storeWarehouseQueryPrintQuantityLogs, listApiConfig,
storeWarehouseOpenAccount, storeWarehouseConfirmSign
} from '@/api/storeWarehouse.store/storeWarehouse'
} from '@/api/storewarehouse.store/storeWarehouse'
import { listInterfaceTypes, getExpressList, getPlatformList, getQimenAppList } from '@/api/index/index'
import ScanBox from '@/components/ScanBox/index.vue'
import UpperTable from '@/components/UpperTable/index.vue'

View File

@ -0,0 +1,463 @@
<template>
<div class="workbench-container" :style="{ height: containerHeight }">
<scan-box
ref="scanBox"
width="250px"
:tree-props="{ children: 'children', label: 'label' }"
:auto-submit="false"
:preset-tree="presetTree"
:available-fields="availableFieldsRef"
@condition-change="handleConditionChange"
@reset="handleConditionReset"
@condition-clear="handleConditionClear"
@submit="handleSubmit"
/>
<div class="main-content">
<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>
</div>
<el-button type="success" size="small" @click="openCreate">新增工作台</el-button>
</div>
<div class="upper-wrapper">
<upper-table
ref="upperTable"
title="工作台列表"
table-id="setting-workbench"
:data="tableData"
:columns="columns"
:table-size="tableSize"
:pagination="pagination"
:show-index="true"
:show-actions="true"
:loading="loading"
:query-time="queryTime"
row-key="id"
@page-change="handlePageChange"
@page-size-change="handlePageSizeChange"
@refresh="loadList"
>
<template #column-status="{ row }">
<el-tag :type="formatWorkbenchStatus(row.status).type" size="small">
{{ formatWorkbenchStatus(row.status).text }}
</el-tag>
</template>
<template #column-created_at="{ row }">
<el-text size="small">{{ formatTime(row.created_at) }}</el-text>
</template>
<template #column-updated_at="{ row }">
<el-text size="small">{{ formatTime(row.updated_at) }}</el-text>
</template>
<template #column-actions="{ row }">
<el-button link type="primary" size="small" @click.stop="openDetail(row)">详情</el-button>
<el-button link type="primary" size="small" @click.stop="openEdit(row)">编辑</el-button>
<el-button link type="danger" size="small" @click.stop="handleDelete(row)">删除</el-button>
</template>
<template #empty>
<div class="empty-tip">暂无工作台数据,可调整左侧筛选条件或点击新增</div>
</template>
</upper-table>
</div>
</div>
<!-- 新增 / 编辑 -->
<el-dialog
v-model="dialogVisible"
:title="dialogMode === 'create' ? '新增工作台' : '编辑工作台'"
width="520px"
align-center
@close="resetForm"
>
<el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
<el-form-item label="名称" prop="name">
<el-input v-model="formData.name" placeholder="请输入工作台名称" maxlength="100" show-word-limit />
</el-form-item>
<el-form-item label="条码" prop="barcode">
<el-input
v-model="formData.barcode"
placeholder="仓库内唯一,可选"
maxlength="64"
show-word-limit
@blur="handleBarcodeBlur"
/>
</el-form-item>
<el-form-item v-if="barcodeCheckHint">
<el-text :type="barcodeCheckHint.type" size="small">{{ barcodeCheckHint.text }}</el-text>
</el-form-item>
<el-form-item label="状态" prop="status">
<el-radio-group v-model="formData.status">
<el-radio :label="1">启用</el-radio>
<el-radio :label="0">禁用</el-radio>
</el-radio-group>
</el-form-item>
<el-form-item label="备注">
<el-input v-model="formData.remark" type="textarea" :rows="3" placeholder="可选" maxlength="200" show-word-limit />
</el-form-item>
</el-form>
<template #footer>
<el-button @click="dialogVisible = false">取消</el-button>
<el-button type="primary" :loading="saving" @click="submitForm">保存</el-button>
</template>
</el-dialog>
<!-- 详情 -->
<el-drawer v-model="detailVisible" title="工作台详情" size="480px" @close="detailData = null">
<div v-loading="detailLoading" class="detail-body">
<template v-if="detailData">
<el-descriptions :column="1" border size="small">
<el-descriptions-item label="ID">{{ detailData.id }}</el-descriptions-item>
<el-descriptions-item label="仓库ID">{{ detailData.warehouse_id || '--' }}</el-descriptions-item>
<el-descriptions-item label="名称">{{ detailData.name || '--' }}</el-descriptions-item>
<el-descriptions-item label="条码">{{ detailData.barcode || '--' }}</el-descriptions-item>
<el-descriptions-item label="状态">
<el-tag :type="formatWorkbenchStatus(detailData.status).type" size="small">
{{ formatWorkbenchStatus(detailData.status).text }}
</el-tag>
</el-descriptions-item>
<el-descriptions-item label="备注">{{ detailData.remark || '--' }}</el-descriptions-item>
<el-descriptions-item label="创建时间">{{ formatTime(detailData.created_at) }}</el-descriptions-item>
<el-descriptions-item label="更新时间">{{ formatTime(detailData.updated_at) }}</el-descriptions-item>
</el-descriptions>
</template>
<el-empty v-else-if="!detailLoading" description="暂无详情" />
</div>
</el-drawer>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import ScanBox from '@/components/ScanBox/index.vue'
import UpperTable from '@/components/UpperTable/index.vue'
import {
list as workbenchList,
detail as workbenchDetail,
create as workbenchCreate,
update as workbenchUpdate,
del as workbenchDelete,
checkBarcode as workbenchCheckBarcode
} from '@/api/workbench/workbench'
import { useSettingsStore } from '@/stores/modules/settings'
import {
buildWorkbenchListPayload,
formatWorkbenchStatus,
formatTime,
normalizeWorkbenchScanConditionToWhere,
workbenchColumns,
workbenchScanFields,
type WorkbenchDetail,
type WorkbenchRecord
} from './workbench-config'
const settingsStore = useSettingsStore()
const scanBox = ref<any>(null)
const upperTable = ref<any>(null)
const presetTree = ref<any[]>([])
const availableFieldsRef = reactive(JSON.parse(JSON.stringify(workbenchScanFields)))
const shortcutExpanded = computed(() => settingsStore.shortcutExpanded)
const containerHeight = computed(() =>
shortcutExpanded.value ? 'calc(100vh - 150px)' : 'calc(100vh - 100px)'
)
const columns = workbenchColumns
const loading = ref(false)
const saving = ref(false)
const tableData = ref<WorkbenchRecord[]>([])
const queryTime = ref(0)
const tableSize = ref<'small' | 'default' | 'large'>('small')
const currentConditionRaw = ref<any>(null)
const pagination = reactive({ currentPage: 1, pageSize: 20, total: 0 })
const dialogVisible = ref(false)
const dialogMode = ref<'create' | 'edit'>('create')
const formRef = ref<FormInstance>()
const formData = reactive({
id: undefined as number | undefined,
name: '',
barcode: '',
status: 1,
remark: ''
})
const barcodeCheckHint = ref<{ text: string; type: 'success' | 'warning' | 'danger' | 'info' } | null>(null)
const rules: FormRules = {
name: [{ required: true, message: '请输入工作台名称', trigger: 'blur' }],
status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}
const detailVisible = ref(false)
const detailLoading = ref(false)
const detailData = ref<WorkbenchDetail | null>(null)
const isSuccess = (res: any) => res && [0, 1, 200].includes(res.code)
// ─── 列表 ────────────────────────────────────────────────────────────────────
async function loadList() {
if (loading.value) return
loading.value = true
const start = Date.now()
try {
const where = normalizeWorkbenchScanConditionToWhere(currentConditionRaw.value)
const res: any = await workbenchList(
buildWorkbenchListPayload({
page: pagination.currentPage,
pageSize: pagination.pageSize,
where
})
)
if (!isSuccess(res)) {
ElMessage.error(res?.message || '获取工作台列表失败')
tableData.value = []
pagination.total = 0
return
}
const data = res?.data || res
tableData.value = data.list || []
pagination.total = Number(data.pagination?.total ?? data.total ?? 0)
} catch {
tableData.value = []
pagination.total = 0
ElMessage.error('获取工作台列表失败')
} finally {
queryTime.value = Date.now() - start
loading.value = false
}
}
function handlePageChange(page: number) {
pagination.currentPage = page
loadList()
}
function handlePageSizeChange(size: number) {
pagination.pageSize = size
pagination.currentPage = 1
loadList()
}
// ─── 筛选 ────────────────────────────────────────────────────────────────────
function handleConditionChange(condition: any) {
currentConditionRaw.value = condition
}
function handleConditionReset() {
currentConditionRaw.value = null
pagination.currentPage = 1
loadList()
}
function handleConditionClear() {
currentConditionRaw.value = null
}
function handleSubmit() {
pagination.currentPage = 1
loadList()
}
// ─── 新增 / 编辑 ─────────────────────────────────────────────────────────────
function resetFormData() {
formData.id = undefined
formData.name = ''
formData.barcode = ''
formData.status = 1
formData.remark = ''
barcodeCheckHint.value = null
}
function openCreate() {
dialogMode.value = 'create'
resetFormData()
dialogVisible.value = true
}
function openEdit(row: WorkbenchRecord) {
dialogMode.value = 'edit'
resetFormData()
formData.id = row.id
formData.name = row.name || ''
formData.barcode = row.barcode || ''
formData.status = row.status ?? 1
formData.remark = row.remark || ''
dialogVisible.value = true
}
function resetForm() {
formRef.value?.resetFields()
resetFormData()
}
async function handleBarcodeBlur() {
const code = formData.barcode?.trim()
if (!code) {
barcodeCheckHint.value = null
return
}
try {
const res: any = await workbenchCheckBarcode({
barcode: code,
excludeId: formData.id
})
if (isSuccess(res)) {
const exists = res?.data?.exists
if (exists) {
barcodeCheckHint.value = { text: '该条码已存在', type: 'danger' }
} else {
barcodeCheckHint.value = { text: '条码可用', type: 'success' }
}
}
} catch {
// 静默处理,不阻塞用户
}
}
async function submitForm() {
const valid = await formRef.value?.validate().catch(() => false)
if (!valid) return
saving.value = true
try {
const payload: any = {
name: formData.name,
status: formData.status
}
if (formData.barcode?.trim()) payload.barcode = formData.barcode.trim()
if (formData.remark?.trim()) payload.remark = formData.remark.trim()
let res: any
if (dialogMode.value === 'create') {
res = await workbenchCreate(payload)
} else {
res = await workbenchUpdate({ id: formData.id!, ...payload })
}
if (isSuccess(res)) {
ElMessage.success(dialogMode.value === 'create' ? '新增成功' : '更新成功')
dialogVisible.value = false
loadList()
} else {
ElMessage.error(res?.message || (dialogMode.value === 'create' ? '新增失败' : '更新失败'))
}
} catch {
ElMessage.error(dialogMode.value === 'create' ? '新增失败' : '更新失败')
} finally {
saving.value = false
}
}
// ─── 详情 ────────────────────────────────────────────────────────────────────
async function openDetail(row: WorkbenchRecord) {
if (!row.id) return
detailVisible.value = true
detailLoading.value = true
detailData.value = null
try {
const res: any = await workbenchDetail({ id: row.id })
if (isSuccess(res)) {
detailData.value = res?.data?.data ?? res?.data ?? null
} else {
ElMessage.error(res?.message || '获取详情失败')
}
} catch {
ElMessage.error('获取详情失败')
} finally {
detailLoading.value = false
}
}
// ─── 删除 ────────────────────────────────────────────────────────────────────
async function handleDelete(row: WorkbenchRecord) {
if (!row.id) return
try {
await ElMessageBox.confirm(
`确定要删除工作台「${row.name || row.id}」吗?删除后数据不可恢复。`,
'删除确认',
{ confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
)
} catch {
return
}
try {
const res: any = await workbenchDelete({ id: row.id })
if (isSuccess(res)) {
ElMessage.success('删除成功')
loadList()
} else {
ElMessage.error(res?.message || '删除失败')
}
} catch {
ElMessage.error('删除失败')
}
}
// ─── 初始化 ──────────────────────────────────────────────────────────────────
onMounted(() => {
loadList()
})
</script>
<style lang="scss" scoped>
.workbench-container {
display: flex;
gap: 12px;
padding: 12px;
box-sizing: border-box;
.main-content {
flex: 1;
display: flex;
flex-direction: column;
gap: 10px;
min-width: 0;
}
.toolbar {
display: flex;
justify-content: space-between;
align-items: center;
flex-wrap: wrap;
gap: 8px;
.toolbar-left {
display: flex;
align-items: center;
gap: 8px;
}
}
.upper-wrapper {
flex: 1;
min-height: 0;
}
.detail-body {
padding: 0 4px;
}
.empty-tip {
color: #909399;
font-size: 13px;
padding: 20px 0;
}
}
</style>

View File

@ -0,0 +1,151 @@
export type WorkbenchRecord = {
id?: number
warehouse_id?: number
name?: string
barcode?: string
status?: number
remark?: string
created_at?: string
updated_at?: string
deleted_at?: string | null
}
export type WorkbenchDetail = WorkbenchRecord
export const workbenchColumns = [
{ prop: 'id', label: 'ID', width: '80', sortable: true },
{ prop: 'name', label: '工作台名称', minWidth: '140', showOverflowTooltip: true },
{ prop: 'barcode', label: '条码', minWidth: '120', showOverflowTooltip: true },
{ prop: 'warehouse_id', label: '仓库ID', width: '100' },
{ prop: 'status', label: '状态', width: '80' },
{ prop: 'remark', label: '备注', minWidth: '140', showOverflowTooltip: true },
{ prop: 'created_at', label: '创建时间', minWidth: '160' },
{ prop: 'updated_at', label: '更新时间', minWidth: '160' },
{ prop: 'actions', label: '操作', width: '200', fixed: 'right' }
]
export const workbenchScanFields = [
{
value: 'quickWhere',
label: '关键词',
type: 'text',
placeholder: '名称/条码',
operators: ['contains'],
defaultOperator: 'contains'
},
{
value: 'name',
label: '名称',
type: 'text',
placeholder: '请输入工作台名称',
operators: ['eq', 'contains', 'like'],
defaultOperator: 'contains'
},
{
value: 'barcode',
label: '条码',
type: 'text',
placeholder: '请输入条码',
operators: ['eq', 'contains', 'like'],
defaultOperator: 'contains'
},
{
value: 'status',
label: '状态',
type: 'select',
clearable: true,
options: [
{ label: '启用', value: '1' },
{ label: '禁用', value: '0' }
]
}
]
export function formatWorkbenchStatus(status: unknown): { text: string; type: 'success' | 'info' } {
const v = Number(status ?? 1)
return v === 1 ? { text: '启用', type: 'success' } : { text: '禁用', type: 'info' }
}
function pad(n: number) {
return String(n).padStart(2, '0')
}
export function formatTime(value: unknown): string {
if (!value) return '--'
const d = new Date(value as string)
if (isNaN(d.getTime())) return String(value)
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
}
function getFieldConfig(key: string, fields: typeof workbenchScanFields) {
return fields.find((f) => f.value === key)
}
function mapFieldType(type: string, value: unknown) {
if (typeof value === 'number') return 'number'
return 'text'
}
function processConditionValue(key: string, raw: any, fields: typeof workbenchScanFields) {
if (key === 'quickWhere') {
const val = raw?.value !== undefined ? raw.value : raw
const text = val == null ? '' : String(val).trim()
return text ? text : null
}
const config = getFieldConfig(key, fields)
const fieldType = config?.type || 'text'
if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
const op = raw.operator || (fieldType === 'select' ? 'eq' : 'contains')
const type = raw.type || mapFieldType(fieldType, raw.value)
const value = raw.value
if (fieldType === 'select') {
return { operator: 'eq', value: value != null ? Number(value) : undefined }
}
return { operator: op, type, value }
}
if (fieldType === 'select') {
return raw != null ? { operator: 'eq', value: Number(raw) } : null
}
if (fieldType === 'number' && raw != null) {
return { operator: 'eq', value: Number(raw) }
}
return raw != null ? raw : null
}
export function normalizeWorkbenchScanConditionToWhere(rawCondition: any): Record<string, unknown> {
if (!rawCondition) return {}
const where: Record<string, unknown> = {}
const entries = Array.isArray(rawCondition) ? rawCondition : Object.entries(rawCondition)
for (const [key, raw] of entries) {
const processed = processConditionValue(String(key), raw, workbenchScanFields)
if (processed == null) continue
if (key === 'quickWhere') {
where.name = { operator: 'contains', value: processed }
where.barcode = { operator: 'contains', value: processed }
continue
}
where[key] = processed
}
return where
}
export function buildWorkbenchListPayload(params: {
page: number
pageSize: number
where?: Record<string, unknown>
}) {
return {
pagination: { page: params.page, pageSize: params.pageSize },
where: params.where || {}
}
}

View File

@ -352,7 +352,7 @@ import {
storeWarehouseUnbind,
storeWarehouseRename,
listApiConfig
} from '@/api/storeWarehouse.store/storeWarehouse'
} from '@/api/storewarehouse.store/storeWarehouse'
import { listInterfaceTypes, getQimenAppList } from '@/api/index/index'
import ScanBox from '@/components/ScanBox/index.vue'
import UpperTable from '@/components/UpperTable/index.vue'