feat(库存管理): 重构库存页面并添加分组功能

添加vxe-table依赖支持表格分组和筛选
重构库存页面为左右布局,左侧仓库树右侧分组表格
实现按物料类型、名称、材质等多维度分组功能
添加全表搜索和列筛选功能
移除不再使用的stockIo组件和旧版库存页面
This commit is contained in:
砂糖
2026-04-03 11:30:19 +08:00
parent 74eae50ab0
commit e673dcbaeb
11 changed files with 1058 additions and 1166 deletions

View File

@@ -1,214 +0,0 @@
<template>
<div ref="chartContainer" style="height: 100%;"></div>
</template>
<script>
import * as echarts from 'echarts';
export default {
name: "MaterialBar",
props: {
// 图表高度
height: {
type: String,
default: '300px'
},
// 库存数据
stockData: {
type: Array,
default: () => []
},
// 选中的仓库ID
selectedWarehouseId: {
type: [String, Number],
default: null
},
// 仓库树数据
warehouseTreeData: {
type: Array,
default: () => []
}
},
data() {
return {
chart: null
};
},
watch: {
stockData: {
handler: 'updateChart',
deep: true
},
selectedWarehouseId: {
handler: 'updateChart',
immediate: true
}
},
mounted() {
this.initChart();
this.updateChart();
},
methods: {
initChart() {
if (this.chart) {
this.chart.dispose();
}
this.chart = echarts.init(this.$refs.chartContainer);
window.addEventListener('resize', this.handleResize);
},
handleResize() {
this.chart && this.chart.resize();
},
// 获取所有子仓库ID包括自身
getAllWarehouseIds(warehouseId) {
const ids = new Set();
const findChildren = (treeData, targetId) => {
for (const node of treeData) {
if (String(node.warehouseId) === String(targetId)) {
// 找到目标节点收集它和它的所有子节点的ID
const collectIds = (node) => {
ids.add(String(node.warehouseId));
if (node.children) {
node.children.forEach(child => collectIds(child));
}
};
collectIds(node);
return true;
}
if (node.children && findChildren(node.children, targetId)) {
return true;
}
}
return false;
};
if (warehouseId) {
findChildren(this.warehouseTreeData, warehouseId);
}
return ids;
},
// 处理数据获取前10的物料
processData() {
let filteredData;
if (this.selectedWarehouseId) {
// 获取选中仓库及其所有子仓库的ID
const warehouseIds = this.getAllWarehouseIds(this.selectedWarehouseId);
// 过滤属于这些仓库的数据
filteredData = this.stockData.filter(item => warehouseIds.has(String(item.warehouseId)));
} else {
filteredData = this.stockData;
}
// 按物料分组并汇总数量
const materialMap = new Map();
filteredData.forEach(item => {
const key = item.itemName;
const quantity = Number(item.quantity) || 0;
const currentQuantity = materialMap.get(key) || 0;
materialMap.set(key, currentQuantity + quantity);
});
// 转换为数组并排序
const sortedData = Array.from(materialMap.entries())
.map(([name, value]) => ({ name, value }))
.sort((a, b) => b.value - a.value)
.slice(0, 10); // 只取前10名
return sortedData;
},
updateChart() {
if (!this.chart) return;
const data = this.processData();
const names = data.map(item => item.name);
const values = data.map(item => item.value);
// 计算最大值,用于设置图表的最大刻度
const maxValue = Math.max(...values);
const interval = Math.ceil(maxValue / 5); // 将刻度分为5份
const option = {
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'shadow'
},
formatter: (params) => {
const data = params[0];
return `${data.name}<br/>数量: ${data.value}`;
}
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
xAxis: {
type: 'value',
boundaryGap: [0, 0.01],
max: Math.ceil(maxValue / interval) * interval,
interval: interval
},
yAxis: {
type: 'category',
data: names,
axisTick: {
alignWithLabel: true
},
axisLabel: {
formatter: (value) => {
// 如果名称太长,截断并添加省略号
if (value.length > 10) {
return value.substring(0, 10) + '...';
}
return value;
}
}
},
series: [
{
name: '数量',
type: 'bar',
data: values,
itemStyle: {
color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
{ offset: 0, color: '#83bff6' },
{ offset: 0.5, color: '#188df0' },
{ offset: 1, color: '#188df0' }
])
},
emphasis: {
itemStyle: {
color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
{ offset: 0, color: '#2378f7' },
{ offset: 0.7, color: '#2378f7' },
{ offset: 1, color: '#83bff6' }
])
}
},
label: {
show: true,
position: 'right',
formatter: '{c}'
}
}
]
};
this.chart.setOption(option, true);
}
},
beforeDestroy() {
window.removeEventListener('resize', this.handleResize);
if (this.chart) {
this.chart.dispose();
this.chart = null;
}
}
};
</script>

