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

@@ -541,7 +541,13 @@ export default {
// 清理空格和换行
content = content.trim();
// 如果不是以大写汉字数字开头,添加一个中文字符的缩进
if (content) {
// 检查是否以大写汉字数字开头(一、二、三、四、五、六、七、八、九、十)
const chineseNumberRegex = /^[一二三四五六七八九十]+、/;
if (!chineseNumberRegex.test(content)) {
content = ' ' + content; // 使用全角空格作为中文字符缩进
}
pContents.push(content);
}
}
@@ -551,7 +557,13 @@ export default {
let textContent = htmlContent.replace(/<[^>]*>/g, '');
textContent = textContent.replace(/&nbsp;/g, ' ').trim();
// 如果不是以大写汉字数字开头,添加一个中文字符的缩进
if (textContent) {
// 检查是否以大写汉字数字开头(一、二、三、四、五、六、七、八、九、十)
const chineseNumberRegex = /^[一二三四五六七八九十]+、/;
if (!chineseNumberRegex.test(textContent)) {
textContent = ' ' + textContent; // 使用全角空格作为中文字符缩进
}
pContents.push(textContent);
}
}

View File

@@ -1,167 +0,0 @@
<template>
<div style="display: flex; height: calc(100vh - 100px);">
<!-- 左侧导航树 -->
<div style="width: 280px; min-width: 200px; border-right: 1px solid #eee; padding: 10px 0;">
<el-tree :data="warehouseTreeData" node-key="warehouseId" :props="treeProps" highlight-current
@node-click="handleTreeNodeClick" :default-expand-all="true" style="height: 100%; overflow-y: auto;" />
</div>
<!-- 右侧图表 -->
<div style="flex: 1; height: calc(100vh - 100px); overflow-y: scroll; overflow-x: hidden;">
<el-row :gutter="10">
<el-col :span="12">
<el-card>
<template #header>
物料统计TOP10
</template>
<div style="height: 300px;">
<ChartWrapper>
<material-bar ref="materialBar" :stock-data="stockData"
:selected-warehouse-id="currentTreeNode ? currentTreeNode.warehouseId : null"
:warehouse-tree-data="warehouseTreeData" />
</ChartWrapper>
</div>
</el-card>
</el-col>
<el-col :span="12">
<el-card>
<template #header>
变动趋势
<el-date-picker style="float: right;" v-model="defaultTimeRange" type="daterange" range-separator="至"
start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd" />
</template>
<div style="height: 300px;">
<ChartWrapper>
<TrendChart ref="trendChart" :warehouseId="currentTreeNode ? currentTreeNode.warehouseId : null"
:time-range="defaultTimeRange"></TrendChart>
</ChartWrapper>
</div>
</el-card>
</el-col>
</el-row>
<el-row>
<el-col :span="24">
<el-card>
<template #header>
仓库库存
</template>
<div style="height: 600px;">
<ChartWrapper>
<rea-tree ref="reaTree" :stock-data="stockData" :warehouse-tree-data="warehouseTreeData" height="600px" />
</ChartWrapper>
</div>
</el-card>
</el-col>
</el-row>
</div>
</div>
</template>
<script>
import { listStock } from "@/api/wms/stock";
import { listWarehouse } from "@/api/wms/warehouse";
import ReaTree from './panels/reattree.vue';
import MaterialBar from './panels/bar.vue';
import TrendChart from './panels/trendChart.vue';
import ChartWrapper from '@/components/ChartWrapper/index.vue';
export default {
name: "StockBox",
components: {
ReaTree,
MaterialBar,
TrendChart,
ChartWrapper
},
data() {
return {
stockData: [],
warehouseData: [],
warehouseTreeData: [],
treeProps: {
label: 'warehouseName',
children: 'children',
isLeaf: 'isLeaf',
id: 'id'
},
currentTreeNode: null,
defaultTimeRange: [
new Date(new Date().setDate(new Date().getDate() - 30)).toISOString().split('T')[0],
new Date().toISOString().split('T')[0]
]
};
},
mounted() {
this.loadData();
},
methods: {
async loadData() {
try {
const [warehouseRes, stockRes] = await Promise.all([
listWarehouse(),
listStock({ pageNum: 1, pageSize: 9999 })
]);
// 处理树结构
this.warehouseTreeData = this.handleTree(warehouseRes.data, 'warehouseId', 'parentId');
this.stockData = stockRes.rows;
} catch (error) {
console.error('加载数据失败:', error);
this.$message.error('库存数据加载失败');
}
},
// 处理树结构
handleTree(data, id, parentId) {
if (!Array.isArray(data)) {
console.error('handleTree: data is not array', data);
return [];
}
const map = {};
const tree = [];
// 创建节点映射
data.forEach(item => {
map[item[id]] = { ...item, children: [] };
});
// 构建树结构
data.forEach(item => {
const node = map[item[id]];
if (!item[parentId] || item[parentId] === 0) {
tree.push(node);
} else if (map[item[parentId]]) {
map[item[parentId]].children.push(node);
}
});
return tree;
},
// 刷新数据
refresh() {
this.loadData();
},
// 导航树点击事件
handleTreeNodeClick(node) {
this.currentTreeNode = node;
if (node && node.warehouseId) {
this.$refs.reaTree.highlightNode(node.warehouseId);
}
}
}
};
</script>
<style scoped>
/* 图表容器样式 */
.treemap-container {
width: 100%;
height: 100%;
min-height: 600px;
}
.el-row {
margin: 10px !important;
}
</style>

