WEB/src/views/data/newpackingflow/config/packingflow-config.ts
liufumingren 5c1aeb2a61 1
2026-07-31 09:35:35 +08:00

779 lines
25 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 【打包流水】页面配置 — 基于 template v2 架构
*
* 原 packingflow 页面迁移至 newpackingflow 新结构。
* 仓库选择、运单号搜索等筛选条件统一整合到左侧 ScanBox 面板。
*/
import type { Component } from 'vue'
import DetailPanel from './components/DetailPanel.vue'
import LogPanel from './components/LogPanel.vue'
import { packingList, packingGet } from '@/api/order/packing/index'
// ============================================================
// 〇、全局页面配置
// ============================================================
export const PAGE_CONFIG = {
/** 是否显示顶部多标签栏 */
showTabArea: false,
/** 单页模式:不显示标签栏,仅一个标签页内容 */
singlePage: true,
/** 是否启用详情面板(底部分栏),false 时表格占满全高 */
enableDetailPanel: true
}
// ============================================================
// 〇-A、组件注册表
// ============================================================
export const COMPONENT_REGISTRY: Record<string, Component> = {
DetailPanel,
LogPanel
}
// ============================================================
// 〇-B、SCANBOX_GROUPS — ScanBox 分组名称
// ============================================================
export const SCANBOX_GROUPS = {
basic: '基础信息',
process: '流程状态',
time: '时间范围'
} as const
// ============================================================
// 一、FIELD_DICT — 全局字段预设表(唯一真相来源)
// ============================================================
// 每个字段拥有:
// label — 唯一翻译文本
// scanBox — ScanBox 渲染配置(type/options/group)
// table — 表格列配置(minWidth/fixed/align/sortable)
// slot — 单元格渲染配置(tag/tagResolver/translateField)
// detailLabel — 明细面板中的标签文本(可选,默认用 label)
// filterParamMap — ScanBox 筛选值 → API 传参值映射
export interface FieldDefinition {
key: string
label: string
scanBox: {
type: 'text' | 'select' | 'daterange' | 'number'
group?: string
options?: { label: string; value: any }[]
} | null
table: {
minWidth?: number
width?: number
fixed?: 'left' | 'right' | boolean
align?: 'left' | 'center' | 'right'
sortable?: boolean
showOverflowTooltip?: boolean
copyAction?: 'copy' | 'copyQr'
copyValue?: (row: any) => any
} | null
slot: {
type: 'tag' | 'text' | 'default' | 'operation'
tagType?: string | Record<string, string>
tagResolver?: string
translateField?: string
format?: 'datetime'
} | null
detailLabel?: string
filterParamMap?: Record<string, string>
}
// ============================================================
// VALUE_MAPS — 值翻译映射(select options 和 tag 翻译共用)
// ============================================================
export const VALUE_MAPS: Record<string, Record<string, string>> = {
status: {
'0': '待处理', '1': '打包中', '2': '已完成', '3': '异常',
'待处理': '待处理', '打包中': '打包中', '已完成': '已完成', '异常': '异常'
},
pack_mode: {
'1': '散单', '2': '团购',
'散单': '散单', '团购': '团购'
}
}
/** 从 VALUE_MAPS 衍生 options(优先取中文值作为 option value) */
export function getOptions(field: string): { label: string; value: string }[] {
const map = VALUE_MAPS[field]
if (!map) return []
const seen = new Set<string>()
const opts: { label: string; value: string }[] = []
const chineseKeys: [string, string][] = []
const otherKeys: [string, string][] = []
for (const [v, l] of Object.entries(map)) {
if (/^[\u4e00-\u9fa5]/.test(v)) {
chineseKeys.push([v, l])
} else {
otherKeys.push([v, l])
}
}
for (const [v, l] of [...chineseKeys, ...otherKeys]) {
if (!seen.has(l)) {
seen.add(l)
opts.push({ label: l, value: v })
}
}
return opts
}
/** 翻译 value → label */
export function translate(field: string, value: any): string {
const map = VALUE_MAPS[field]
if (!map) return String(value ?? '—')
return map[String(value)] ?? String(value ?? '—')
}
/** 格式化时间戳为 YYYY-MM-DD HH:mm:ss */
export 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)
}
}
/** 计算打包时长(结束时间 - 开始时间),返回格式化字符串 */
export function calcPackDuration(startTime: any, endTime: any): string {
if (!startTime || !endTime) return '—'
try {
const start = new Date(startTime)
const end = new Date(endTime)
if (isNaN(start.getTime()) || isNaN(end.getTime())) return '—'
const diff = end.getTime() - start.getTime()
if (diff < 0) return '—'
const hours = Math.floor(diff / 3600000)
const minutes = Math.floor((diff % 3600000) / 60000)
const seconds = Math.floor((diff % 60000) / 1000)
if (hours > 0) return `${hours}小时${minutes}分${seconds}秒`
if (minutes > 0) return `${minutes}分${seconds}秒`
return `${seconds}秒`
} catch {
return '—'
}
}
// ============================================================
// TAG_RESOLVERS — 标签颜色解析器
// ============================================================
export const TAG_RESOLVERS: Record<string, (val: any) => string> = {
resolveStatusTag(v) {
const s = Number(v)
if (s === 0) return 'info' // 待处理
if (s === 1) return 'warning' // 打包中
if (s === 2) return 'success' // 已完成
if (s === 3) return 'danger' // 异常
return 'info'
},
resolvePackModeTag(v) {
const s = Number(v)
if (s === 2) return 'warning' // 团购
return 'info' // 散单
}
}
// ============================================================
// 二、FIELD_DICT 实例 — 打包流水字段定义
// ============================================================
export const FIELD_DICT: Record<string, FieldDefinition> = {
id: {
key: 'id',
label: '任务ID',
scanBox: null,
table: { width: 90 },
slot: null,
detailLabel: '任务ID'
},
order_id: {
key: 'order_id',
label: '订单ID',
scanBox: { type: 'text', group: SCANBOX_GROUPS.basic },
table: { width: 100 },
slot: null,
detailLabel: '订单ID'
},
waybill_code: {
key: 'waybill_code',
label: '运单号',
scanBox: { type: 'text', group: SCANBOX_GROUPS.basic },
table: { minWidth: 160, showOverflowTooltip: true },
slot: null,
detailLabel: '运单号'
},
wave_no: {
key: 'wave_no',
label: '波次号',
scanBox: { type: 'text', group: SCANBOX_GROUPS.basic },
table: { minWidth: 140, showOverflowTooltip: true },
slot: null,
detailLabel: '波次号'
},
operator_text: {
key: 'operator_text',
label: '打包员',
scanBox: null,
table: { width: 100 },
slot: null,
detailLabel: '打包员'
},
workbench_name: {
key: 'workbench_name',
label: '工作台',
scanBox: null,
table: { width: 120, showOverflowTooltip: true },
slot: null,
detailLabel: '工作台'
},
pack_quantity: {
key: 'pack_quantity',
label: '打包数量',
scanBox: null,
table: { width: 100, align: 'center', sortable: true },
slot: null,
detailLabel: '打包数量'
},
pack_mode: {
key: 'pack_mode',
label: '打包模式',
scanBox: { type: 'select', group: SCANBOX_GROUPS.process, options: getOptions('pack_mode') },
table: { width: 100, align: 'center' },
slot: { type: 'tag', tagResolver: 'resolvePackModeTag', translateField: 'pack_mode' },
detailLabel: '打包模式',
filterParamMap: { '散单': '1', '团购': '2' }
},
status: {
key: 'status',
label: '任务状态',
scanBox: { type: 'select', group: SCANBOX_GROUPS.process, options: getOptions('status') },
table: { width: 100, align: 'center' },
slot: { type: 'tag', tagResolver: 'resolveStatusTag', translateField: 'status' },
detailLabel: '任务状态',
filterParamMap: { '待处理': '0', '打包中': '1', '已完成': '2', '异常': '3' }
},
start_time: {
key: 'start_time',
label: '开始时间',
scanBox: { type: 'daterange', group: SCANBOX_GROUPS.time },
table: { width: 170, sortable: true },
slot: { type: 'text', format: 'datetime' },
detailLabel: '开始时间'
},
end_time: {
key: 'end_time',
label: '结束时间',
scanBox: { type: 'daterange', group: SCANBOX_GROUPS.time },
table: { width: 170, sortable: true },
slot: { type: 'text', format: 'datetime' },
detailLabel: '结束时间'
},
pack_duration: {
key: 'pack_duration',
label: '打包时长',
scanBox: null,
table: { width: 120, align: 'center' },
slot: { type: 'text' },
detailLabel: '打包时长'
},
create_time: {
key: 'create_time',
label: '创建时间',
scanBox: { type: 'daterange', group: SCANBOX_GROUPS.time },
table: { width: 170, sortable: true },
slot: { type: 'text', format: 'datetime' },
detailLabel: '创建时间'
},
/** 仓库 — 仅用于 ScanBox 筛选,options 由 index.vue 动态注入 */
warehouse_id: {
key: 'warehouse_id',
label: '仓库',
scanBox: { type: 'select', group: SCANBOX_GROUPS.basic, options: [] },
table: null,
slot: null
},
/** 工作台ID — 仅用于 ScanBox 筛选 */
workbench_id: {
key: 'workbench_id',
label: '工作台ID',
scanBox: { type: 'text', group: SCANBOX_GROUPS.basic },
table: null,
slot: null
},
/** 录像列 — 由 index.vue 自定义插槽渲染 VideoButton */
videos: {
key: 'videos',
label: '录像',
scanBox: null,
table: { width: 110, fixed: 'right', align: 'center' },
slot: null
}
}
// ============================================================
// 三、ColumnSlotConfig — 列单元格渲染配置
// ============================================================
export interface ColumnSlotConfig {
type: 'tag' | 'text' | 'default' | 'operation'
tagType?: string | Record<string, string>
tagResolver?: string
translateField?: string
format?: 'datetime'
}
// ============================================================
// 三-A、OperationButtonConfig — 操作列按钮配置
// ============================================================
export interface OperationButtonConfig {
key: string
label: string
type?: 'primary' | 'success' | 'warning' | 'danger' | 'info' | ''
actionType: 'form' | 'action'
formKey?: string
formTitle?: string
formWidth?: string
paramMap?: Record<string, string>
extraParams?: Record<string, any>
disabledOnField?: string
confirmMessage?: string
confirmTitle?: string
confirmType?: 'warning' | 'danger' | 'info'
confirmButtonText?: string
}
// ============================================================
// 四、DetailFieldConfig / DetailSectionConfig — 明细面板配置
// ============================================================
export interface DetailFieldConfig {
key: string
label?: string
span?: number
renderType?: 'text' | 'tag' | 'pre'
tagType?: string | Record<string, string>
tagResolver?: string
translateField?: string
}
export interface DetailSectionConfig {
title: string
columnCount: number
fields: DetailFieldConfig[]
}
export interface DetailTabConfig {
name: string
label: string
componentKey: string
component?: Component
}
// ============================================================
// 五、TabPageApiConfig — 标签页接口插槽配置
// ============================================================
export type ApiMethod = (...args: any[]) => Promise<any>
export type ApiSource = 'api' | 'list'
export type ComponentApiConfig = { source: 'list' } | ApiMethod
export interface TabPageApiConfig {
/** 列表查询接口 */
list: ApiMethod
/** 明细面板接口(可选,不配则用 row 数据) */
detail?: ComponentApiConfig
/** 操作日志接口(可选) */
log?: ComponentApiConfig
/** 导出接口(可选) */
export?: ApiMethod
/** 导出进度查询接口(可选) */
exportProgress?: ApiMethod
/** ScanBox 下拉选项数据源接口(可选) */
scanBoxOptions?: Record<string, ApiMethod>
/** 工具栏按钮 → API 方法映射(可选) */
toolbar?: Record<string, ApiMethod>
/** 列表响应解析器 */
parseListResponse?: (res: any) => { list: any[]; total: number }
/** 构建列表请求参数 */
buildListParams?: (params: {
pagination: { page: number; pageSize: number }
conditions: Record<string, any>
sort?: { prop: string; order: string }
}) => Record<string, any>
}
// ============================================================
// 六、TabPageRawConfig — 标签页声明配置(仅用 key 引用)
// ============================================================
export interface TabPageRawConfig {
name: string
label: string
scanBoxCacheKey: string
/** ScanBox 需要的字段 key 列表(从 FIELD_DICT 中查找) */
scanBoxFieldKeys: string[]
/** 表格需要的列 key 列表(从 FIELD_DICT 中查找) */
tableColumnKeys: string[]
upperTableDefaults: {
title: string
enableColumnConfig?: boolean
showIndex?: boolean
showSelection?: boolean
emptyText?: string
}
/** 明细面板标签页配置 */
detailTabs?: { name: string; label: string; componentKey: string }[]
/** 明细面板分区配置(字段 key 列表,resolveTabConfig 展开) */
detailSections: {
title: string
columnCount: number
fieldKeys: string[]
}[]
/** 接口配置(有 api 时启用真实接口) */
api?: TabPageApiConfig
/** 操作列按钮配置(需 tableColumnKeys 包含 'operation') */
operationButtons?: OperationButtonConfig[]
}
// ============================================================
// 七、TabPageConfig — 展开后的完整配置(给 index.vue 使用)
// ============================================================
export interface TabPageConfig {
name: string
label: string
scanBoxCacheKey: string
scanBoxFields: Record<string, any>[]
upperTable: {
title: string
enableColumnConfig: boolean
showIndex: boolean
showSelection: boolean
emptyText: string
columns: Record<string, any>[]
}
columnSlots: Record<string, ColumnSlotConfig>
detailConfig: DetailSectionConfig[]
detailTabs: DetailTabConfig[]
api?: TabPageApiConfig
operationButtons?: OperationButtonConfig[]
}
// ============================================================
// 八、resolveTabConfig — 加载时将 RawConfig 展开为完整配置
// ============================================================
export function resolveTabConfig(raw: TabPageRawConfig): TabPageConfig {
// 展开 ScanBox 字段
const scanBoxFields: Record<string, any>[] = []
for (const key of raw.scanBoxFieldKeys) {
const def = FIELD_DICT[key]
if (!def || !def.scanBox) continue
scanBoxFields.push({
label: def.label,
value: def.key,
type: def.scanBox.type,
options: def.scanBox.options ? [...def.scanBox.options] : undefined,
group: def.scanBox.group,
required: (def.scanBox as any).required
})
}
// 展开表格列
const columns: Record<string, any>[] = []
for (const key of raw.tableColumnKeys) {
const def = FIELD_DICT[key]
if (!def || !def.table) continue
columns.push({
prop: def.key,
label: def.label,
...def.table
})
}
// 展开列插槽
const columnSlots: Record<string, ColumnSlotConfig> = {}
for (const key of raw.tableColumnKeys) {
const def = FIELD_DICT[key]
if (!def || !def.slot) continue
columnSlots[def.key] = { ...def.slot }
}
// 展开明细面板配置
const detailConfig: DetailSectionConfig[] = raw.detailSections.map((sec) => ({
title: sec.title,
columnCount: sec.columnCount,
fields: sec.fieldKeys
.map((key): DetailFieldConfig | null => {
const def = FIELD_DICT[key]
if (!def) return null
return {
key: def.key,
label: def.detailLabel ?? def.label,
translateField: def.slot?.translateField,
tagResolver: def.slot?.tagResolver,
tagType: def.slot?.tagType,
renderType: def.slot?.type === 'tag' ? 'tag' : 'text'
}
})
.filter((f): f is DetailFieldConfig => f !== null)
}))
// 展开明细标签页(解析 componentKey → Component)
const detailTabs: DetailTabConfig[] = raw.detailTabs
? raw.detailTabs.map((tab) => ({
name: tab.name,
label: tab.label,
componentKey: tab.componentKey,
component: COMPONENT_REGISTRY[tab.componentKey]
}))
: [{ name: 'detail', label: '明细', componentKey: 'DetailPanel', component: COMPONENT_REGISTRY['DetailPanel'] }]
return {
name: raw.name,
label: raw.label,
scanBoxCacheKey: raw.scanBoxCacheKey,
scanBoxFields,
upperTable: {
title: raw.upperTableDefaults.title,
enableColumnConfig: raw.upperTableDefaults.enableColumnConfig ?? true,
showIndex: raw.upperTableDefaults.showIndex ?? true,
showSelection: raw.upperTableDefaults.showSelection ?? true,
emptyText: raw.upperTableDefaults.emptyText ?? '暂无数据',
columns
},
columnSlots,
detailConfig,
detailTabs,
api: raw.api,
operationButtons: raw.operationButtons
}
}
// ============================================================
// 九、buildWhereConditions — 将 ScanBox 条件转为 API where 参数
// ============================================================
export function buildWhereConditions(rawConditions: Record<string, any>): Record<string, any> {
const where: Record<string, any> = {}
for (const [key, cond] of Object.entries(rawConditions || {})) {
let value: any = undefined
if (cond && typeof cond === 'object' && 'operator' in cond) {
value = (cond as any).value
} else if (cond !== undefined && cond !== null && cond !== '') {
value = Array.isArray(cond) ? cond[0] ?? '' : cond
}
if (value === undefined || value === null || value === '' || (Array.isArray(value) && value.length === 0)) {
continue
}
const def = FIELD_DICT[key]
// daterange 类型:拆分为 key_start / key_end
if (def?.scanBox?.type === 'daterange' && Array.isArray(value) && value.length === 2) {
where[`${key}_start`] = value[0]
where[`${key}_end`] = value[1]
continue
}
// filterParamMap 值映射(如中文 → 数字)
if (def?.filterParamMap) {
const mapped = def.filterParamMap[String(value)]
if (mapped !== undefined) {
where[key] = mapped
continue
}
}
where[key] = value
}
return where
}
// ============================================================
// 十、工具栏按钮系统
// ============================================================
// 按钮分为三类:
// common — 公共按钮(刷新、导出)
// function — 功能按钮(打开表单/确认窗口)
// basic — 基础操作(字段设置、隐藏详情)
export interface ToolbarButtonConfig {
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
dynamicLabelKey?: string
onlyForTabs?: string[]
buttonType?: 'default' | 'dropdown'
dropdownOptions?: Array<{ label: string; action: string; divided?: boolean }>
formKey?: string
}
export const TOOLBAR_BUTTONS: Record<string, ToolbarButtonConfig> = {
// ===== 公共按钮 =====
refresh: {
key: 'refresh',
label: '刷新',
category: 'common',
type: 'primary',
size: 'small',
loadingKey: 'loading',
action: 'loadData'
},
// ===== 基础操作 =====
columnConfig: {
key: 'columnConfig',
label: '字段设置',
category: 'basic',
size: 'small',
action: 'openColumnConfigPanel'
},
toggleDetail: {
key: 'toggleDetail',
label: '显示详情',
category: 'basic',
dynamicLabelKey: 'detailToggleLabel',
size: 'small',
action: 'toggleDetailVisible'
}
}
/** 按标签页名称获取工具栏按钮列表(自动根据 PAGE_CONFIG 过滤) */
export function getTabToolbarButtons(tabName: string): ToolbarButtonConfig[] {
return Object.values(TOOLBAR_BUTTONS).filter((btn) => {
if (btn.onlyForTabs && !btn.onlyForTabs.includes(tabName)) return false
// 详情面板禁用时,隐藏「显示/隐藏详情」按钮
if (!PAGE_CONFIG.enableDetailPanel && btn.key === 'toggleDetail') return false
return true
})
}
// ============================================================
// 十一、批量操作配置(可选,接入 BatchOperationForm 时使用)
// ============================================================
export interface BatchOperationConfig {
action: string
title: string
confirmText: string
confirmType?: 'warning' | 'error' | 'info' | 'success'
confirmButtonText: string
successText: string
failText: string
apiMethod: (...args: any[]) => Promise<any>
payloadKey?: string
idField?: string | string[]
payloadBuilder?: (rows: Record<string, any>[]) => Record<string, any>
useProgress?: boolean
progressApiMethod?: (...args: any[]) => Promise<any>
}
/** ★ 在此配置批量操作 */
export const BATCH_OPERATION_CONFIGS: Record<string, BatchOperationConfig> = {
// batchExample: {
// action: 'batchExample',
// title: '批量操作示例',
// confirmText: '确定对选中的 {count} 项执行操作吗?',
// confirmType: 'warning',
// confirmButtonText: '确认操作',
// successText: '批量操作成功',
// failText: '批量操作失败',
// apiMethod: yourBatchApi,
// payloadKey: 'ids',
// idField: 'id'
// }
}
// ============================================================
// 十二、标签页注册表 — 打包流水(单页模式)
// ============================================================
export const tabPages: TabPageRawConfig[] = [
{
name: 'packing',
label: '打包任务',
scanBoxCacheKey: 'packingflow-list',
scanBoxFieldKeys: [
'warehouse_id', 'waybill_code', 'wave_no', 'order_id', 'workbench_id',
'status', 'pack_mode',
'start_time'
],
tableColumnKeys: [
'id', 'order_id', 'waybill_code', 'wave_no', 'operator_text',
'workbench_name', 'pack_quantity', 'pack_mode', 'status',
'start_time', 'end_time', 'pack_duration', 'create_time', 'videos'
],
upperTableDefaults: {
title: '打包任务列表',
showIndex: true,
showSelection: false,
emptyText: '暂无打包任务数据'
},
detailTabs: [
{ name: 'detail', label: '任务明细', componentKey: 'DetailPanel' }
],
detailSections: [
{
title: '基础信息',
columnCount: 2,
fieldKeys: ['id', 'order_id', 'wave_no', 'waybill_code', 'operator_text', 'workbench_name', 'pack_quantity', 'pack_mode', 'status']
},
{
title: '时间信息',
columnCount: 2,
fieldKeys: ['start_time', 'end_time', 'pack_duration', 'create_time']
}
],
api: {
list: packingList as ApiMethod,
detail: packingGet as ApiMethod,
parseListResponse(res: any) {
const codeOk = [200, 20000, 1, 0].includes(res.code)
if (!codeOk) throw new Error(res.message || '查询失败')
const list = (res.data?.list ?? []).map((item: any) => ({
...item,
waybill_code: extractWaybillCode(item),
pack_duration: calcPackDuration(item.start_time, item.end_time)
}))
return {
list,
total: res.data?.pagination?.total ?? 0
}
},
buildListParams({ pagination, conditions, sort }) {
// warehouse_id 提到顶层,其余进入 where
const { warehouse_id, ...rest } = buildWhereConditions(conditions)
return {
warehouse_id: warehouse_id || undefined,
pagination: { page: pagination.page, pageSize: pagination.pageSize },
where: rest,
sort: sort?.prop
? { sortField: sort.prop, sortOrder: sort.order === 'ascending' ? 'ASC' : 'DESC' }
: { sortField: 'create_time', sortOrder: 'DESC' }
}
}
}
}
]
// ============================================================
// 十三、工具函数
// ============================================================
/**
* 从 API 返回数据中提取运单号
* 优先取顶层 waybill_code,若为空则从 expresses 数组中拼接
*/
export function extractWaybillCode(row: any): string | null {
if (row.waybill_code) return row.waybill_code
if (row.expresses?.length) {
return row.expresses
.map((e: any) => e.waybill_code)
.filter(Boolean)
.join(',')
}
return null
}
// ============================================================
// 十四、向后兼容导出
// ============================================================
export const templateTabs = tabPages.map((t) => ({ name: t.name, label: t.label, scanBoxCacheKey: t.scanBoxCacheKey }))