View File

@@ -1,269 +0,0 @@
<template>
<div ref="chartContainer" :style="{ height: '100%' }"></div>
</template>
<script>
import * as echarts from 'echarts';
export default {
name: "ReaTree",
props: {
// 图表高度
height: {
type: String,
default: '600px'
},
// 库存数据
stockData: {
type: Array,
default: () => []
},
// 仓库数据树
warehouseTreeData: {
type: Array,
default: () => []
}
},
data() {
return {
chart: null
};
},
mounted() {
this.initChart();
this.updateChartData();
},
watch: {
stockData: {
handler: 'updateChartData',
deep: true
},
warehouseTreeData: {
handler: 'updateChartData',
deep: true
}
},
methods: {
initChart() {
if (this.chart) {
this.chart.dispose();
}
this.chart = echarts.init(this.$refs.chartContainer);
window.addEventListener('resize', this.handleResize);
},
handleResize() {
this.chart && this.chart.resize();
},
// 创建树形数据
createTreeData() {
// 递归构建仓库树
const buildWarehouseTree = (warehouseNode, parentId = '') => {
const stocks = this.stockData.filter(stock => stock.warehouseId === warehouseNode.warehouseId);
const children = [];
let totalQuantity = 0;
// 添加库存物品
stocks.forEach(stock => {
const quantity = Number(stock.quantity) || 0;
totalQuantity += quantity;
children.push({
id: `${warehouseNode.warehouseId}_${stock.itemCode || stock.itemName}`,
name: stock.itemName,
value: quantity,
itemInfo: {
type: stock.itemType,
code: stock.itemCode,
unit: stock.unit,
batchNo: stock.batchNo
}
});
});
// 递归处理子仓库
if (warehouseNode.children && warehouseNode.children.length > 0) {
warehouseNode.children.forEach(child => {
const childNode = buildWarehouseTree(child, warehouseNode.warehouseId);
if (childNode.value > 0) {
children.push(childNode);
totalQuantity += childNode.value;
}
});
}
return {
id: String(warehouseNode.warehouseId),
name: warehouseNode.warehouseName,
value: totalQuantity,
warehouseInfo: {
code: warehouseNode.warehouseCode
},
children: children.length > 0 ? children : undefined
};
};
return this.warehouseTreeData.map(warehouse => buildWarehouseTree(warehouse));
},
// 获取层级样式配置
getLevelOption() {
return [
{
itemStyle: {
borderColor: '#555',
borderWidth: 4,
gapWidth: 3
},
emphasis: {
itemStyle: {
borderColor: '#333'
}
},
upperLabel: {
show: true,
height: 35,
fontSize: 16,
fontWeight: 'bold',
color: '#333'
}
},
{
itemStyle: {
borderColor: '#777',
borderWidth: 3,
gapWidth: 2
},
emphasis: {
itemStyle: {
borderColor: '#555'
}
},
upperLabel: {
show: true,
height: 28,
fontSize: 14
}
},
{
itemStyle: {
borderColor: '#999',
borderWidth: 2,
gapWidth: 1
},
emphasis: {
itemStyle: {
borderColor: '#777'
}
}
}
];
},
// 获取物料单位
getItemUnit(data) {
return data.itemInfo?.unit || '';
},
// 获取物料类型名称
getItemTypeName(type) {
const typeMap = {
raw_material: '原材料',
product: '产品',
semi_product: '半成品'
};
return typeMap[type] || type || '未分类';
},
// 更新图表数据
updateChartData() {
if (!this.chart) return;
const treeData = this.createTreeData();
const option = {
tooltip: {
formatter: (info) => {
const value = info.value || 0;
const treePath = info.treePathInfo || [];
let path = '';
for (let i = 0; i < treePath.length; i++) {
if (treePath[i].name) {
path += treePath[i].name;
if (i < treePath.length - 1) path += '/';
}
}
const content = [];
content.push(`<div class="tooltip-title">${echarts.format.encodeHTML(path)}</div>`);
content.push(`库存数量: ${echarts.format.addCommas(value)} ${this.getItemUnit(info.data)}`);
if (info.data.itemInfo) {
const item = info.data.itemInfo;
content.push(`物料类型: ${this.getItemTypeName(item.type)}`);
content.push(`物料编码: ${item.code || '无'}`);
if (item.batchNo) content.push(`批次号: ${item.batchNo}`);
}
return content.join('<br>');
}
},
series: [{
name: '库存',
type: 'treemap',
visibleMin: 300,
leafDepth: 2,
label: {
show: true,
fontSize: 12,
formatter: (params) => {
if (params.data.itemInfo) {
const unit = params.data.itemInfo.unit || '';
return `${params.name}\n${params.value}${unit}`;
}
return params.name;
},
ellipsis: true
},
upperLabel: {
show: true,
fontWeight: 'bold'
},
itemStyle: {
borderColor: '#fff',
borderWidth: 1
},
levels: this.getLevelOption(),
data: treeData
}]
};
this.chart.setOption(option, true);
},
// 高亮指定节点
highlightNode(id) {
if (!this.chart) return;
this.chart.dispatchAction({
type: 'highlight',
seriesIndex: 0,
targetNodeId: id
});
this.chart.dispatchAction({
type: 'treemapRootToNode',
seriesIndex: 0,
targetNodeId: id
});
}
},
beforeDestroy() {
window.removeEventListener('resize', this.handleResize);
if (this.chart) {
this.chart.dispose();
this.chart = null;
}
}
};
</script>
<style scoped>
.tooltip-title {
font-weight: bold;
margin-bottom: 5px;
}
</style>