View File

@@ -0,0 +1,721 @@
<template>
<div class="app-container stock-layout">
<!-- 左侧树结构 -->
<div class="stock-tree-col">
<el-card shadow="never" class="stock-tree-card">
<div slot="header" class="stock-tree-title">
<div style="display: flex; align-items: center; justify-content: space-between;">
<span>
仓库结构
</span>
<el-select v-model="warehouseType" placeholder="请选择仓库类别" style="width: 50%;">
<el-option label="真实库区" value="real" />
<el-option label="逻辑库位" value="virtual" />
</el-select>
</div>
</div>
<WarehouseTree @node-click="handleTreeSelect" :warehouseType="warehouseType" :showEmpty="true" />
</el-card>
</div>
<!-- 右侧内容 -->
<div class="stock-main-col">
<!-- <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
<MaterialSelect :itemType.sync="queryParams.itemType" :itemId.sync="queryParams.itemId" @change="getList" />
<el-form-item>
<el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
<el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
<el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
</el-form-item>
</el-form> -->
<!-- 上方增加分组信息会影响下面的表格显示, 可以添加多级分组例如按照itemType按照itemName, 按照材质material, 按照规格specification, 按照厂家manufacturer -->
<div class="group-controls">
<el-form :model="groupForm" size="small" :inline="true">
<el-form-item label="分组维度">
<el-select v-model="groupForm.groupingCriteria" multiple placeholder="请选择分组维度" style="width: 300px;">
<el-option label="物料类型" value="itemType" />
<el-option label="物料名称" value="itemName" />
<el-option label="材质" value="material" />
<el-option label="规格" value="specification" />
<el-option label="厂家" value="manufacturer" />
<el-option label="镀层质量" value="zincLayer" />
</el-select>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="getList">应用分组</el-button>
<el-button @click="resetGroup">重置分组</el-button>
</el-form-item>
</el-form>
</div>
<vxe-toolbar :refresh="{query: reload}" export custom>
<template v-slot:buttons>
<!-- 统计数据{{ total }} -->
<span style="margin-left: 10px; font-weight: bold;">统计数据{{ totalQuantity }}</span>
<!-- <vxe-input v-model.lazy="filterName" type="search" placeholder="全表搜索" style="width: 200px; margin-left: 10px;"></vxe-input> -->
<!-- <vxe-button @click="$refs.xTree.setAllTreeExpand(true)">展开所有</vxe-button>
<vxe-button @click="$refs.xTree.clearTreeExpand()">关闭所有</vxe-button> -->
<vxe-button @click="clearFilterEvent">清除所有筛选</vxe-button>
</template>
</vxe-toolbar>
<div style="height: calc(100vh - 260px);">
<vxe-table ref="xTree" :loading="loading" :data="list" size="mini" :tree-config="tableTreeConfig"
max-height="100%" @row-click="handleTableRowClick" :export-config="{}">
<vxe-table-column field="itemType" title="物料类型" align="center" :formatter="formatterItemType" tree-node sortable :filters="[{label: '产品', value: 'product'}, {label: '原料', value: 'raw_material'}]" :filter-method="filterItemTypeMethod">
<template v-slot="{ row }">
<span v-if="row.itemType">{{ formatterItemType(row.itemType) }}</span>
<span v-else>{{ row.itemType || row.itemName || row.material || row.specification || row.manufacturer || row.zincLayer
}}</span>
</template>
</vxe-table-column>
<vxe-table-column sortable field="itemName" title="物料名称" align="center" :filters="itemNameOptions" :filter-method="filterItemNameMethod">
</vxe-table-column>
<vxe-table-column sortable field="material" title="材质" align="center" :filters="materialOptions" :filter-method="filterMaterialMethod">
</vxe-table-column>
<vxe-table-column sortable field="specification" title="规格" align="center" :filters="specificationOptions" :filter-method="filterSpecificationMethod">
</vxe-table-column>
<vxe-table-column sortable field="manufacturer" title="厂家" align="center" :filters="manufacturerOptions" :filter-method="filterManufacturerMethod">
</vxe-table-column>
<vxe-table-column sortable field="zincLayer" title="镀层质量" align="center" :filters="zincLayerOptions" :filter-method="filterZincLayerMethod">
</vxe-table-column>
<vxe-table-column sortable field="totalQuantity" title="库存数量" align="center">
</vxe-table-column>
<vxe-table-column field="remark" title="备注" align="center" />
<vxe-table-column title="操作" align="center" width="100">
<template v-slot="{ row }">
<el-button v-if="row.itemId" type="text" size="small" @click="handleDrillDown(row)">查看明细</el-button>
</template>
</vxe-table-column>
</vxe-table>
</div>
<!-- <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
@pagination="getList" /> -->
<!-- 钻取明细对话框 -->
<el-dialog :title="dialogTitle" :visible.sync="drillDownVisible" width="80%" :close-on-click-modal="false">
<DrillDownTable :query-params="drillDownQueryParams" :item-name="drillDownParams.itemName"
:warehouse-name="drillDownParams.warehouseName" />
</el-dialog>
</div>
</div>
</template>
<script>
import { listStock, getStockByActual } from "@/api/wms/stock";
import RawMaterialSelect from "@/components/KLPService/RawMaterialSelect";
import ProductSelect from "@/components/KLPService/ProductSelect";
import WarehouseSelect from "@/components/WarehouseSelect";
import RawMaterialInfo from "@/components/KLPService/Renderer/RawMaterialInfo";
import ProductInfo from "@/components/KLPService/Renderer/ProductInfo";
import WarehouseTree from "@/components/KLPService/WarehouseTree/index.vue";
import MaterialSelect from "@/components/KLPService/MaterialSelect";
// 导入钻取表格组件
import DrillDownTable from '../coil/panels/DrillDownTable.vue';
import { findItemWithBom } from "@/store/modules/category";
export default {
name: "Stock",
dicts: ['stock_item_type'],
components: {
WarehouseSelect,
RawMaterialSelect,
ProductSelect,
RawMaterialInfo,
ProductInfo,
WarehouseTree,
MaterialSelect,
DrillDownTable // 注册钻取组件
},
data() {
return {
// 库存分析对话框显示状态
stockBoxVisible: false,
// 按钮loading
buttonLoading: false,
// 遮罩层
loading: true,
// 显示搜索条件
showSearch: true,
// 总条数
total: 0,
totalQuantity: 0,
// 库存:原材料/产品与库区/库位的存放关系表格数据
stockList: [],
// 弹出层标题
title: "",
// 是否显示弹出层
open: false,
// 查询参数
queryParams: {
pageNum: 1,
pageSize: 9999,
warehouseId: undefined,
itemType: undefined,
itemId: undefined,
quantity: undefined,
unit: undefined,
batchNo: undefined,
mergeBatch: false,
},
warehouseType: 'real',
// 表单参数
form: {},
// 钻取相关数据
drillDownVisible: false,
dialogTitle: '',
drillDownParams: {
itemType: null,
itemId: null,
itemName: '',
warehouseId: null,
warehouseName: '',
},
// 传给钻取表格组件的查询参数
drillDownQueryParams: {
warehouseId: null,
itemType: null,
itemId: null,
actualWarehouseId: null,
},
// 分组相关数据
groupForm: {
groupingCriteria: []
},
// vxe-table树配置
tableTreeConfig: {
children: 'children',
accordion: true,
expandAll: false,
line: true,
},
// 搜索关键字
filterName: '',
// 筛选选项数组
itemNameOptions: [],
materialOptions: [],
specificationOptions: [],
manufacturerOptions: [],
zincLayerOptions: []
};
},
computed: {
list() {
const filterName = this.filterName.trim().toLowerCase();
if (!filterName) {
return this.stockList;
}
const searchProps = ['itemType', 'itemName', 'material', 'specification', 'manufacturer', 'totalQuantity', 'remark'];
const filterData = (data) => {
return data.filter(item => {
if (item.children) {
item.children = filterData(item.children);
return item.children.length > 0 || searchProps.some(key => {
return String(item[key] || '').toLowerCase().includes(filterName);
});
}
return searchProps.some(key => {
return String(item[key] || '').toLowerCase().includes(filterName);
});
});
};
return filterData([...this.stockList]);
}
},
created() {
this.getList();
},
methods: {
/** 查询库存列表 */
getList() {
this.loading = true;
if (this.warehouseType === 'real') {
getStockByActual(this.queryParams).then(response => {
let q = 0
const processedData = response.rows.map(item => {
q += parseInt(item.totalQuantity);
const itemType = item.itemType
if (itemType === 'raw_material') {
item.rawMaterial = {
rawMaterialId: item.itemId,
rawMaterialName: item.itemName,
itemId: item.itemId,
itemName: item.itemName,
rawMaterialCode: item.itemCode,
specification: item.specification,
material: item.material,
surfaceTreatment: item.surfaceTreatment,
zincLayer: item.zincLayer,
manufacturer: item.manufacturer,
}
} else if (itemType === 'product') {
item.product = {
productId: item.itemId,
productName: item.itemName,
productCode: item.itemCode,
itemId: item.itemId,
itemName: item.itemName,
specification: item.specification,
material: item.material,
surfaceTreatment: item.surfaceTreatment,
zincLayer: item.zincLayer,
manufacturer: item.manufacturer,
}
}
return item
});
this.stockList = this.groupData(processedData, this.groupForm.groupingCriteria);
this.total = response.total;
this.totalQuantity = q;
// 提取选项值
this.extractOptions(processedData);
this.loading = false;
});
} else {
listStock(this.queryParams).then(response => {
const processedData = response.rows.map(item => {
const itemType = item.itemType
if (itemType === 'raw_material') {
item.rawMaterial = {
rawMaterialId: item.itemId,
rawMaterialName: item.itemName,
rawMaterialCode: item.itemCode,
specification: item.specification,
material: item.material,
surfaceTreatment: item.surfaceTreatment,
zincLayer: item.zincLayer,
manufacturer: item.manufacturer,
}
} else if (itemType === 'product') {
item.product = {
productId: item.itemId,
productName: item.itemName,
productCode: item.itemCode,
specification: item.specification,
material: item.material,
surfaceTreatment: item.surfaceTreatment,
zincLayer: item.zincLayer,
manufacturer: item.manufacturer,
}
}
return item
});
this.stockList = this.groupData(processedData, this.groupForm.groupingCriteria);
this.total = response.total;
// 提取选项值
this.extractOptions(processedData);
this.loading = false;
});
}
},
/** 提取筛选选项值 */
extractOptions(data) {
// 提取唯一值
const itemNames = new Set();
const materials = new Set();
const specifications = new Set();
const manufacturers = new Set();
const zincLayers = new Set();
data.forEach(item => {
if (item.itemName) itemNames.add(item.itemName);
if (item.material) materials.add(item.material);
if (item.specification) specifications.add(item.specification);
if (item.manufacturer) manufacturers.add(item.manufacturer);
if (item.zincLayer) zincLayers.add(item.zincLayer);
});
// 转换为数组并排序
this.itemNameOptions = Array.from(itemNames).sort();
this.materialOptions = Array.from(materials).sort();
this.specificationOptions = Array.from(specifications).sort();
this.manufacturerOptions = Array.from(manufacturers).sort();
this.zincLayerOptions = Array.from(zincLayers).sort();
this.updateManufacturerFilterEvent();
this.updateZincLayerFilterEvent();
this.updateSpecificationFilterEvent();
this.updateMaterialFilterEvent();
this.updateNameFilterEvent();
console.log(this.itemNameOptions, itemNames, data);
},
formatterItemType(itemType) {
return itemType === 'raw_material' ? '原材料' : '产品';
},
// 树节点点击
handleTreeSelect(node) {
this.queryParams.warehouseId = node.warehouseId;
this.queryParams.actualWarehouseId = node.actualWarehouseId;
this.queryParams.pageNum = 1;
this.getList();
},
// 表单重置
reset() {
this.form = {
stockId: undefined,
warehouseId: undefined,
itemType: undefined,
itemId: undefined,
quantity: undefined,
unit: undefined,
batchNo: undefined,
remark: undefined,
delFlag: undefined,
createTime: undefined,
createBy: undefined,
updateTime: undefined,
updateBy: undefined
};
this.resetForm("form");
},
/** 搜索按钮操作 */
handleQuery() {
this.queryParams.pageNum = 1;
this.getList();
},
/** 重置按钮操作 */
resetQuery() {
this.resetForm("queryForm");
this.handleQuery();
},
/** 导出按钮操作 */
handleExport() {
this.download('wms/stock/export', {
...this.queryParams
}, `stock_${new Date().getTime()}.xlsx`)
},
/** 处理表格行点击 */
handleTableRowClick(row) {
this.handleDrillDown(row);
},
/** 处理钻取操作 */
handleDrillDown(row) {
// 重置钻取参数
this.drillDownParams = {
itemType: null,
itemId: null,
itemName: '',
warehouseId: null,
warehouseName: '',
};
// 重置传给子组件的查询参数
this.drillDownQueryParams = {
warehouseId: this.queryParams.warehouseId || row.warehouseId,
itemType: row.itemType,
itemId: row.itemId,
actualWarehouseId: row.actualWarehouseId
};
// 设置钻取参数
this.drillDownParams.itemType = row.itemType;
this.drillDownParams.itemId = row.itemId;
this.drillDownParams.warehouseId = this.queryParams.warehouseId || row.warehouseId;
// 获取物料名称
const item = findItemWithBom(row.itemType, row.itemId);
this.drillDownParams.itemName = item ?
(row.itemType === 'product' ? item.productName : item.rawMaterialName) :
'未知物料';
// 设置对话框标题
this.dialogTitle = `${row.itemType === 'product' ? '成品' : '原材料'}库存明细`;
// 打开弹窗
this.drillDownVisible = true;
},
/** 重置分组 */
resetGroup() {
this.groupForm.groupingCriteria = [];
this.getList();
},
/** 分组数据处理 */
groupData(data, criteria) {
if (!criteria || criteria.length === 0) {
return data;
}
const groupBy = (arr, key) => {
return arr.reduce((groups, item) => {
const value = item[key] || '未知';
if (!groups[value]) {
groups[value] = [];
}
groups[value].push(item);
return groups;
}, {});
};
const buildTree = (items, level) => {
if (level >= criteria.length) {
return items;
}
const currentCriteria = criteria[level];
const grouped = groupBy(items, currentCriteria);
return Object.keys(grouped).map(key => {
const children = buildTree(grouped[key], level + 1);
const totalQuantity = children.reduce((sum, child) => {
return sum + (parseInt(child.totalQuantity) || 0);
}, 0);
return {
[currentCriteria]: key,
totalQuantity,
children,
hasChildren: children.length > 0
};
});
};
return buildTree(data, 0);
},
/** 物料类型筛选 */
filterItemTypeMethod({ cellValue, option }) {
return cellValue === option.value;
},
/** 物料名称筛选 */
filterItemNameMethod({ cellValue, option }) {
return option.value ? cellValue === option.value : true;
},
/** 材质筛选 */
filterMaterialMethod({ cellValue, option }) {
return option.value ? cellValue === option.value : true;
},
/** 规格筛选 */
filterSpecificationMethod({ cellValue, option }) {
return option.value ? cellValue === option.value : true;
},
/** 厂家筛选 */
filterManufacturerMethod({ cellValue, option }) {
return option.value ? cellValue === option.value : true;
},
/** 镀层质量筛选 */
filterZincLayerMethod({ cellValue, option }) {
return option.value ? cellValue === option.value : true;
},
/** 库存数量筛选 */
filterTotalQuantityMethod({ cellValue, option }) {
const value = Number(cellValue || 0);
const filterValue = Number(option.value || 0);
switch (option.operator || option.value) {
case 'gt':
return value > filterValue;
case 'gte':
return value >= filterValue;
case 'lt':
return value < filterValue;
case 'lte':
return value <= filterValue;
case 'eq':
return value === filterValue;
default:
return true;
}
},
/** 更改物料名称筛选条件 */
updateNameFilterEvent() {
const xTable = this.$refs.xTree;
const column = xTable.getColumnByField('itemName');
// 使用从数据中汇总的实际选项
const options = this.itemNameOptions.map(item => ({
label: item,
value: item
}));
// 修改筛选列表
xTable.setFilter(column, options);
// 修改条件之后,需要手动调用 updateData 处理表格数据
xTable.updateData();
},
/** 更改材质筛选条件 */
updateMaterialFilterEvent() {
const xTable = this.$refs.xTree;
const column = xTable.getColumnByField('material');
// 使用从数据中汇总的实际选项
const options = this.materialOptions.map(item => ({
label: item,
value: item
}));
// 修改筛选列表
xTable.setFilter(column, options);
// 修改条件之后,需要手动调用 updateData 处理表格数据
xTable.updateData();
},
/** 更改规格筛选条件 */
updateSpecificationFilterEvent() {
const xTable = this.$refs.xTree;
const column = xTable.getColumnByField('specification');
// 使用从数据中汇总的实际选项
const options = this.specificationOptions.map(item => ({
label: item,
value: item
}));
// 修改筛选列表
xTable.setFilter(column, options);
// 修改条件之后,需要手动调用 updateData 处理表格数据
xTable.updateData();
},
/** 更改厂家筛选条件 */
updateManufacturerFilterEvent() {
const xTable = this.$refs.xTree;
const column = xTable.getColumnByField('manufacturer');
// 使用从数据中汇总的实际选项
const options = this.manufacturerOptions.map(item => ({
label: item,
value: item
}));
// 修改筛选列表
xTable.setFilter(column, options);
// 修改条件之后,需要手动调用 updateData 处理表格数据
xTable.updateData();
},
/** 更改镀层质量筛选条件 */
updateZincLayerFilterEvent() {
const xTable = this.$refs.xTree;
const column = xTable.getColumnByField('zincLayer');
// 使用从数据中汇总的实际选项
const options = this.zincLayerOptions.map(item => ({
label: item,
value: item
}));
// 修改筛选列表
xTable.setFilter(column, options);
// 修改条件之后,需要手动调用 updateData 处理表格数据
xTable.updateData();
},
/** 清除筛选条件 */
clearFilterEvent() {
const xTable = this.$refs.xTree;
xTable.clearFilter();
xTable.updateData();
},
/** 刷新数据 */
reload() {
this.getList();
}
}
};
</script>
<style scoped>
.stock-layout {
height: 100%;
display: flex;
flex-direction: row;
}
.stock-tree-col {
width: 260px;
max-width: 300px;
background: #fff;
border-right: 1px solid #f0f0f0;
height: 100%;
padding-right: 0;
box-sizing: border-box;
display: flex;
flex-direction: column;
}
.stock-tree-card {
height: 100%;
border: none;
box-shadow: none;
}
.stock-tree-title {
font-weight: bold;
font-size: 16px;
padding: 8px 0;
}
.stock-tree {
min-height: 500px;
max-height: 80vh;
overflow-y: auto;
}
.stock-main-col {
flex: 1;
padding-left: 24px;
min-width: 0;
display: flex;
flex-direction: column;
}
.group-controls {
margin-bottom: 16px;
padding: 12px;
background-color: #f9f9f9;
border-radius: 4px;
border: 1px solid #eaeaea;
}
.group-controls .el-form {
margin-bottom: 0;
}
/* 分组行样式 */
.el-table__row.group-row {
background-color: #f5f7fa;
}
/* 叶子节点样式 */
.el-table__row.leaf-row {
background-color: #ffffff;
}
/* 筛选输入框样式 */
.my-input {
width: 100%;
padding: 4px 8px;
border: 1px solid #dcdfe6;
border-radius: 4px;
font-size: 12px;
outline: none;
transition: border-color 0.3s;
}
.my-input:focus {
border-color: #409eff;
}
/* 筛选下拉选择框样式 */
.my-select {
width: 100%;
padding: 4px 8px;
border: 1px solid #dcdfe6;
border-radius: 4px;
font-size: 12px;
outline: none;
transition: border-color 0.3s;
background-color: #fff;
}
.my-select:focus {
border-color: #409eff;
}
/* 库存数量筛选样式 */
.quantity-filter {
display: flex;
flex-direction: column;
gap: 4px;
}
.quantity-filter .my-select {
width: 100%;
}
.quantity-filter .my-input {
width: 100%;
}
</style>

