feat: 仓库管理

This commit is contained in:
砂糖
2025-09-17 15:59:03 +08:00
parent 0346e09dd3
commit 2bd09e2cf4
43 changed files with 5473 additions and 33 deletions

View File

@@ -0,0 +1,167 @@
<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,410 @@
<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>
<WarehouseTree @node-click="handleTreeSelect" />
</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 label="单位" prop="unit">
<el-input v-model="queryParams.unit" placeholder="请输入单位" clearable @keyup.enter.native="handleQuery" />
</el-form-item>
<el-form-item>
<el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
<el-button icon="Refresh" @click="resetQuery">重置</el-button>
<el-button type="warning" plain icon="Download" size="mini" @click="handleExport">导出</el-button>
<!-- 合并批次<el-switch v-model="queryParams.mergeBatch" :active-value="1" :inactive-value="0" @change="handleQuery" /> -->
</el-form-item>
</el-form>
<right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
<el-table v-loading="loading" :data="stockList" @selection-change="handleSelectionChange">
<el-table-column type="selection" width="55" align="center" />
<el-table-column label="仓库" align="center" prop="warehouseName" />
<el-table-column label="物品类型" align="center" prop="itemType">
<template #default="scope">
<dict-tag :options="stock_item_type" :value="scope.row.itemType" />
</template>
</el-table-column>
<el-table-column label="物品" align="center" prop="itemName">
<template #default="scope">
<ProductInfo v-if="scope.row.itemType == 'product' || scope.row.itemType == 'semi'" :productId="scope.row.itemId">
<template #default="{ product }">
{{ product.productName }}({{ product.productCode }})
</template>
</ProductInfo>
<!-- <RawMaterialInfo v-else-if="scope.row.itemType === 'raw_material'" :materialId="scope.row.itemId">
<template #default="{ material }">
{{ material.rawMaterialName }}({{ material.rawMaterialCode }})
</template>
</RawMaterialInfo> -->
</template>
</el-table-column>
<el-table-column label="BOM">
<template #default="scope">
<BomInfoMini :itemType="scope.row.itemType" :itemId="scope.row.itemId" />
</template>
</el-table-column>
<el-table-column label="库存数量" align="center" prop="quantity" />
<!-- <el-table-column label="在途数量" align="center" prop="onTheWay" /> -->
<el-table-column label="单位" align="center" prop="unit" />
<el-table-column label="批次号" align="center" prop="batchNo" />
<el-table-column label="备注" align="center" prop="remark" />
<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
<template #default="scope">
<el-button type="text" size="small" @click="handleTrace(scope.row)">物料追溯</el-button>
</template>
</el-table-column>
</el-table>
<pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
@pagination="getList" />
<!-- 添加或修改库存对话框保持不变 -->
<el-dialog :title="title" v-model="open" width="500px" append-to-body>
<el-form ref="form" :model="form" :rules="rules" label-width="80px">
<el-form-item label="仓库/库区/库位ID" prop="warehouseId">
<warehouse-select v-model="form.warehouseId" placeholder="请选择仓库/库区/库位" style="width: 100%;" clearable />
</el-form-item>
<el-form-item label="物品类型" prop="itemType">
<el-select v-model="form.itemType" placeholder="请选择物品类型">
<el-option v-for="dict in stock_item_type" :key="dict.value" :label="dict.label"
:value="dict.value"></el-option>
</el-select>
</el-form-item>
<el-form-item label="物品" prop="itemId">
<!-- <raw-material-select v-if="form.itemType === 'rawMaterial'" v-model="form.itemId" placeholder="请选择原材料"
style="width: 100%;" clearable /> -->
<product-select v-if="form.itemType === 'product'" v-model="form.itemId" placeholder="请选择产品"
style="width: 100%;" clearable />
<el-input v-else v-model="form.itemId" placeholder="请先选择物品类型" :disabled="true" style="width: 100%;" />
</el-form-item>
<el-form-item label="库存数量" prop="quantity">
<el-input v-model="form.quantity" placeholder="请输入库存数量" />
</el-form-item>
<el-form-item label="单位" prop="unit">
<el-input v-model="form.unit" placeholder="请输入单位" />
</el-form-item>
<el-form-item label="批次号" prop="batchNo">
<el-input v-model="form.batchNo" placeholder="请输入批次号" />
</el-form-item>
<el-form-item label="备注" prop="remark">
<el-input v-model="form.remark" placeholder="请输入备注" />
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button :loading="buttonLoading" type="primary" @click="submitForm"> </el-button>
<el-button @click="cancel"> </el-button>
</div>
</el-dialog>
<el-dialog v-model="stockBoxVisible" title="暂存单据" width="800px" append-to-body>
<stock-io :data="stockBoxData" @generateBill="handleGenerateBill" />
</el-dialog>
<el-dialog v-model="stockTraceVisible" title="物料追溯" width="800px" append-to-body>
<el-table :data="stockTraceList" style="width: 100%">
<el-table-column label="单据类型" align="center" prop="ioType">
<template #default="scope">
<dict-tag :options="stock_io_type" :value="scope.row.ioType" />
</template>
</el-table-column>
<el-table-column label="单据ID" align="center" prop="stockIoId" />
<el-table-column label="单据编号" align="center" prop="stockIoCode" />
<!-- <el-table-column label="创建时间" align="center" prop="createTime" /> -->
<el-table-column label="变更数量" align="center" prop="quantity" />
<el-table-column label="备注" align="center" prop="remark" />
</el-table>
</el-dialog>
</div>
</div>
</template>
<script>
import { listStock, delStock, addStock, updateStock, getStockTrace } from "@/api/wms/stock";
import { addStockIoWithDetail } from "@/api/wms/stockIo";
import ProductSelect from "@/components/ProductSelect";
import WarehouseSelect from "@/components/WarehouseSelect";
import StockBox from './box';
import ProductInfo from "@/components/Renderer/ProductInfo";
import BomInfoMini from "@/components/Renderer/BomInfoMini";
import StockIo from './panels/stockIo.vue';
import WarehouseTree from "@/components/WarehouseTree/index.vue";
export default {
name: "Stock",
setup() {
const { proxy } = getCurrentInstance();
const { stock_item_type, stock_io_type } = proxy.useDict('stock_item_type', 'stock_io_type');
return {
stock_item_type,
stock_io_type,
};
},
components: {
WarehouseSelect,
ProductSelect,
StockBox,
ProductInfo,
BomInfoMini,
StockIo,
WarehouseTree,
},
data() {
return {
// 库存分析对话框显示状态
stockBoxVisible: false,
// 按钮loading
buttonLoading: false,
// 遮罩层
loading: true,
// 选中数组
ids: [],
// 非单个禁用
single: true,
// 非多个禁用
multiple: true,
// 显示搜索条件
showSearch: true,
// 总条数
total: 0,
// 库存:原材料/产品与库区/库位的存放关系表格数据
stockList: [],
// 弹出层标题
title: "",
// 是否显示弹出层
open: false,
// 查询参数
queryParams: {
pageNum: 1,
pageSize: 20,
warehouseId: undefined,
itemType: undefined,
itemId: undefined,
quantity: undefined,
unit: undefined,
batchNo: undefined,
mergeBatch: false,
},
// 表单参数
form: {},
// 表单校验
rules: {
warehouseId: [
{ required: true, message: "仓库/库区/库位ID不能为空", trigger: "blur" }
],
itemType: [
{ required: true, message: "物品类型不能为空", trigger: "change" }
],
itemId: [
{ required: true, message: "物品ID不能为空", trigger: "blur" }
],
quantity: [
{ required: true, message: "库存数量不能为空", trigger: "blur" }
],
unit: [
{ required: true, message: "单位不能为空", trigger: "blur" }
],
batchNo: [
{ required: true, message: "批次号不能为空", trigger: "blur" }
],
},
// 暂存用于创建出库单或移库单的数据
stockBoxData: [],
stockBoxVisible: false,
// 选中的数据
selectedRows: [],
stockTraceList: [],
stockTraceVisible: false,
};
},
created() {
this.getList();
},
methods: {
/** 查询库存:原材料/产品与库区/库位的存放关系列表 */
getList() {
this.loading = true;
listStock(this.queryParams).then(response => {
this.stockList = response.rows;
this.total = response.total;
this.loading = false;
});
},
// 树节点点击
handleTreeSelect(node) {
this.queryParams.warehouseId = node.warehouseId;
this.queryParams.pageNum = 1;
this.getList();
},
// 取消按钮
cancel() {
this.open = false;
this.reset();
},
// 表单重置
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();
},
// 多选框选中数据
handleSelectionChange(selection) {
this.selectedRows = selection;
this.ids = selection.map(item => item.stockId)
this.single = selection.length !== 1
this.multiple = !selection.length
},
/** 提交按钮 */
submitForm() {
this.$refs["form"].validate(valid => {
if (valid) {
this.buttonLoading = true;
if (this.form.stockId != null) {
updateStock(this.form).then(response => {
this.$modal.msgSuccess("修改成功");
this.open = false;
this.getList();
}).finally(() => {
this.buttonLoading = false;
});
} else {
addStock(this.form).then(response => {
this.$modal.msgSuccess("新增成功");
this.open = false;
this.getList();
}).finally(() => {
this.buttonLoading = false;
});
}
}
});
},
/** 删除按钮操作 */
handleDelete(row) {
const stockIds = row.stockId || this.ids;
this.$modal.confirm('是否确认删除库存:原材料/产品与库区/库位的存放关系编号为"' + stockIds + '"的数据项?').then(() => {
this.loading = true;
return delStock(stockIds);
}).then(() => {
this.loading = false;
this.getList();
this.$modal.msgSuccess("删除成功");
}).catch(() => {
}).finally(() => {
this.loading = false;
});
},
/** 导出按钮操作 */
handleExport() {
this.download('wms/stock/export', {
...this.queryParams
}, `stock_${new Date().getTime()}.xlsx`)
},
handleStockBox() {
// 添加到暂存单据中,并且去重,去重依据为stockId是否相同
const list = [...this.selectedRows, ...this.stockBoxData];
console.log(list);
const uniqueStockBoxData = list.filter((item, index, self) =>
index === self.findIndex(t => t.stockId === item.stockId)
);
this.stockBoxData = uniqueStockBoxData;
this.$modal.msgSuccess("暂存成功,请点击“暂存单据”按钮生成单据");
},
handleGenerateBill(data) {
addStockIoWithDetail(data).then(response => {
this.$modal.msgSuccess("生成单据成功");
});
},
handleViewStockBox() {
// 查看暂存单据
console.log(this.stockBoxData);
this.stockBoxVisible = true;
},
handleTrace(row) {
// 查询对应批次号的的出库和入库单据明细并展示
getStockTrace(row.batchNo).then(response => {
this.stockTraceList = response.data;
this.stockTraceVisible = true;
});
}
}
};
</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;
}
</style>