View File

@@ -1,104 +0,0 @@
<template>
<div>
<el-form :model="form" label-width="120px">
<el-form-item label="单号">
<el-input v-model="form.stockIoCode" placeholder="请输入单号" />
</el-form-item>
<el-form-item label="类型">
<el-select v-model="form.ioType" placeholder="请选择类型">
<el-option label="入库" value="in" />
<el-option label="出库" value="out" />
</el-select>
</el-form-item>
<el-form-item label="业务类型">
<el-select v-model="form.bizType" placeholder="请选择业务类型">
<el-option
v-for="dict in dict.type.stock_biz_type"
:key="dict.value"
:label="dict.label"
:value="dict.value"
/>
</el-select>
</el-form-item>
<el-form-item label="备注">
<el-input v-model="form.remark" placeholder="请输入备注" />
</el-form-item>
</el-form>
<KLPTable :data="stockBoxData" style="width: 100%">
<el-table-column type="selection" width="55" />
<el-table-column prop="warehouseName" label="仓库" />
<el-table-column prop="itemName" label="物料" />
<el-table-column prop="quantity" label="数量" width="200">
<template slot-scope="scope">
<el-input-number :controls=false controls-position="right" v-model="scope.row.count" :min="0" :step="1" :max="scope.row.quantity" />
</template>
</el-table-column>
<el-table-column prop="unit" label="单位" />
<el-table-column label="操作" width="100">
<template slot-scope="scope">
<el-button type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
</template>
</el-table-column>
</KLPTable>
<div style="text-align: right; margin-top: 10px;">
<el-button type="danger" @click="handleDeleteAll">清空</el-button>
<el-button type="primary" @click="handleGenerateBill">生成单据</el-button>
</div>
</div>
</template>
<script>
export default {
name: 'StockIo',
dicts: ['stock_biz_type'],
data() {
return {
stockBoxData: [],
form: {
stockIoCode: '',
ioType: 'in',
bizType: 'stock_io',
remark: '',
}
}
},
props: {
data: {
type: Array,
default: () => []
}
},
watch: {
data: {
handler(newVal) {
this.stockBoxData = newVal.map(item => ({
...item,
count: 0,
}));
},
deep: true,
immediate: true
}
},
methods: {
handleDelete(row) {
this.stockBoxData = this.stockBoxData.filter(item => item.stockId !== row.stockId);
},
handleDeleteAll() {
this.stockBoxData = [];
},
handleGenerateBill() {
this.$emit('generateBill', {
...this.form,
details: this.stockBoxData.map(item => ({
...item,
status: 0,
quantity: item.count,
batchNo: item.batchNo,
remark: item.remark
}))
});
}
}
}
</script>