View File

@@ -72,14 +72,12 @@
</template>
<script>
import { listStock, delStock, addStock, updateStock, getStockByActual } from "@/api/wms/stock";
import { addStockIoWithDetail } from "@/api/wms/stockIo";
import { listStock, getStockByActual } from "@/api/wms/stock";
import RawMaterialSelect from "@/components/KLPService/RawMaterialSelect";
import ProductSelect from "@/components/KLPService/ProductSelect";
import WarehouseSelect from "@/components/WarehouseSelect";
import RawMaterialInfo from "@/components/KLPService/Renderer/RawMaterialInfo";
import ProductInfo from "@/components/KLPService/Renderer/ProductInfo";
import StockIo from './panels/stockIo.vue';
import WarehouseTree from "@/components/KLPService/WarehouseTree/index.vue";
import MaterialSelect from "@/components/KLPService/MaterialSelect";
// 导入钻取表格组件
@@ -88,14 +86,13 @@ import { findItemWithBom } from "@/store/modules/category";
export default {
name: "Stock",
dicts: ['stock_item_type', 'stock_io_type'],
dicts: ['stock_item_type'],
components: {
WarehouseSelect,
RawMaterialSelect,
ProductSelect,
RawMaterialInfo,
ProductInfo,
StockIo,
WarehouseTree,
MaterialSelect,
DrillDownTable // 注册钻取组件

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>