View File

@@ -0,0 +1,214 @@
<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

@@ -0,0 +1,269 @@
<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

@@ -0,0 +1,85 @@
// 防抖函数:避免频繁触发 resize
function debounce(fn, delay = 100) {
let timer = null;
return function (...args) {
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this, args);
timer = null;
}, delay);
};
}
export default {
data() {
return {
// 存储ResizeObserver实例
resizeObserver: null,
// 标记是否已初始化监听
isResizeListening: false
};
},
methods: {
/**
* 初始化尺寸监听
* @param {HTMLElement} container - 图表容器DOM默认取this.$refs.chartContainer
*/
initResizeListener(container) {
// 防止重复初始化
if (this.isResizeListening) return;
// 默认使用组件内的chartContainer作为监听目标
const target = container || this.$refs.chartContainer;
if (!target) {
console.warn('未找到图表容器,无法初始化尺寸监听');
return;
}
// 创建ResizeObserver实例
this.resizeObserver = new ResizeObserver(
debounce(entries => {
// 触发图表重绘
this.handleContainerResize(entries);
})
);
// 开始监听容器尺寸变化
this.resizeObserver.observe(target);
this.isResizeListening = true;
},
/**
* 处理容器尺寸变化
* @param {ResizeObserverEntry[]} entries - ResizeObserver回调参数
*/
handleContainerResize(entries) {
// 确保图表实例存在
if (this.chart && this.chart.resize) {
// 调用ECharts的resize方法重绘图表
this.chart.resize();
}
},
/**
* 销毁尺寸监听
*/
destroyResizeListener() {
if (this.resizeObserver) {
this.resizeObserver.disconnect();
this.resizeObserver = null;
}
this.isResizeListening = false;
}
},
// 组件挂载后初始化监听
mounted() {
// 延迟初始化确保DOM已渲染完成
this.$nextTick(() => {
this.initResizeListener();
});
},
// 组件销毁前清理监听
beforeDestroy() {
this.destroyResizeListener();
}
};

View File

@@ -0,0 +1,104 @@
<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>
<el-table :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 #default="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 #default="scope">
<el-button type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
</template>
</el-table-column>
</el-table>
<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

@@ -0,0 +1,406 @@
<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: 300px;"></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>