1536 lines
52 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.

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<OrderKind, OrderActionDef[]> = {
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<string, any> {
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<string, any>[]) {
return lines.map((line) => {
const attrs = parseJsonObject(line.attrsJson || '{}', {});
const rest = { ...line };
delete rest.attrsJson;
const next: Record<string, any> = {
...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 (
<Form.Item name={namePath} rules={rules} noStyle>
<InputNumber {...minQty} size="small" style={{ width: '100%' }} />
</Form.Item>
);
}
return (
<Form.Item name={namePath} rules={rules} noStyle>
<Input size="small" />
</Form.Item>
);
}
/** 主数据远端搜索(入库明细):编码/名称 keyword OR */
function InboundMasterSelect({
placeholder = '请输入关键词搜索',
fetchPage,
afterChange,
...selectProps
}: Omit<React.ComponentProps<typeof Select<string>>, '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<ReturnType<typeof setTimeout>>();
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 (
<Select<string, { label: string; value: string }>
{...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 (
<Form.Item
name={[rowKey as never, 'inventoryKind']}
rules={[{ required: true, message: '请选择类型' }]}
noStyle
initialValue={1}
>
<Select<number, InventoryKindOption>
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);
}
}}
/>
</Form.Item>
);
}
function InboundMaterialSelectCell({ rowKey }: { rowKey: React.Key }) {
const form = Form.useFormInstance();
const fetchPage = async (keyword: string) => {
const res = await pagedList<Record<string, any>>('Material', {
current: 1,
pageSize: 50,
...(keyword ? { keyword } : {}),
});
return (res.data || []).map((x: Record<string, any>) => ({
label: `${x.code} (${x.name || '-'})`,
value: String(x.code),
}));
};
return (
<Form.Item noStyle dependencies={[['lines', rowKey, 'inventoryKind']]}>
{() => {
const ik = Number(form.getFieldValue(['lines', rowKey, 'inventoryKind']) ?? 1);
if (ik === 2) {
return <span style={{ color: '#999' }}>-</span>;
}
return (
<Form.Item
name={[rowKey as never, 'materialCode']}
rules={[{ required: true, message: '请选择物料' }]}
noStyle
>
<InboundMasterSelect placeholder="搜编码或名称" fetchPage={fetchPage} />
</Form.Item>
);
}}
</Form.Item>
);
}
function InboundWarehouseSelect({ rowKey }: { rowKey: React.Key }) {
const form = Form.useFormInstance();
const fetchPage = async (keyword: string) => {
const res = await pagedList<Record<string, any>>('Warehouse', {
current: 1,
pageSize: 50,
...(keyword ? { keyword } : {}),
});
return (res.data || []).map((x: Record<string, any>) => ({
label: `${x.code} (${x.name || '-'})`,
value: String(x.code),
}));
};
return (
<Form.Item name={[rowKey as never, 'warehouseCode']} rules={[{ required: true, message: '请选择仓库' }]} noStyle>
<InboundMasterSelect
placeholder="搜编码或名称"
fetchPage={fetchPage}
afterChange={() => form.setFieldValue(['lines', rowKey, 'areaCode'], undefined)}
/>
</Form.Item>
);
}
function InboundAreaSelectCell({ rowKey }: { rowKey: React.Key }) {
const form = Form.useFormInstance();
return (
<Form.Item noStyle dependencies={[['lines', rowKey, 'warehouseCode']]}>
{() => {
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<Record<string, any>>('Area', {
current: 1,
pageSize: 50,
warehouseCode: wh,
...(keyword ? { keyword } : {}),
});
return (res.data || []).map((x: Record<string, any>) => ({
label: `${x.code} (${x.name || '-'})`,
value: String(x.code),
}));
};
return (
<Form.Item name={[rowKey as never, 'areaCode']} rules={[{ required: true, message: '请选择库区' }]} noStyle>
<InboundMasterSelect
placeholder={disabled ? '先选仓库' : '搜编码或名称'}
fetchPage={fetchPage}
disabled={disabled}
/>
</Form.Item>
);
}}
</Form.Item>
);
}
function inboundLinesEditorColumns(
fields: FormListFieldData[],
remove: (index: number | number[]) => void,
inventoryKindOpts: InventoryKindOption[],
): ColumnsType<FormListFieldData> {
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<FormListFieldData> = [
{
title: '库存类型',
key: 'inventoryKind',
width: 132,
render: (_u, rowField) => (
<InboundInventoryKindSelect rowKey={rowField.name} options={inventoryKindOpts} />
),
},
{
title: '物料',
key: 'materialCode',
width: 220,
render: (_u, rowField) => <InboundMaterialSelectCell rowKey={rowField.name} />,
},
{
title: '仓库',
key: 'warehouseCode',
width: 200,
render: (_u, rowField) => <InboundWarehouseSelect rowKey={rowField.name} />,
},
{
title: '库区',
key: 'areaCode',
width: 200,
render: (_u, rowField) => <InboundAreaSelectCell rowKey={rowField.name} />,
},
{
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) => (
<Button
type="link"
size="small"
danger
disabled={fields.length <= 1}
onClick={() => remove(rowField.name)}
>
删
</Button>
),
},
];
return cols;
}
function OutboundMaterialCell({ rowKey }: { rowKey: React.Key }) {
const form = Form.useFormInstance();
return (
<Form.Item noStyle dependencies={[['lines', rowKey, 'inventoryKind']]}>
{() => {
const ik = Number(form.getFieldValue(['lines', rowKey, 'inventoryKind']) ?? 1);
if (ik === 2) return <span style={{ color: '#999' }}>-</span>;
return (
<Form.Item name={[rowKey as never, 'materialCode']} rules={[{ required: true, message: '请选择物料' }]} noStyle>
<MasterDataSelect controller="Material" placeholder="搜物料编码/名称" size="small" style={{ minWidth: 180 }} />
</Form.Item>
);
}}
</Form.Item>
);
}
function OutboundWarehouseCell({ rowKey }: { rowKey: React.Key }) {
const form = Form.useFormInstance();
return (
<Form.Item name={[rowKey as never, 'warehouseCode']} rules={[{ required: true, message: '请选择仓库' }]} noStyle>
<MasterDataSelect
controller="Warehouse"
placeholder="搜仓库"
size="small"
style={{ minWidth: 160 }}
afterChange={() => {
form.setFieldValue(['lines', rowKey, 'areaCode'], undefined);
form.setFieldValue(['lines', rowKey, 'locationCode'], undefined);
}}
/>
</Form.Item>
);
}
function OutboundAreaCell({ rowKey }: { rowKey: React.Key }) {
const form = Form.useFormInstance();
return (
<Form.Item noStyle dependencies={[['lines', rowKey, 'warehouseCode']]}>
{() => {
const warehouseCode = String(form.getFieldValue(['lines', rowKey, 'warehouseCode']) || '').trim();
return (
<Form.Item name={[rowKey as never, 'areaCode']} rules={[{ required: true, message: '请选择库区' }]} noStyle>
<MasterDataSelect
controller="Area"
placeholder={warehouseCode ? '搜库区' : '先选仓库'}
size="small"
style={{ minWidth: 150 }}
disabled={!warehouseCode}
buildParams={(keyword) => ({ warehouseCode, ...(keyword ? { keyword } : {}) })}
afterChange={() => form.setFieldValue(['lines', rowKey, 'locationCode'], undefined)}
/>
</Form.Item>
);
}}
</Form.Item>
);
}
function OutboundLocationCell({ rowKey }: { rowKey: React.Key }) {
const form = Form.useFormInstance();
return (
<Form.Item noStyle dependencies={[['lines', rowKey, 'warehouseCode'], ['lines', rowKey, 'areaCode']]}>
{() => {
const warehouseCode = String(form.getFieldValue(['lines', rowKey, 'warehouseCode']) || '').trim();
const areaCode = String(form.getFieldValue(['lines', rowKey, 'areaCode']) || '').trim();
const disabled = !warehouseCode || !areaCode;
return (
<Form.Item name={[rowKey as never, 'locationCode']} noStyle>
<MasterDataSelect
controller="Location"
placeholder={disabled ? '自动分配' : '可选指定库位'}
size="small"
style={{ minWidth: 160 }}
disabled={disabled}
buildParams={(keyword) => ({ warehouseCode, areaCode, ...(keyword ? { keyword } : {}) })}
/>
</Form.Item>
);
}}
</Form.Item>
);
}
function outboundLinesEditorColumns(
fields: FormListFieldData[],
remove: (index: number | number[]) => void,
): ColumnsType<FormListFieldData> {
const qtyDef: LineFieldDef = { key: 'qty', title: '数量', width: 88, type: 'number', required: true };
return [
{ title: '物料', key: 'materialCode', width: 220, render: (_u, rowField) => <OutboundMaterialCell rowKey={rowField.name} /> },
{ title: '仓库', key: 'warehouseCode', width: 180, render: (_u, rowField) => <OutboundWarehouseCell rowKey={rowField.name} /> },
{ title: '库区', key: 'areaCode', width: 170, render: (_u, rowField) => <OutboundAreaCell rowKey={rowField.name} /> },
{ title: '指定库位', key: 'locationCode', width: 180, render: (_u, rowField) => <OutboundLocationCell rowKey={rowField.name} /> },
{ title: '数量', key: 'qty', width: 100, render: (_u, rowField) => renderLineCell(rowField, qtyDef) },
{
title: '操作',
key: '_op',
width: 56,
fixed: 'right',
render: (_u, rowField) => (
<Button type="link" size="small" danger disabled={fields.length <= 1} onClick={() => remove(rowField.name)}>
删
</Button>
),
},
];
}
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) => (
<Button
type="link"
size="small"
danger
disabled={fields.length <= 1}
onClick={() => remove(rowField.name)}
>
删
</Button>
),
});
return cols;
}
function lineIsFullyReceived(row: Record<string, any>) {
const s = row.lineStatus;
return s === 'completed' || s === 'Completed' || s === 2;
}
function orderIsDraft(row?: Record<string, any> | 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 <Tag color={orderStatusColor(value)}>{text}</Tag>;
}
function viewerColumnsForKind(kind: OrderKind): ProColumns<Record<string, any>>[] {
if (kind === 'inbound') {
const defs = INBOUND_LINE_FIELDS.filter((d) => d.key !== 'attrsJson');
const cols: ProColumns<Record<string, any>>[] = 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<Record<string, any>>[] = 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<OrderRow>[] = [
{ 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<string, any>[]) {
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<ActionType>();
const viewerOrderIdRef = useRef<string | number | null>(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<Record<string, any> | null>(null);
const [viewerLines, setViewerLines] = useState<Record<string, any>[]>([]);
const [viewerPickTasks, setViewerPickTasks] = useState<Record<string, any>[]>([]);
const [viewerTitle, setViewerTitle] = useState('');
const [confirmOpen, setConfirmOpen] = useState(false);
const [confirmLoading, setConfirmLoading] = useState(false);
const [confirmLine, setConfirmLine] = useState<Record<string, any> | 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<Record<string, any>>('Container', {
current: 1,
pageSize: 50,
...(keyword ? { keyword } : {}),
});
return (res.data || []).map((x: Record<string, any>) => ({
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<OrderRow> => {
if (col.dataIndex === 'orderNo') {
return {
...col,
render: (_, row) => <span className="wms-order-no">{row.orderNo || '-'}</span>,
};
}
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<Record<string, any>>(controller, id);
setViewerLines(Array.isArray(lines) ? lines : []);
if (kind === 'outbound') {
const tasks = await getOutboundPickTasks<Record<string, any>>(id);
setViewerPickTasks(Array.isArray(tasks) ? tasks : []);
}
} catch {
message.error('刷新明细失败');
}
}, [controller, kind]);
const confirmPickTask = useCallback(
async (task: Record<string, any>) => {
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<string, any>) => {
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<string, any>) => {
viewerOrderIdRef.current = record.id;
setViewerRecord(record);
setViewerTitle(`${record.orderNo || record.id}`);
setViewerOpen(true);
setViewerLoading(true);
setViewerLines([]);
setViewerPickTasks([]);
try {
const lines = await getRecordLines<Record<string, any>>(controller, record.id);
setViewerLines(Array.isArray(lines) ? lines : []);
if (kind === 'outbound') {
const tasks = await getOutboundPickTasks<Record<string, any>>(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<string, any>) =>
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<string, any>) =>
lineIsFullyReceived(row) ? (
'-'
) : (
<Button type="link" size="small" onClick={() => void openConfirmInbound(row)}>
确认入库
</Button>
),
},
];
}, [kind, resolveLabel, openConfirmInbound]);
const pickTaskCols = useMemo(
(): ProColumns<Record<string, any>>[] => [
{ 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 (
<Popconfirm
title="确认该拣货任务已完成?"
okText="确认"
cancelText="取消"
onConfirm={() => confirmPickTask(row)}
>
<Button type="link" size="small" icon={<CheckOutlined />}>
确认拣货
</Button>
</Popconfirm>
);
},
},
],
[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 (
<>
<ProTable<OrderRow>
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) => (
<Space wrap size={[4, 4]}>
<Button type="link" size="small" icon={<EyeOutlined />} onClick={() => openViewer(record)}>
查看明细
</Button>
{actions.map((a, idx) => {
const button = (
<Button
key={`${a.backendAction}-${idx}-${a.label}`}
type="link"
size="small"
onClick={async () => {
await actionRecord(controller, a.backendAction, record.id);
message.success('操作成功');
actionRef.current?.reload();
}}
>
{a.label}
</Button>
);
if (a.backendAction !== 'cancel') return button;
return (
<Popconfirm
key={`${a.backendAction}-${idx}-${a.label}`}
title="取消出库单会释放已预占库存,确认继续?"
okText="确认"
cancelText="取消"
onConfirm={async () => {
await actionRecord(controller, a.backendAction, record.id);
message.success('操作成功');
actionRef.current?.reload();
}}
>
<Button type="link" size="small">
{a.label}
</Button>
</Popconfirm>
);
})}
</Space>
),
},
]}
request={(params) => pagedList(controller, params)}
search={{ labelWidth: 'auto' }}
scroll={{ x: 'max-content' }}
options={{ density: true, reload: false, setting: true }}
toolBarRender={() => [
<Button key="reload" icon={<ReloadOutlined />} onClick={() => actionRef.current?.reload()}>
刷新
</Button>,
...(canMaintainLines
? [
<Button
key="new-header"
onClick={async () => {
await createOrderHeader(controller, {
bizType: `${kind}_default`,
...(kind === 'outbound' ? { attrs: {} } : {}),
});
message.success('单头创建成功');
actionRef.current?.reload();
}}
>
新增单头
</Button>,
]
: []),
<Button key="new" type="primary" icon={<PlusOutlined />} onClick={() => setCreateOpen(true)}>
新增
</Button>,
]}
/>
<ModalForm
title={`新增${title}`}
width={createModalWidth}
open={createOpen}
initialValues={createInitialValues}
key={kind}
form={createForm}
modalProps={{
destroyOnHidden: true,
onCancel: () => setCreateOpen(false),
}}
onFinish={async (values) => {
const lines = values.lines as Record<string, any>[];
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' && (
<ProFormText name="orderNo" label="单号" rules={[{ required: true, message: '请输入单号' }]} />
)}
{kind === 'inbound' ? (
<ProFormSelect
name="bizType"
label="业务类型"
placeholder="请选择业务类型"
rules={[{ required: true, message: '请选择业务类型' }]}
options={inboundBizTypeOptions}
fieldProps={{ allowClear: false, optionFilterProp: 'label', showSearch: true }}
/>
) : (
<ProFormText name="bizType" label="业务类型" rules={[{ required: true, message: '请输入业务类型' }]} />
)}
<ProFormTextArea name="remark" label="备注" fieldProps={{ rows: 3 }} />
{kind !== 'inbound' && (
<ProFormTextArea name="attrsJson" label="单据扩展字段(JSON)" fieldProps={{ rows: 4 }} />
)}
<Form.Item label="明细" required style={{ marginBottom: 0 }}>
<Form.List name="lines">
{(fields, { add, remove }) => (
<>
<Table<FormListFieldData>
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<FormListFieldData>)
}
/>
<Button
type="dashed"
block
style={{ marginTop: 8 }}
onClick={() => add(createEmptyLine(kind))}
>
新增明细行
</Button>
</>
)}
</Form.List>
</Form.Item>
</ModalForm>
<ModalForm
title={`新增${title}明细`}
width={kind === 'inbound' || kind === 'outbound' ? 1180 : 1040}
open={addLineOpen}
initialValues={addLineInitialValues}
key={`${kind}-add-line`}
form={addLineForm}
modalProps={{
destroyOnHidden: true,
onCancel: () => setAddLineOpen(false),
}}
onFinish={async (values) => {
const orderId = viewerOrderIdRef.current;
if (!orderId) {
message.error('请先打开单据详情');
return false;
}
const lines = values.lines as Record<string, any>[];
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;
}}
>
<Form.Item label="明细" required style={{ marginBottom: 0 }}>
<Form.List name="lines">
{(fields, { add, remove }) => (
<>
<Table<FormListFieldData>
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<FormListFieldData>)
}
/>
<Button
type="dashed"
block
style={{ marginTop: 8 }}
onClick={() => add(createEmptyLine(kind))}
>
新增明细行
</Button>
</>
)}
</Form.List>
</Form.Item>
</ModalForm>
<Drawer
title={`单据明细 — ${viewerTitle}`}
open={viewerOpen}
width={kind === 'inbound' || kind === 'outbound' ? 1280 : 1040}
destroyOnHidden
extra={
canMaintainLines && orderIsDraft(viewerRecord) ? (
<Button
type="primary"
size="small"
icon={<PlusOutlined />}
onClick={() => {
addLineForm.resetFields();
addLineForm.setFieldsValue(addLineInitialValues);
setAddLineOpen(true);
}}
>
新增明细
</Button>
) : null
}
onClose={() => {
setViewerOpen(false);
setViewerRecord(null);
}}
>
<div className="wms-order-detail-head">
<div className="wms-order-detail-title">
<div>
<div className="wms-order-detail-title-main">{viewerRecord?.orderNo || viewerTitle || '-'}</div>
<Typography.Text type="secondary">{title}</Typography.Text>
</div>
{renderOrderStatusTag(
viewerRecord?.orderStatus,
resolveLabel('OrderStatus', viewerRecord?.orderStatus),
)}
</div>
<div className="wms-order-detail-meta">
<div>
<div className="wms-order-detail-meta-label">业务类型</div>
<div className="wms-order-detail-meta-value">
{viewerRecord?.bizType
? resolveLabel(bizTypeDictCategory, viewerRecord.bizType) || viewerRecord.bizType
: '-'}
</div>
</div>
<div>
<div className="wms-order-detail-meta-label">明细行数</div>
<div className="wms-order-detail-meta-value">{viewerLines.length}</div>
</div>
{kind === 'outbound' && (
<div>
<div className="wms-order-detail-meta-label">拣货任务</div>
<div className="wms-order-detail-meta-value">{viewerPickTasks.length}</div>
</div>
)}
<div>
<div className="wms-order-detail-meta-label">创建时间</div>
<div className="wms-order-detail-meta-value">{viewerRecord?.createTime || '-'}</div>
</div>
<div>
<div className="wms-order-detail-meta-label">备注</div>
<div className="wms-order-detail-meta-value">{viewerRecord?.remark || '-'}</div>
</div>
</div>
</div>
<ProTable<Record<string, any>>
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' && (
<>
<div className="wms-section-title">拣货任务</div>
<ProTable<Record<string, any>>
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: '待出库单转待拣后生成拣货任务' }}
/>
</>
)}
</Drawer>
<Modal
title="确认入库"
open={confirmOpen}
confirmLoading={confirmLoading}
destroyOnHidden
onCancel={() => 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);
}
}}
>
<Form form={confirmForm} layout="vertical">
<Form.Item name="locationCode" label="入库库位" rules={[{ required: true, message: '请选择库位' }]}>
<Select
showSearch
allowClear
placeholder="选择库区下的库位"
options={locationOptions}
optionFilterProp="label"
/>
</Form.Item>
<Form.Item name="qty" label="入库数量" rules={[{ required: true, message: '请输入数量' }]}>
<InputNumber
min={0.000001}
max={confirmLine ? Number(confirmLine.remainingQty) : undefined}
style={{ width: '100%' }}
/>
</Form.Item>
{Number(confirmLine?.inventoryKind) !== 2 ? (
<Typography.Paragraph type="secondary" style={{ marginBottom: 16 }}>
单位:
{(() => {
const u =
`${confirmLine?.materialMasterUnit ?? ''}`.trim() ||
`${confirmLine?.unit ?? ''}`.trim();
return u || '未在明细中带出,将根据物料主数据写入库存(无需手工填写)。';
})()}
</Typography.Paragraph>
) : (
<Form.Item
name="unit"
label="单位(可选填写)"
extra="可由入库明细带出;留空则用明细行的单位。"
rules={[
{
validator: async (_, val) => {
const merged =
String(val ?? '').trim() || String(confirmLine?.unit ?? '').trim();
if (!merged) {
return Promise.reject(
new Error('请填写单位,或在入库明细中维护该行单位以便带出'),
);
}
return Promise.resolve();
},
},
]}
>
<Input allowClear placeholder="留空则用明细带出" />
</Form.Item>
)}
<Form.Item
name="containerCode"
label="容器"
extra={
confirmLine?.inventoryKind === 2
? '空容器行:必选容器'
: '物料行:可选,绑定到库存容器编码'
}
rules={[
...(confirmLine?.inventoryKind === 2
? [{ required: true, message: '空容器行请选择容器' }]
: []),
]}
>
<InboundMasterSelect
placeholder="搜编码或名称"
fetchPage={fetchConfirmContainerPage}
/>
</Form.Item>
</Form>
</Modal>
</>
);
}