lunanting 55b755c1d9 feat: 新增「缺货补货监控」看板(拣货位缺货 → 从存货位补货)
数据源:聚水潭「箱及仓位库存」rpt.jst_packInventoryInfo(副本里是视图,
按 SKU+货位聚合单次 35~45s,因此服务端缓存 10 分钟 + 启动预热)。

口径:
- 拣货位:按业务导入的货位清单判定(本地表 bin_replenish_pick_bin,按仓库隔离);
  副本没有货位类型主数据,未导入时回退为 pack_type='Bin' 的记录,页面明确标注。
- 拣货位库存 / 存货位库存 / 现有库存合计;
- 目标库存 = max(10, 近15天日销 × 目标天数(默认7));
- 建议补货量 = min(存货位库存, 目标 − 拣货位库存);
- 状态:拣货位缺货 / 无货可补 / 拣货位偏低 / 未设拣货位 / 正常。
  「未设拣货位」单列,避免把整箱直发商品误报成缺货。

后端:binReplenishService + binReplenishSchema + /api/bin-replenish
(list / export / pick-bins GET-POST-DELETE / ping),建表与预热挂在 localSchema。
前端:/planning/operation/bin-replenish-monitor 页面、侧栏入口、页面权限注册,
含 KPI 卡、状态分段筛选、关键字搜索、目标天数、货位清单导入/清除、服务端导出。
2026-10-22 11:08:20 +08:00

