import React, { useCallback, useMemo, useRef, useState } from 'react'; import { ActionType, ModalForm, ProColumns, ProFormSelect, ProFormText, ProFormTextArea, ProTable, } from '@ant-design/pro-components'; import type { ColumnsType } from 'antd/es/table'; import { Button, Drawer, Form, Input, InputNumber, message, Modal, Popconfirm, Select, Space, Table, Tag, Typography } from 'antd'; import type { FormListFieldData } from 'antd/es/form/FormList'; import { CheckOutlined, EyeOutlined, PlusOutlined, ReloadOutlined } from '@ant-design/icons'; import { actionRecord, addOrderLine, confirmOutboundPickTask, confirmInboundLine, createOrderHeader, createRecord, getOutboundPickTasks, getRecordLines, pagedList, parseJsonObject, } from '@/services/api'; import { useDictionary } from '@/contexts/DictionaryContext'; import type { OrderRow } from '@/types/orders'; import MasterDataSelect from './MasterDataSelect'; type OrderKind = 'inbound' | 'outbound' | 'transfer' | 'stocktake'; type OrderPageProps = { title: string; controller: string; kind: OrderKind; }; type OrderActionDef = { label: string; backendAction: string }; type LineFieldDef = { key: string; title: string; width: number; type: 'text' | 'number'; required?: boolean; }; /** 与后端 OrderControllers 一致:入库单在明细中确认,单头无 pending/confirm */ const ORDER_ACTIONS: Record = { inbound: [], outbound: [ { label: '待拣', backendAction: 'pending' }, { label: '确认出库', backendAction: 'confirm' }, { label: '取消', backendAction: 'cancel' }, ], transfer: [ { label: '待处理', backendAction: 'pending' }, { label: '确认移库', backendAction: 'confirm' }, ], stocktake: [{ label: '确认盘点', backendAction: 'confirm' }], }; /** 仅用于入库明细查看表头与其它单据共用的 defs;新建入库明细表格单独渲染 */ const INBOUND_LINE_FIELDS: LineFieldDef[] = [ { key: 'inventoryKind', title: '库存类型', width: 132, type: 'number', required: true }, { key: 'materialCode', title: '物料编码', width: 120, type: 'text', required: false }, { key: 'warehouseCode', title: '仓库编码', width: 100, type: 'text', required: true }, { key: 'areaCode', title: '库区编码', width: 88, type: 'text', required: true }, { key: 'qty', title: '数量', width: 88, type: 'number', required: true }, { key: 'attrsJson', title: '扩展字段(JSON)', width: 160, type: 'text' }, ]; const IN_OUT_LINE_FIELDS: LineFieldDef[] = [ { key: 'materialCode', title: '物料编码', width: 120, type: 'text', required: true }, { key: 'containerCode', title: '容器编码', width: 110, type: 'text' }, { key: 'warehouseCode', title: '仓库编码', width: 100, type: 'text', required: true }, { key: 'areaCode', title: '库区编码', width: 88, type: 'text', required: true }, { key: 'locationCode', title: '库位编码', width: 110, type: 'text', required: true }, { key: 'qty', title: '数量', width: 88, type: 'number', required: true }, { key: 'unit', title: '单位', width: 72, type: 'text', required: true }, { key: 'attrsJson', title: '扩展字段(JSON)', width: 160, type: 'text' }, ]; const TRANSFER_LINE_FIELDS: LineFieldDef[] = [ { key: 'materialCode', title: '物料编码', width: 120, type: 'text', required: true }, { key: 'containerCode', title: '容器编码', width: 110, type: 'text' }, { key: 'fromWarehouseCode', title: '来源仓库', width: 100, type: 'text', required: true }, { key: 'fromAreaCode', title: '来源库区', width: 88, type: 'text', required: true }, { key: 'fromLocationCode', title: '来源库位', width: 110, type: 'text', required: true }, { key: 'toWarehouseCode', title: '目标仓库', width: 100, type: 'text', required: true }, { key: 'toAreaCode', title: '目标库区', width: 88, type: 'text', required: true }, { key: 'toLocationCode', title: '目标库位', width: 110, type: 'text', required: true }, { key: 'qty', title: '数量', width: 88, type: 'number', required: true }, { key: 'unit', title: '单位', width: 72, type: 'text', required: true }, { key: 'attrsJson', title: '扩展字段(JSON)', width: 160, type: 'text' }, ]; const STOCKTAKE_LINE_FIELDS: LineFieldDef[] = [ { key: 'materialCode', title: '物料编码', width: 120, type: 'text', required: true }, { key: 'warehouseCode', title: '仓库编码', width: 100, type: 'text', required: true }, { key: 'areaCode', title: '库区编码', width: 88, type: 'text', required: true }, { key: 'locationCode', title: '库位编码', width: 110, type: 'text', required: true }, { key: 'qty', title: '账面数量', width: 96, type: 'number', required: true }, { key: 'countedQty', title: '盘点数量', width: 96, type: 'number', required: true }, { key: 'unit', title: '单位', width: 72, type: 'text', required: true }, { key: 'attrsJson', title: '扩展字段(JSON)', width: 160, type: 'text' }, ]; function lineFieldsForKind(kind: OrderKind): LineFieldDef[] { if (kind === 'transfer') return TRANSFER_LINE_FIELDS; if (kind === 'stocktake') return STOCKTAKE_LINE_FIELDS; if (kind === 'inbound') return INBOUND_LINE_FIELDS; if (kind === 'outbound') { return IN_OUT_LINE_FIELDS.map((field) => field.key === 'locationCode' ? { ...field, title: '指定库位(可选)', required: false, width: 128 } : field, ); } return IN_OUT_LINE_FIELDS; } function createEmptyLine(kind: OrderKind): Record { const base = { inventoryKind: 1, attrsJson: '{}' }; switch (kind) { case 'inbound': return { ...base, materialCode: '', warehouseCode: '', areaCode: '', qty: 0, }; case 'outbound': return { ...base, materialCode: '', containerCode: '', warehouseCode: '', areaCode: '', locationCode: '', qty: 0, }; case 'transfer': return { ...base, materialCode: '', fromWarehouseCode: '', fromAreaCode: '', fromLocationCode: '', toWarehouseCode: '', toAreaCode: '', toLocationCode: '', qty: 0, unit: 'pcs', }; case 'stocktake': return { ...base, materialCode: '', warehouseCode: '', areaCode: '', locationCode: '', qty: 0, countedQty: 0, unit: 'pcs', }; default: return base; } } function normalizeLinesForSubmit(lines: Record[]) { return lines.map((line) => { const attrs = parseJsonObject(line.attrsJson || '{}', {}); const rest = { ...line }; delete rest.attrsJson; const next: Record = { ...rest, attrs, inventoryKind: Number(line.inventoryKind ?? 1), }; if ('locationCode' in next && !String(next.locationCode ?? '').trim()) { delete next.locationCode; } if ('unit' in next && !String(next.unit ?? '').trim()) { delete next.unit; } if ('qty' in next) next.qty = Number(next.qty); if ('countedQty' in next && next.countedQty !== undefined && next.countedQty !== '') next.countedQty = Number(next.countedQty); return next; }); } function renderLineCell(field: FormListFieldData, def: LineFieldDef) { const rules = def.required ? [{ required: true, message: `请输入${def.title}` }] : []; const namePath = [field.name, def.key]; if (def.type === 'number') { const minQty = def.key === 'qty' ? { min: 0.000001 } : { min: 0 }; return ( ); } return ( ); } /** 主数据远端搜索(入库明细):编码/名称 keyword OR */ function InboundMasterSelect({ placeholder = '请输入关键词搜索', fetchPage, afterChange, ...selectProps }: Omit>, 'options' | 'onSearch' | 'mode'> & { fetchPage: (keyword: string) => Promise<{ label: string; value: string }[]>; placeholder?: string; afterChange?: () => void; }) { const [opts, setOpts] = useState<{ label: string; value: string }[]>([]); const [loading, setLoading] = useState(false); const tRef = useRef>(); const runFetch = useCallback( async (keyword: string) => { setLoading(true); try { const o = await fetchPage(keyword); setOpts(o); } catch { setOpts([]); } finally { setLoading(false); } }, [fetchPage], ); React.useEffect(() => () => clearTimeout(tRef.current), []); const onSearch = useCallback( (text: string) => { clearTimeout(tRef.current); tRef.current = setTimeout(() => void runFetch(text.trim()), 300); }, [runFetch], ); return ( {...selectProps} placeholder={placeholder} loading={loading} labelInValue={false} optionFilterProp="label" showSearch filterOption={false} options={opts} allowClear dropdownStyle={{ minWidth: 320 }} style={{ ...(selectProps.style || {}), minWidth: selectProps.disabled ? undefined : 140 }} size="small" onSearch={onSearch} onOpenChange={(open) => { if (open) void runFetch(''); }} onChange={(v, option) => { selectProps.onChange?.(v, option as any); afterChange?.(); }} onClear={() => { selectProps.onClear?.(); afterChange?.(); }} /> ); } type InventoryKindOption = { label: string; value: number }; function InboundInventoryKindSelect({ rowKey, options, }: { rowKey: React.Key; options: InventoryKindOption[]; }) { const form = Form.useFormInstance(); return ( placeholder="请选择" size="small" style={{ width: '100%', minWidth: 120 }} options={options} fieldNames={{ label: 'label', value: 'value' }} optionFilterProp="label" allowClear={false} onChange={(v) => { if (Number(v) === 2) { form.setFieldValue(['lines', rowKey, 'materialCode'], undefined); } }} /> ); } function InboundMaterialSelectCell({ rowKey }: { rowKey: React.Key }) { const form = Form.useFormInstance(); const fetchPage = async (keyword: string) => { const res = await pagedList>('Material', { current: 1, pageSize: 50, ...(keyword ? { keyword } : {}), }); return (res.data || []).map((x: Record) => ({ label: `${x.code} (${x.name || '-'})`, value: String(x.code), })); }; return ( {() => { const ik = Number(form.getFieldValue(['lines', rowKey, 'inventoryKind']) ?? 1); if (ik === 2) { return -; } return ( ); }} ); } function InboundWarehouseSelect({ rowKey }: { rowKey: React.Key }) { const form = Form.useFormInstance(); const fetchPage = async (keyword: string) => { const res = await pagedList>('Warehouse', { current: 1, pageSize: 50, ...(keyword ? { keyword } : {}), }); return (res.data || []).map((x: Record) => ({ label: `${x.code} (${x.name || '-'})`, value: String(x.code), })); }; return ( form.setFieldValue(['lines', rowKey, 'areaCode'], undefined)} /> ); } function InboundAreaSelectCell({ rowKey }: { rowKey: React.Key }) { const form = Form.useFormInstance(); return ( {() => { const wc = form.getFieldValue(['lines', rowKey, 'warehouseCode']); const wh = typeof wc === 'string' ? wc.trim() : ''; const disabled = !wh; const fetchPage = async (keyword: string) => { if (!wh) return []; const res = await pagedList>('Area', { current: 1, pageSize: 50, warehouseCode: wh, ...(keyword ? { keyword } : {}), }); return (res.data || []).map((x: Record) => ({ label: `${x.code} (${x.name || '-'})`, value: String(x.code), })); }; return ( ); }} ); } function inboundLinesEditorColumns( fields: FormListFieldData[], remove: (index: number | number[]) => void, inventoryKindOpts: InventoryKindOption[], ): ColumnsType { const qtyDef: LineFieldDef = { key: 'qty', title: '数量', width: 88, type: 'number', required: true, }; const attrsDef: LineFieldDef = INBOUND_LINE_FIELDS.find((x) => x.key === 'attrsJson')!; const cols: ColumnsType = [ { title: '库存类型', key: 'inventoryKind', width: 132, render: (_u, rowField) => ( ), }, { title: '物料', key: 'materialCode', width: 220, render: (_u, rowField) => , }, { title: '仓库', key: 'warehouseCode', width: 200, render: (_u, rowField) => , }, { title: '库区', key: 'areaCode', width: 200, render: (_u, rowField) => , }, { title: '数量', key: 'qty', width: 100, render: (_u, rowField) => renderLineCell(rowField, qtyDef), }, { title: '扩展字段(JSON)', key: 'attrsJson', width: 160, render: (_u, rowField) => renderLineCell(rowField, attrsDef), }, { title: '操作', key: '_op', width: 56, fixed: 'right', render: (_u, rowField: FormListFieldData) => ( ), }, ]; return cols; } function OutboundMaterialCell({ rowKey }: { rowKey: React.Key }) { const form = Form.useFormInstance(); return ( {() => { const ik = Number(form.getFieldValue(['lines', rowKey, 'inventoryKind']) ?? 1); if (ik === 2) return -; return ( ); }} ); } function OutboundWarehouseCell({ rowKey }: { rowKey: React.Key }) { const form = Form.useFormInstance(); return ( { form.setFieldValue(['lines', rowKey, 'areaCode'], undefined); form.setFieldValue(['lines', rowKey, 'locationCode'], undefined); }} /> ); } function OutboundAreaCell({ rowKey }: { rowKey: React.Key }) { const form = Form.useFormInstance(); return ( {() => { const warehouseCode = String(form.getFieldValue(['lines', rowKey, 'warehouseCode']) || '').trim(); return ( ({ warehouseCode, ...(keyword ? { keyword } : {}) })} afterChange={() => form.setFieldValue(['lines', rowKey, 'locationCode'], undefined)} /> ); }} ); } function OutboundLocationCell({ rowKey }: { rowKey: React.Key }) { const form = Form.useFormInstance(); return ( {() => { const warehouseCode = String(form.getFieldValue(['lines', rowKey, 'warehouseCode']) || '').trim(); const areaCode = String(form.getFieldValue(['lines', rowKey, 'areaCode']) || '').trim(); const disabled = !warehouseCode || !areaCode; return ( ({ warehouseCode, areaCode, ...(keyword ? { keyword } : {}) })} /> ); }} ); } function outboundLinesEditorColumns( fields: FormListFieldData[], remove: (index: number | number[]) => void, ): ColumnsType { const qtyDef: LineFieldDef = { key: 'qty', title: '数量', width: 88, type: 'number', required: true }; return [ { title: '物料', key: 'materialCode', width: 220, render: (_u, rowField) => }, { title: '仓库', key: 'warehouseCode', width: 180, render: (_u, rowField) => }, { title: '库区', key: 'areaCode', width: 170, render: (_u, rowField) => }, { title: '指定库位', key: 'locationCode', width: 180, render: (_u, rowField) => }, { title: '数量', key: 'qty', width: 100, render: (_u, rowField) => renderLineCell(rowField, qtyDef) }, { title: '操作', key: '_op', width: 56, fixed: 'right', render: (_u, rowField) => ( ), }, ]; } function linesEditorColumns( kind: OrderKind, fields: FormListFieldData[], remove: (index: number | number[]) => void, ): any[] { if (kind === 'outbound') { return outboundLinesEditorColumns(fields, remove); } const defs = lineFieldsForKind(kind); const cols: any[] = defs.map((def) => ({ title: def.title, key: def.key, width: def.width, render: (_: unknown, rowField: FormListFieldData) => renderLineCell(rowField, def), })); cols.push({ title: '操作', key: '_op', width: 56, fixed: 'right' as const, render: (_: unknown, rowField: FormListFieldData) => ( ), }); return cols; } function lineIsFullyReceived(row: Record) { const s = row.lineStatus; return s === 'completed' || s === 'Completed' || s === 2; } function orderIsDraft(row?: Record | null) { const s = row?.orderStatus; return s === 'draft' || s === 'Draft' || s === 1; } function normalizeStatusKey(value: unknown) { if (value === 1) return 'draft'; if (value === 2) return 'pending'; if (value === 3) return 'completed'; if (value === 4) return 'cancelled'; return String(value ?? '').trim().toLowerCase(); } function orderStatusColor(value: unknown) { const key = normalizeStatusKey(value); if (key === 'draft') return 'default'; if (key === 'pending') return 'processing'; if (key === 'completed') return 'success'; if (key === 'cancelled' || key === 'canceled') return 'error'; return 'default'; } function orderStatusFallback(value: unknown) { const key = normalizeStatusKey(value); if (key === 'draft') return '草稿'; if (key === 'pending') return '待处理'; if (key === 'completed') return '已完成'; if (key === 'cancelled' || key === 'canceled') return '已取消'; return String(value ?? '-'); } function renderOrderStatusTag(value: unknown, label?: React.ReactNode) { const text = label && String(label).trim() ? label : orderStatusFallback(value); return {text}; } function viewerColumnsForKind(kind: OrderKind): ProColumns>[] { if (kind === 'inbound') { const defs = INBOUND_LINE_FIELDS.filter((d) => d.key !== 'attrsJson'); const cols: ProColumns>[] = defs.map((def) => ({ title: def.title, dataIndex: def.key, width: def.width, ellipsis: true, })); cols.push( { title: '主数据单位', dataIndex: 'materialMasterUnit', width: 100, ellipsis: true }, { title: '库位(展示)', dataIndex: 'locationCode', width: 100, ellipsis: true }, { title: '已收', dataIndex: 'receivedQty', width: 72 }, { title: '剩余', dataIndex: 'remainingQty', width: 72 }, { title: '行状态', dataIndex: 'lineStatus', width: 88 }, ); cols.push({ title: '扩展字段', width: 200, ellipsis: true, render: (_, row) => { const a = row.attrs; if (a === undefined || a === null) return '-'; if (typeof a === 'object') { try { return JSON.stringify(a); } catch { return '-'; } } return String(a); }, }); return cols; } const defs = lineFieldsForKind(kind).filter((d) => d.key !== 'attrsJson'); const cols: ProColumns>[] = defs.map((def) => ({ title: def.title, dataIndex: def.key, width: def.width, ellipsis: true, })); cols.push({ title: '扩展字段', width: 200, ellipsis: true, render: (_, row) => { const a = row.attrs; if (a === undefined || a === null) return '-'; if (typeof a === 'object') { try { return JSON.stringify(a); } catch { return '-'; } } return String(a); }, }); return cols; } const headerColumnsBase: ProColumns[] = [ { title: '单号', dataIndex: 'orderNo', width: 140, ellipsis: true, search: true }, { title: '业务类型', dataIndex: 'bizType', width: 120, ellipsis: true, search: true }, { title: '状态', dataIndex: 'orderStatus', width: 120, search: false }, { title: '备注', dataIndex: 'remark', ellipsis: true, search: false }, { title: '创建时间', dataIndex: 'createTime', width: 168, valueType: 'dateTime', search: false, }, ]; function validateInboundCreateLines(normalizedLines: Record[]) { for (let i = 0; i < normalizedLines.length; i++) { const ln = normalizedLines[i]; const ik = Number(ln.inventoryKind ?? 1); const idx = i + 1; const qty = Number(ln.qty); if (!Number.isFinite(qty) || qty <= 0) { message.error(`第 ${idx} 行:请输入大于 0 的数量`); return false; } const wh = String(ln.warehouseCode || '').trim(); const ac = String(ln.areaCode || '').trim(); if (!wh) { message.error(`第 ${idx} 行:请选择仓库`); return false; } if (!ac) { message.error(`第 ${idx} 行:请选择库区`); return false; } if (ik === 1 && !String(ln.materialCode || '').trim()) { message.error(`第 ${idx} 行:物料行请选择物料`); return false; } if (!(ik === 1 || ik === 2)) { message.error(`第 ${idx} 行:库存类型无效`); return false; } } return true; } export default function OrderPage({ title, controller, kind }: OrderPageProps) { const { buildValueEnum, resolveLabel, buildSelectOptions } = useDictionary(); const actionRef = useRef(); const viewerOrderIdRef = useRef(null); const [createOpen, setCreateOpen] = useState(false); const [addLineOpen, setAddLineOpen] = useState(false); const [viewerOpen, setViewerOpen] = useState(false); const [viewerLoading, setViewerLoading] = useState(false); const [viewerRecord, setViewerRecord] = useState | null>(null); const [viewerLines, setViewerLines] = useState[]>([]); const [viewerPickTasks, setViewerPickTasks] = useState[]>([]); const [viewerTitle, setViewerTitle] = useState(''); const [confirmOpen, setConfirmOpen] = useState(false); const [confirmLoading, setConfirmLoading] = useState(false); const [confirmLine, setConfirmLine] = useState | null>(null); const [locationOptions, setLocationOptions] = useState<{ label: string; value: string }[]>([]); const [confirmForm] = Form.useForm(); const [createForm] = Form.useForm(); const [addLineForm] = Form.useForm(); const fetchConfirmContainerPage = useCallback(async (keyword: string) => { const res = await pagedList>('Container', { current: 1, pageSize: 50, ...(keyword ? { keyword } : {}), }); return (res.data || []).map((x: Record) => ({ label: `${x.code} (${x.name || '-'})`, value: String(x.code), })); }, []); const actions = ORDER_ACTIONS[kind]; const inboundBizTypeOptions = useMemo(() => { const dict = buildSelectOptions('InboundOrder.bizType').map(({ label, value }) => ({ label, value: String(value), })); if (dict.length > 0) return dict; return [{ label: '默认入库', value: 'inbound_default' }]; }, [buildSelectOptions]); const inventoryKindInboundOpts = useMemo((): InventoryKindOption[] => { const mapped = buildSelectOptions('InventoryKind', true).map(({ label, value }) => ({ label, value: Number(value), })); const ok = mapped.filter((x) => x.value === 1 || x.value === 2); return ok.length >= 2 ? ok : [ { label: '物料', value: 1 }, { label: '空容器', value: 2 }, ]; }, [buildSelectOptions]); const bizTypeDictCategory = useMemo(() => { if (kind === 'inbound') return 'InboundOrder.bizType'; if (kind === 'outbound') return 'OutboundOrder.bizType'; if (kind === 'transfer') return 'TransferOrder.bizType'; return 'StocktakeOrder.bizType'; }, [kind]); const headerColumns = useMemo( () => headerColumnsBase.map((col): ProColumns => { if (col.dataIndex === 'orderNo') { return { ...col, render: (_, row) => {row.orderNo || '-'}, }; } if (col.dataIndex === 'orderStatus') { const valueEnum = buildValueEnum('OrderStatus'); return { ...col, ...(Object.keys(valueEnum).length ? { valueEnum } : {}), render: (_, row) => renderOrderStatusTag(row.orderStatus, resolveLabel('OrderStatus', row.orderStatus)), }; } if (col.dataIndex === 'bizType') { const valueEnum = buildValueEnum(bizTypeDictCategory); return Object.keys(valueEnum).length ? { ...col, valueEnum } : col; } return col; }), [buildValueEnum, bizTypeDictCategory, resolveLabel], ); const refreshViewerLines = useCallback(async () => { const id = viewerOrderIdRef.current; if (id === null || id === undefined) return; try { const lines = await getRecordLines>(controller, id); setViewerLines(Array.isArray(lines) ? lines : []); if (kind === 'outbound') { const tasks = await getOutboundPickTasks>(id); setViewerPickTasks(Array.isArray(tasks) ? tasks : []); } } catch { message.error('刷新明细失败'); } }, [controller, kind]); const confirmPickTask = useCallback( async (task: Record) => { if (!task.id) return; await confirmOutboundPickTask({ id: task.id, pickedQty: Number(task.qty), }); message.success('拣货已确认'); await refreshViewerLines(); actionRef.current?.reload(); }, [refreshViewerLines], ); const openConfirmInbound = useCallback( async (line: Record) => { setConfirmLine(line); confirmForm.resetFields(); const ik = Number(line.inventoryKind ?? 1); const rem = Number(line.remainingQty); confirmForm.setFieldsValue({ qty: Number.isFinite(rem) && rem > 0 ? rem : undefined, ...(ik === 2 ? { unit: String(line.unit ?? '').trim() || undefined } : {}), containerCode: line.containerCode !== undefined && line.containerCode !== null && `${line.containerCode}`.trim() ? `${line.containerCode}`.trim() : undefined, }); setConfirmOpen(true); try { const res = await pagedList('Location', { current: 1, pageSize: 500, warehouseCode: line.warehouseCode, areaCode: line.areaCode, }); setLocationOptions((res.data || []).map((r: any) => ({ label: r.code, value: r.code }))); } catch { setLocationOptions([]); message.error('加载库位列表失败'); } }, [confirmForm], ); const openViewer = useCallback( async (record: Record) => { viewerOrderIdRef.current = record.id; setViewerRecord(record); setViewerTitle(`${record.orderNo || record.id}`); setViewerOpen(true); setViewerLoading(true); setViewerLines([]); setViewerPickTasks([]); try { const lines = await getRecordLines>(controller, record.id); setViewerLines(Array.isArray(lines) ? lines : []); if (kind === 'outbound') { const tasks = await getOutboundPickTasks>(record.id); setViewerPickTasks(Array.isArray(tasks) ? tasks : []); } } catch { setViewerLines([]); setViewerPickTasks([]); message.error('加载明细失败'); } finally { setViewerLoading(false); } }, [controller, kind], ); const viewerCols = useMemo(() => { const baseCols = viewerColumnsForKind(kind); let cols = kind === 'inbound' ? baseCols.map((c) => c.dataIndex === 'lineStatus' ? { ...c, render: (_: unknown, row: Record) => resolveLabel('OrderLineStatus', row.lineStatus), } : c, ) : baseCols; if (kind !== 'inbound') return cols; return [ ...cols, { title: '操作', key: 'inboundConfirm', width: 108, fixed: 'right' as const, render: (_: unknown, row: Record) => lineIsFullyReceived(row) ? ( '-' ) : ( ), }, ]; }, [kind, resolveLabel, openConfirmInbound]); const pickTaskCols = useMemo( (): ProColumns>[] => [ { title: '任务号', dataIndex: 'taskNo', width: 180, ellipsis: true }, { title: '物料', dataIndex: 'materialCode', width: 120, ellipsis: true }, { title: '容器', dataIndex: 'containerCode', width: 110, ellipsis: true }, { title: '仓库', dataIndex: 'warehouseCode', width: 100, ellipsis: true }, { title: '库区', dataIndex: 'areaCode', width: 88, ellipsis: true }, { title: '分区', dataIndex: 'zoneCode', width: 88, ellipsis: true }, { title: '拣货库位', dataIndex: 'locationCode', width: 110, ellipsis: true }, { title: '应拣', dataIndex: 'qty', width: 88 }, { title: '已拣', dataIndex: 'pickedQty', width: 88 }, { title: '单位', dataIndex: 'unit', width: 72 }, { title: '拣货人', dataIndex: 'pickerUserId', width: 120, ellipsis: true }, { title: '拣货时间', dataIndex: 'pickedTime', width: 168, ellipsis: true, render: (_, row) => row.pickedTime || '-', }, { title: '异常原因', dataIndex: 'exceptionReason', width: 160, ellipsis: true }, { title: '状态', dataIndex: 'taskStatus', width: 88, render: (_, row) => { const s = row.taskStatus; if (s === 'picked' || s === 'Picked' || s === 2) return '已拣'; if (s === 'cancelled' || s === 'Cancelled' || s === 3) return '已取消'; return '待拣'; }, }, { title: '操作', key: 'pickAction', width: 110, fixed: 'right', render: (_, row) => { const s = row.taskStatus; const isOpen = s === 'open' || s === 'Open' || s === 1; if (!isOpen) return '-'; return ( confirmPickTask(row)} > ); }, }, ], [confirmPickTask], ); const createInitialValues = useMemo( () => kind === 'inbound' ? { bizType: `${kind}_default`, lines: [createEmptyLine(kind)] } : { bizType: `${kind}_default`, attrsJson: '{}', orderNo: '', lines: [createEmptyLine(kind)] }, [kind], ); const addLineInitialValues = useMemo( () => ({ lines: [createEmptyLine(kind)] }), [kind], ); const canMaintainLines = kind === 'inbound' || kind === 'outbound'; const createModalWidth = kind === 'inbound' || kind === 'outbound' ? 1180 : 1040; return ( <> headerTitle={title} actionRef={actionRef} rowKey="id" columns={[ ...headerColumns, { title: '操作', valueType: 'option', width: kind === 'inbound' ? 140 : kind === 'outbound' ? 280 : 220, fixed: 'right', search: false, render: (_, record) => ( {actions.map((a, idx) => { const button = ( ); if (a.backendAction !== 'cancel') return button; return ( { await actionRecord(controller, a.backendAction, record.id); message.success('操作成功'); actionRef.current?.reload(); }} > ); })} ), }, ]} request={(params) => pagedList(controller, params)} search={{ labelWidth: 'auto' }} scroll={{ x: 'max-content' }} options={{ density: true, reload: false, setting: true }} toolBarRender={() => [ , ...(canMaintainLines ? [ , ] : []), , ]} /> setCreateOpen(false), }} onFinish={async (values) => { const lines = values.lines as Record[]; if (!lines?.length) { message.error('请至少添加一行明细'); return false; } const normalized = normalizeLinesForSubmit(lines); if (kind === 'inbound') { if (!validateInboundCreateLines(normalized)) return false; await createRecord(controller, { bizType: values.bizType, remark: values.remark, lines: normalized, }); } else { await createRecord(controller, { ...(kind === 'outbound' ? {} : { orderNo: values.orderNo }), bizType: values.bizType, remark: values.remark, attrs: parseJsonObject(values.attrsJson, {}), lines: normalized, }); } message.success('创建成功'); setCreateOpen(false); actionRef.current?.reload(); return true; }} > {kind !== 'inbound' && kind !== 'outbound' && ( )} {kind === 'inbound' ? ( ) : ( )} {kind !== 'inbound' && ( )} {(fields, { add, remove }) => ( <> size="small" pagination={false} scroll={{ x: 'max-content' }} dataSource={fields} rowKey="key" columns={ kind === 'inbound' ? inboundLinesEditorColumns(fields, remove, inventoryKindInboundOpts) : (linesEditorColumns(kind, fields, remove) as ColumnsType) } /> )} setAddLineOpen(false), }} onFinish={async (values) => { const orderId = viewerOrderIdRef.current; if (!orderId) { message.error('请先打开单据详情'); return false; } const lines = values.lines as Record[]; if (!lines?.length) { message.error('请至少添加一行明细'); return false; } const normalized = normalizeLinesForSubmit(lines); if (kind === 'inbound' && !validateInboundCreateLines(normalized)) return false; for (const line of normalized) { await addOrderLine(controller, { orderId, line }); } message.success('明细添加成功'); setAddLineOpen(false); await refreshViewerLines(); actionRef.current?.reload(); return true; }} > {(fields, { add, remove }) => ( <> size="small" pagination={false} scroll={{ x: 'max-content' }} dataSource={fields} rowKey="key" columns={ kind === 'inbound' ? inboundLinesEditorColumns(fields, remove, inventoryKindInboundOpts) : (linesEditorColumns(kind, fields, remove) as ColumnsType) } /> )} } onClick={() => { addLineForm.resetFields(); addLineForm.setFieldsValue(addLineInitialValues); setAddLineOpen(true); }} > 新增明细 ) : null } onClose={() => { setViewerOpen(false); setViewerRecord(null); }} >
{viewerRecord?.orderNo || viewerTitle || '-'}
{title}
{renderOrderStatusTag( viewerRecord?.orderStatus, resolveLabel('OrderStatus', viewerRecord?.orderStatus), )}
业务类型
{viewerRecord?.bizType ? resolveLabel(bizTypeDictCategory, viewerRecord.bizType) || viewerRecord.bizType : '-'}
明细行数
{viewerLines.length}
{kind === 'outbound' && (
拣货任务
{viewerPickTasks.length}
)}
创建时间
{viewerRecord?.createTime || '-'}
备注
{viewerRecord?.remark || '-'}
> loading={viewerLoading} rowKey={(row, i) => String(row.id ?? row.lineNo ?? i)} search={false} pagination={false} options={false} columns={viewerCols} dataSource={viewerLines} scroll={{ x: 'max-content' }} /> {kind === 'outbound' && ( <>
拣货任务
> loading={viewerLoading} rowKey={(row, i) => String(row.id ?? row.taskNo ?? i)} search={false} pagination={false} options={false} columns={pickTaskCols} dataSource={viewerPickTasks} scroll={{ x: 'max-content' }} locale={{ emptyText: '待出库单转待拣后生成拣货任务' }} /> )}
setConfirmOpen(false)} onOk={async () => { if (!confirmLine?.id) return; try { const v = await confirmForm.validateFields(); setConfirmLoading(true); const ik = Number(confirmLine.inventoryKind ?? 1); await confirmInboundLine({ lineId: confirmLine.id, locationCode: v.locationCode, qty: Number(v.qty), ...(ik === 2 ? { unit: String(v.unit ?? '') .trim() || String(confirmLine.unit ?? '') .trim(), } : {}), containerCode: v.containerCode, }); message.success('确认成功'); setConfirmOpen(false); await refreshViewerLines(); actionRef.current?.reload(); } catch (e: any) { if (e?.errorFields) return; } finally { setConfirmLoading(false); } }} >
)}
); }