View File

@@ -1,406 +0,0 @@
<template>
<div class="chart-container">
<div v-if="isDrilled" class="drill-header">
<button @click="backToSummary" class="back-btn"> 返回汇总</button>
</div>
<div id="trendChart" style="width: 100%; height: 100%;"></div>
</div>
</template>
<script>
import { listStockLog } from '@/api/wms/stockLog';
import * as echarts from 'echarts';
import Resize from './resize';
export default {
name: 'TrendChart',
mixins: [Resize],
data() {
return {
trendChart: null,
allData: [], // 存储原始数据
dailySummary: {}, // 存储按天汇总数据
isDrilled: false, // 是否处于钻取状态
currentDrillDate: '' // 当前钻取的日期
};
},
props: {
timeRange: {
required: true,
type: Array,
},
warehouseId: {
required: false,
type: String,
},
},
mounted() {
this.initChart();
this.getTrendData();
},
watch: {
timeRange: {
handler: function() {
// 当时间范围变化时,重置钻取状态
this.isDrilled = false;
this.currentDrillDate = '';
this.getTrendData();
},
immediate: true,
},
warehouseId: function() {
this.isDrilled = false;
this.currentDrillDate = '';
this.getTrendData();
},
},
methods: {
initChart() {
this.trendChart = echarts.init(document.getElementById('trendChart'));
// 绑定双击事件用于数据钻取
this.trendChart.on('dblclick', (params) => {
// 如果点击的是坐标轴空白区域,返回汇总视图
if (params.componentType === 'grid') {
if (this.isDrilled) {
this.backToSummary();
}
return;
}
// 如果是柱状图元素,进行钻取
if (params.componentType === 'series' &&!this.isDrilled) {
const dateIndex = params.dataIndex;
const sortedDates = Object.keys(this.dailySummary).sort((a, b) => new Date(a) - new Date(b));
const drillDate = sortedDates[dateIndex];
this.drillDownToDate(drillDate);
}
});
window.addEventListener('resize', () => {
this.trendChart.resize();
});
},
getTrendData() {
const { timeRange, warehouseId } = this;
const params = {
startTime: timeRange? timeRange[0] + ' 00:00:00' : '',
endTime: timeRange? timeRange[1] + ' 23:59:59' : '',
warehouseId,
pageSize: 999999,
pageNum: 1,
};
listStockLog(params).then((res) => {
this.allData = res.rows;
this.processAndRenderData();
});
},
processAndRenderData() {
// 按日期分组统计
this.dailySummary = {};
this.allData.forEach((item) => {
const dateArr = item.changeTime.split(' ')[0].split('-');
const year = dateArr[0];
const month = dateArr[1].padStart(2, '0');
const day = dateArr[2].padStart(2, '0');
const date = `${year}-${month}-${day}`;
const changeQty = parseFloat(item.changeQty);
if (!this.dailySummary[date]) {
this.dailySummary[date] = {
total: 0,
items: []
};
}
this.dailySummary[date].total += changeQty;
this.dailySummary[date].items.push(item);
});
// 根据当前状态渲染不同视图
if (this.isDrilled) {
this.renderDetailChart(this.currentDrillDate);
} else {
this.renderSummaryChart();
}
},
renderSummaryChart() {
const sortedDates = Object.keys(this.dailySummary).sort((a, b) => new Date(a) - new Date(b));
const categories = sortedDates;
const placeholderData = [0];
const incomeData = [];
const expensesData = [];
let accumulatedValue = 0;
sortedDates.forEach((date) => {
const dailyChange = this.dailySummary[date].total;
accumulatedValue += dailyChange;
placeholderData.push(accumulatedValue);
if (dailyChange > 0) {
incomeData.push(dailyChange);
expensesData.push('-');
} else {
incomeData.push('-');
expensesData.push(Math.abs(dailyChange));
}
});
const option = {
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'shadow',
},
formatter: (params) => {
let tar;
if (params[1] && params[1].value!== '-') {
tar = params[1];
} else {
tar = params[2];
}
if (tar) {
const date = sortedDates[tar.dataIndex];
const itemCount = this.dailySummary[date].items.length;
return `
<div>日期: ${date}</div>
<div>当日库存变化: ${this.dailySummary[date].total}</div>
<div>累计库存变化: ${placeholderData[tar.dataIndex + 1]}</div>
<div>操作记录: ${itemCount} 条</div>
<div style="color:#888">双击查看明细</div>
`;
}
return '';
},
},
legend: {
data: ['入库', '出库'],
top: 30,
},
grid: {
left: '3%',
right: '4%',
bottom: '15%',
containLabel: true,
},
xAxis: {
type: 'category',
data: categories,
axisLabel: {
rotate: 45,
interval: 0,
fontSize: 12,
},
},
yAxis: {
type: 'value',
name: '库存变化量',
nameLocation:'middle',
nameGap: 30,
},
series: [
{
name: '占位',
type: 'bar',
stack: 'Total',
silent: true,
itemStyle: {
color: 'transparent',
},
data: placeholderData.slice(0, -1),
},
{
name: '入库',
type: 'bar',
stack: 'Total',
label: {
show: true,
position: 'top',
formatter: (params) => params.value!== '-'? `+${params.value}` : '',
},
itemStyle: {
color: '#52c41a',
},
data: incomeData,
},
{
name: '出库',
type: 'bar',
stack: 'Total',
label: {
show: true,
position: 'bottom',
formatter: (params) => params.value!== '-'? `-${params.value}` : '',
},
itemStyle: {
color: '#f5222d',
},
data: expensesData,
},
],
};
this.trendChart.setOption(option);
},
// 钻取到指定日期的明细
drillDownToDate(date) {
this.isDrilled = true;
this.currentDrillDate = date;
this.renderDetailChart(date);
},
// 渲染明细图表
renderDetailChart(date) {
const dayItems = this.dailySummary[date].items.sort((a, b) => new Date(a.changeTime) - new Date(b.changeTime));
// 准备明细数据
const timeLabels = dayItems.map(item => {
const timePart = item.changeTime.split(' ')[1];
return timePart.slice(0, 5); // 只显示时分
});
const values = dayItems.map(item => {
const qty = parseFloat(item.changeQty);
return {
value: qty,
itemStyle: {
color: qty > 0? '#52c41a' : '#f5222d'
},
label: {
show: true,
position: qty > 0? 'top' : 'bottom',
formatter: `${qty > 0? '+' : ''}${qty}`
}
};
});
// 计算累积值用于阶梯效果
const bases = [0];
let accumulated = 0;
dayItems.forEach((item, index) => {
if (index > 0) {
accumulated += parseFloat(dayItems[index - 1].changeQty);
bases.push(accumulated);
}
});
const option = {
title: {
text: `${date} 库存变动明细`,
left: 'center'
},
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'shadow'
},
formatter: (params) => {
const item = dayItems[params[0].dataIndex];
return `
<div>时间: ${item.changeTime}</div>
<div>类型: ${item.changeType}</div>
<div>物料ID: ${item.itemId}</div>
<div>变化量: ${item.changeQty}</div>
<div>操作后数量: ${item.afterQty}</div>
${item.remark? `<div>备注: ${item.remark}</div>` : ''}
`;
}
},
grid: {
left: '5%',
right: '4%',
bottom: '15%',
containLabel: true
},
xAxis: {
type: 'category',
data: timeLabels,
axisLabel: {
rotate: 45,
interval: 0
},
name: '时间'
},
yAxis: {
type: 'value',
name: '数量'
},
series: [
{
name: '占位',
type: 'bar',
stack: 'Detail',
silent: true,
itemStyle: {
color: 'transparent'
},
data: bases
},
{
name: '变动',
type: 'bar',
stack: 'Detail',
data: values,
barWidth: '60%'
}
]
};
this.trendChart.setOption(option);
},
// 返回汇总视图
backToSummary() {
this.isDrilled = false;
this.currentDrillDate = '';
this.renderSummaryChart();
},
},
beforeDestroy() {
window.removeEventListener('resize', () => {
this.trendChart.resize();
});
if (this.trendChart) {
this.trendChart.dispose();
}
},
};
</script>
<style scoped>
.chart-container {
position: relative;
}
.drill-header {
padding: 10px 0;
display: flex;
align-items: center;
gap: 10px;
}
.back-btn {
padding: 4px 10px;
background-color: #1890ff;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
display: flex;
align-items: center;
gap: 5px;
}
.back-btn:hover {
background-color: #096dd9;
}
.drill-header h3 {
margin: 0;
font-size: 16px;
color: #333;
}
</style>