518 lines
18 KiB
JavaScript
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, useEffect, useMemo, useRef, useState } from 'react';
import {
Alert, Button, Empty, Input, InputNumber, Popconfirm, Segmented, Select, Spin, Table, Tag, Tooltip, Upload,
message,
} from 'antd';
import {
DeleteOutlined, DownloadOutlined, InfoCircleOutlined, ReloadOutlined, SearchOutlined, UploadOutlined,
} from '@ant-design/icons';
import {
clearPickBins, exportBinReplenish, getBinReplenishList, importPickBins,
} from '../../api/binReplenish';
import { downloadBlobAsFile, readBlobErrorMessage } from '../../utils/tableExport';
import { SycmPage } from '../../components/Common';
import './style.css';
const num = (value) => (value === null || value === undefined || value === ''
? '--'
: Number(value).toLocaleString('zh-CN'));
const STATUS_TAGS = {
pickout: { color: 'red', label: '拣货位缺货' },
empty: { color: 'default', label: '无货可补' },
low: { color: 'orange', label: '拣货位偏低' },
nopick: { color: 'blue', label: '未设拣货位' },
ok: { color: 'green', label: '正常' },
};
const STATUS_OPTIONS = [
{ label: '待补货', value: 'replenish' },
{ label: '无货可补', value: 'empty' },
{ label: '未设拣货位', value: 'nopick' },
{ label: '全部', value: 'all' },
];
const DEFAULT_TARGET_DAYS = 7;
const renderBinTags = (bins = [], emptyText = '未维护', limit = 3) => {
if (!bins.length) return <span className="brp-muted">{emptyText}</span>;
const visible = bins.slice(0, limit);
const rest = bins.length - visible.length;
return (
<span className="brp-bins">
{visible.map((item) => (
<Tag key={`${item.bin}-${item.qty}`} className={`brp-bin${item.qty > 0 ? '' : ' is-zero'}`}>
{item.bin}
<b>{num(item.qty)}</b>
</Tag>
))}
{rest > 0 ? (
<Tooltip title={bins.slice(limit).map((item) => `${item.bin}(${num(item.qty)})`).join('、')}>
<Tag className="brp-bin brp-bin--more">+{rest}</Tag>
</Tooltip>
) : null}
</span>
);
};
const BinReplenishMonitor = () => {
const [warehouse, setWarehouse] = useState('cuiqiao');
const [status, setStatus] = useState('replenish');
const [keyword, setKeyword] = useState('');
const [targetDays, setTargetDays] = useState(DEFAULT_TARGET_DAYS);
const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState(50);
const [loading, setLoading] = useState(true);
const [refreshing, setRefreshing] = useState(false);
const [error, setError] = useState('');
const [data, setData] = useState({
rows: [], total: 0, summary: {}, warehouse: null, warehouses: [], pickBinMeta: null, updatedAt: '', cacheHit: false,
});
const [importing, setImporting] = useState(false);
const keywordTimer = useRef(null);
const load = useCallback(async (options = {}) => {
const isRefresh = options.refresh === true;
if (isRefresh) setRefreshing(true);
else setLoading(true);
setError('');
try {
const response = await getBinReplenishList({
warehouse,
status,
keyword,
targetDays,
page: options.page || page,
pageSize: options.pageSize || pageSize,
refresh: isRefresh ? 'true' : undefined,
});
const payload = response?.data?.data || response?.data || {};
setData({
rows: payload.rows || [],
total: payload.total || 0,
summary: payload.summary || {},
warehouse: payload.warehouse || null,
warehouses: payload.warehouses || [],
pickBinMeta: payload.pickBinMeta || null,
updatedAt: payload.updatedAt || '',
cacheHit: Boolean(payload.cacheHit),
});
if (isRefresh) message.success('已重新回源取数');
} catch (err) {
setError(err?.message || '加载失败');
} finally {
setLoading(false);
setRefreshing(false);
}
}, [warehouse, status, keyword, targetDays, page, pageSize]);
useEffect(() => {
load();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [warehouse, status, page, pageSize, targetDays]);
useEffect(() => {
if (keywordTimer.current) clearTimeout(keywordTimer.current);
keywordTimer.current = setTimeout(() => {
setPage(1);
load({ page: 1 });
}, 400);
return () => { if (keywordTimer.current) clearTimeout(keywordTimer.current); };
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [keyword]);
const summary = data.summary;
const pickBinMeta = data.pickBinMeta || {};
const usingFallback = pickBinMeta.source !== 'import';
const metrics = useMemo(() => ([
{
key: 'pickout',
tone: 'red',
label: '拣货位缺货',
value: summary.pickout || 0,
unit: '个 SKU',
foot: `可立即从存货位补 ${num(summary.suggestQtyTotal)} 件`,
tip: '拣货位库存为 0、存货位还有货:需要把存货位的库存补到拣货位',
},
{
key: 'empty',
tone: 'grey',
label: '无货可补',
value: summary.empty || 0,
unit: '个 SKU',
foot: '拣货位与存货位都为 0,需采购',
tip: '拣货位库存为 0,且仓库里已经没有该商品的存货,补货要走走采购',
},
{
key: 'low',
tone: 'orange',
label: '拣货位偏低',
value: summary.low || 0,
unit: '个 SKU',
foot: `低于 ${targetDays} 天销量目标`,
tip: `拣货位还有货,但低于目标库存(= 近15天日销 × ${targetDays},最少 ${10} 件)`,
},
{
key: 'qty',
tone: 'blue',
label: '建议补货合计',
value: summary.suggestQtyTotal || 0,
unit: '件',
foot: `覆盖 ${num(summary.withPickSlot)} 个有拣货位的 SKU`,
tip: '建议补货量 = min(存货位库存, 目标拣货位库存 − 当前拣货位库存)',
},
]), [summary, targetDays]);
const handleExport = async () => {
try {
const response = await exportBinReplenish({ warehouse, status, keyword, targetDays });
downloadBlobAsFile(response.data, `${(data.warehouse || {}).shortName || '仓库'}缺货补货监控.xlsx`);
} catch (error_) {
const text = await readBlobErrorMessage(error_);
message.error(text || '导出失败');
}
};
const handleImport = async (file) => {
setImporting(true);
try {
const response = await importPickBins(file, warehouse);
const result = response?.data?.data || {};
message.success(`已导入 ${result.importedRows || 0} 个拣货位,正在重新取数…`);
await load({ refresh: true, page: 1 });
setPage(1);
} catch (error_) {
message.error(error_?.message || '导入失败');
} finally {
setImporting(false);
}
return false;
};
const handleClear = async () => {
try {
await clearPickBins(warehouse);
message.success('已清除货位清单,回到「货位散件记录」回退口径');
setPage(1);
await load({ refresh: true, page: 1 });
} catch (error_) {
message.error(error_?.message || '清除失败');
}
};
const columns = [
{
title: '状态',
dataIndex: 'status',
width: 112,
fixed: 'left',
render: (value) => {
const tag = STATUS_TAGS[value] || STATUS_TAGS.ok;
return <Tag color={tag.color} className="brp-status-tag">{tag.label}</Tag>;
},
},
{
title: '商品编码',
dataIndex: 'skuId',
width: 175,
render: (value, row) => (
<div className="brp-sku">
<span className="brp-sku__code">{value}</span>
{row.supplier ? <span className="brp-sku__supplier">{row.supplier}</span> : null}
</div>
),
},
{ title: '品名', dataIndex: 'productName', width: 260, ellipsis: true },
{
title: '拣货位(货位号 / 数量)',
dataIndex: 'pickBins',
width: 300,
render: (bins, row) => (row.hasPickSlot ? renderBinTags(bins) : <span className="brp-muted">未维护拣货位</span>),
},
{
title: '拣货位库存',
dataIndex: 'pickQty',
width: 108,
align: 'right',
render: (value) => (
<span className={Number(value) <= 0 ? 'brp-qty brp-qty--zero' : 'brp-qty'}>{num(value)}</span>
),
},
{
title: '存货位库存',
dataIndex: 'storageQty',
width: 108,
align: 'right',
render: (value) => <span className="brp-qty">{num(value)}</span>,
},
{
title: '建议补货',
dataIndex: 'suggestQty',
width: 110,
align: 'right',
render: (value) => (
<span className={Number(value) > 0 ? 'brp-qty brp-qty--suggest' : 'brp-qty brp-qty--zero'}>
{num(value)}
</span>
),
},
{
title: '目标拣货位',
dataIndex: 'targetQty',
width: 108,
align: 'right',
render: (value) => <span className="brp-qty brp-qty--muted">{num(value)}</span>,
},
{
title: '存货位(前 5 个 / 数量)',
dataIndex: 'storageBins',
width: 300,
render: (bins) => renderBinTags(bins, '无存货', 3),
},
{
title: '近15天日销',
dataIndex: 'avgSale',
width: 108,
align: 'right',
render: (value) => <span className="brp-qty brp-qty--muted">{num(value)}</span>,
},
{
title: '现有库存',
dataIndex: 'totalQty',
width: 100,
align: 'right',
render: (value) => <span className="brp-qty">{num(value)}</span>,
},
];
return (
<SycmPage className="brp-page">
<div className="brp-hero">
<div className="brp-hero__main">
<h1 className="brp-hero__title">缺货补货监控</h1>
<p className="brp-hero__desc">
盯的是<b>拣货位</b>:拣货位没货就拣不出来,需要从<b>存货位</b>把货补过去。
状态、建议补货量都按当前库存实时算,数据来自聚水潭「箱及仓位库存」。
</p>
</div>
<div className="brp-hero__meta">
<div>
仓库:<b>{(data.warehouse || {}).name || '简尚-崔桥工厂仓'}</b>
</div>
<div>
拣货位口径:
<b className={usingFallback ? '' : 'brp-ok'}>
{usingFallback ? '默认拣选位(Bin 且非存货位)' : `导入清单 ${num(pickBinMeta.count)} 个`}
</b>
</div>
<div>
取数时间:<b>{data.updatedAt ? new Date(data.updatedAt).toLocaleString('zh-CN') : '--'}</b>
{data.cacheHit ? <span className="brp-muted">(缓存)</span> : null}
</div>
<div>
共 <b>{num(summary.skuTotal)}</b> 个 SKU,其中未设拣货位{' '}
<b>{num(summary.nopick)}</b> 个(不参与待补货)
</div>
</div>
</div>
<div className="brp-metrics">
{metrics.map((item) => (
<div key={item.key} className={`brp-metric brp-metric--${item.tone}`}>
<Tooltip title={item.tip}>
<div className="brp-metric__label">
{item.label}
<InfoCircleOutlined className="brp-metric__info" />
</div>
</Tooltip>
<div className="brp-metric__value">
{num(item.value)}
<span className="brp-metric__unit">{item.unit}</span>
</div>
<div className="brp-metric__foot">{item.foot}</div>
</div>
))}
</div>
<div className="brp-toolbar">
<span className="brp-toolbar__field">
<span className="brp-toolbar__label">仓库</span>
<Select
value={warehouse}
onChange={(value) => { setWarehouse(value); setPage(1); }}
style={{ width: 210 }}
options={(data.warehouses || []).map((item) => ({
value: item.key,
label: item.name,
}))}
/>
</span>
<span className="brp-toolbar__field">
<span className="brp-toolbar__label">范围</span>
<Segmented
value={status}
onChange={(value) => { setStatus(value); setPage(1); }}
options={STATUS_OPTIONS.map((item) => ({
...item,
label: item.value === 'replenish'
? `${item.label} ${num((summary.pickout || 0) + (summary.low || 0))}`
: item.value === 'empty'
? `${item.label} ${num(summary.empty || 0)}`
: item.label,
}))}
/>
</span>
<span className="brp-toolbar__field">
<span className="brp-toolbar__label">目标天数(天)</span>
<InputNumber
min={1}
max={90}
value={targetDays}
onChange={(value) => { setTargetDays(Number(value) || DEFAULT_TARGET_DAYS); setPage(1); }}
style={{ width: 90 }}
/>
</span>
<Input
allowClear
value={keyword}
onChange={(event) => setKeyword(event.target.value)}
placeholder="搜商品编码 / 品名 / 供应商"
prefix={<SearchOutlined />}
style={{ width: 260 }}
/>
<span className="brp-toolbar__spacer" />
<Upload
accept=".xlsx,.xls,.csv,.txt"
showUploadList={false}
beforeUpload={handleImport}
disabled={importing}
>
<Button icon={<UploadOutlined />} loading={importing}>导入货位清单</Button>
</Upload>
<Button icon={<DownloadOutlined />} onClick={handleExport}>导出</Button>
<Button
type="primary"
icon={<ReloadOutlined />}
loading={refreshing}
onClick={() => load({ refresh: true })}
>
刷新数据
</Button>
</div>
{usingFallback ? (
<Alert
type="info"
showIcon
className="brp-alert"
message="拣货位口径:默认拣选位(pack_type = Bin 且非存货位),与「拣选库位动销分析」一致"
description="这是系统当前能确定的最准口径。如果业务另有一份拣货位清单,可以上传覆盖(只放货位号,如 XA01-01-11),上传后按清单判定,其余货位都算存货位。"
action={(
<Upload accept=".xlsx,.xls,.csv,.txt" showUploadList={false} beforeUpload={handleImport}>
<Button size="small" type="primary">上传清单</Button>
</Upload>
)}
/>
) : (
<Alert
type="success"
showIcon
className="brp-alert"
message={`拣货位口径:导入清单(${num(pickBinMeta.count)} 个货位)`}
description={`最近导入:${pickBinMeta.lastImport?.fileName || '—'} · ${pickBinMeta.lastImport?.importedRows || 0} 个货位 · ${pickBinMeta.lastImport?.importedAt ? new Date(pickBinMeta.lastImport.importedAt).toLocaleString('zh-CN') : '—'}。清单变更后重新上传即可覆盖。`}
action={(
<Popconfirm
title="清除后回到「货位散件记录」回退口径,确定吗?"
onConfirm={handleClear}
okText="清除"
cancelText="取消"
>
<Button size="small" danger icon={<DeleteOutlined />}>清除清单</Button>
</Popconfirm>
)}
/>
)}
{error ? (
<Alert
type="error"
showIcon
className="brp-alert"
message={error}
action={<Button size="small" onClick={() => load()}>重试</Button>}
/>
) : null}
<Spin
spinning={loading}
tip="正在从仓位库存视图聚合,首次约 30~60 秒"
wrapperClassName="brp-table-spin"
>
<Table
rowKey="skuId"
size="small"
className="brp-table"
columns={columns}
dataSource={data.rows}
scroll={{ x: 1900 }}
locale={{
emptyText: (
<Empty
description={status === 'replenish'
? '当前没有需要补货的拣货位'
: '没有符合条件的商品'}
/>
),
}}
pagination={{
current: page,
pageSize,
total: data.total,
showSizeChanger: true,
pageSizeOptions: ['20', '50', '100', '200'],
showTotal: (total) => `共 ${total} 个 SKU`,
onChange: (nextPage, nextSize) => {
setPage(nextPage);
setPageSize(nextSize);
},
}}
/>
</Spin>
<div className="brp-notes">
<div className="brp-notes__title">数据来源与口径说明</div>
<ul>
<li>
<b>库存</b>:聚水潭「箱及仓位库存」(rpt.jst_packInventoryInfo),按商品编码 + 货位汇总。
「拣货位库存」= 拣货位上的数量合计;「存货位库存」= 其余货位(含整箱、未分箱)的数量合计。
</li>
<li>
<b>拣货位</b>:副本没有货位类型字段,按导入的货位清单判定;未导入时回退为
pack_type = Bin 的记录(页面顶部会标出当前口径)。
</li>
<li>
<b>目标库存</b>:max(10, 近15天日销 × {targetDays});日销取 rpt.pm_stockMonitor 同仓最新快照的
fifteenAvgSale,取不到的按 10 件兜底。
</li>
<li>
<b>建议补货量</b>:min(存货位库存, 目标拣货位库存 − 当前拣货位库存),只在「拣货位缺货 / 偏低」时给数字;
「无货可补」表示拣货位和存货位都没货,要走走采购,不是仓库内部调拨。
</li>
<li>
<b>未设拣货位</b>:该 SKU 在拣货位清单里一个货位都没有(多为整箱直发、或还没维护拣货位)。
这类不算「拣货位缺货」,不进待补货清单,可在「未设拣货位」页签单独核对。
</li>
<li>
<b>时效</b>:仓位库存视图单次聚合约 35~45 秒,服务端缓存 10 分钟(启动时已预热);
点「刷新数据」会强制回源,需要等半分钟左右。
</li>
</ul>
</div>
</SycmPage>
);
};
export default BinReplenishMonitor;