This commit is contained in:
2025-08-27 19:50:22 +08:00
parent f637e65635
commit 7d6c13e935
12 changed files with 1212 additions and 470 deletions

View File

@ -6,8 +6,8 @@
<el-card shadow="hover">
<template #header>
<el-row :gutter="10" class="mb8">
<el-col :span="1.5" :offset="0"
><el-button
<el-col :span="1.5" :offset="0">
<el-button
type="primary"
v-hasPermi="['cailiaoshebei:materialbatchdemandplan:add']"
size="default"
@ -15,10 +15,10 @@
icon="FolderAdd"
plain
>新增</el-button
></el-col
>
<el-col :span="1.5" :offset="0"
><el-button
>
</el-col>
<el-col :span="1.5" :offset="0">
<el-button
type="danger"
size="default"
v-hasPermi="['cailiaoshebei:materialbatchdemandplan:remove']"
@ -27,8 +27,8 @@
icon="FolderDelete"
plain
>删除</el-button
></el-col
>
>
</el-col>
</el-row>
</template>
@ -75,14 +75,11 @@
>审核</el-button
>
</el-col>
<right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
</el-row>
</template>
<el-table v-loading="loading" :data="cailiaoshebeiList" @selection-change="handleSelectionChange">
<!-- <el-table-column type="selection" width="55" align="center" /> -->
<!-- <el-table-column label="供货商ID" align="center" prop="supplierId" /> -->
<el-table-column label="物资名称" align="center" prop="name" />
<el-table-column label="质量标准" align="center" prop="qs" />
<el-table-column label="规格型号" align="center" prop="specification" />
@ -103,7 +100,7 @@
</el-row>
<!-- 添加或修改物资-材料设备对话框 -->
<el-dialog draggable :title="dialog.title" v-model="dialog.visible" width="1300px" append-to-body>
<el-dialog :close-on-click-modal="false" draggable :title="dialog.title" v-model="dialog.visible" width="1500px" append-to-body>
<el-form :model="form" ref="cailiaoshebeiFormRef" :rules="rules" label-width="80px" :inline="false">
<el-divider>基础信息</el-divider>
<el-row :gutter="20">
@ -125,63 +122,91 @@
</el-row>
<el-divider>主要信息</el-divider>
<el-table :data="form.planList">
<el-table-column prop="name" align="center" label="版本号 " width="150">
<!-- 表格添加border属性优化视觉体验 -->
<el-table :data="form.planList" border>
<!-- 版本号列 -->
<el-table-column prop="versions" align="center" label="版本号 " width="200">
<template #default="scope">
<el-select v-model="scope.row.versions" placeholder="请选择" @change="(val) => selectNameVersion(val, scope.row)">
<el-select v-model="scope.row.versions" placeholder="请选择" @change="(val) => selectNameVersion(val, scope.row, scope.$index)">
<el-option v-for="item in versionList" :key="item.versions" :label="item.versions" :value="item.versions" />
</el-select>
</template>
</el-table-column>
<el-table-column prop="name" align="center" label="物资名称">
<!-- 物资名称列 -->
<el-table-column prop="name" align="center" label="物资名称" width="160">
<template #default="scope">
<el-select
:disabled="!scope.row.versions"
v-model="scope.row.suppliespriceId"
placeholder="请选择"
@change="(val) => selectName(val, scope.row)"
@change="(val) => selectName(val, scope.row, scope.$index)"
>
<el-option v-for="item in nameList" :key="item.id" :label="item.name" :value="item.id" />
</el-select>
</template>
</el-table-column>
<el-table-column prop="specification" align="center" label="规格型号" width="150">
<!-- 剩余量列 -->
<el-table-column align="center" label="剩余量" width="80">
<template #default="scope">
<el-input v-model="scope.row.specification" placeholder="请输入规格型号" disabled />
<span>{{ scope.row.Remaining }}</span>
<!-- <el-input disabled v-model="scope.row.Remaining" placeholder="剩余量" /> -->
</template>
</el-table-column>
<el-table-column prop="unit" align="center" label="单位" width="130">
<!-- 规格型号列 -->
<el-table-column prop="specification" align="center" label="规格型号" width="100">
<template #default="scope">
<el-input v-model="scope.row.unit" placeholder="请输入单位" disabled />
<span>{{ scope.row.specification }}</span>
<!-- <el-input v-model="scope.row.specification" placeholder="请输入规格型号" disabled /> -->
</template>
</el-table-column>
<el-table-column prop="demandQuantity" align="center" label="数量" width="130">
<!-- 单位列 -->
<el-table-column prop="unit" align="center" label="单位" width="80">
<template #default="scope">
<el-input v-model="scope.row.demandQuantity" placeholder="请输入数量" type="number" min="0" disabled />
<span>{{ scope.row.unit }}</span>
<!-- <el-input v-model="scope.row.unit" placeholder="请输入单位" disabled /> -->
</template>
</el-table-column>
<el-table-column prop="qs" align="center" label="质量标准" width="150">
<template #header> <span class="text-red">*</span> 质量标准 </template>
<!-- 数量列新增错误提示展示 -->
<el-table-column prop="demandQuantity" align="center" label="数量" width="140">
<template #default="scope">
<el-input
v-model.number="scope.row.demandQuantity"
@input="validateDemandQuantity(scope.row, scope.$index)"
@blur="validateDemandQuantity(scope.row, scope.$index)"
:max="scope.row.Remaining"
placeholder="请输入数量"
type="number"
min="0"
/>
<!-- 数量错误提示红色小字体 -->
<div v-if="scope.row.quantityError" class="text-red-500 text-xs mt-1">{{ scope.row.quantityError }}</div>
</template>
</el-table-column>
<!-- 质量标准列 -->
<el-table-column prop="qs" align="center" label="质量标准" width="140">
<template #header> <span class="text-red-500">*</span> 质量标准 </template>
<template #default="scope">
<el-input v-model="scope.row.qs" placeholder="请输入质量标准" />
</template>
</el-table-column>
<el-table-column prop="arrivalTime" align="center" label="需求到货时间">
<template #header> <span class="text-red">*</span> 需求到货时间 </template>
<!-- 需求到货时间列 -->
<el-table-column prop="arrivalTime" align="center" label="需求到货时间" width="180">
<template #header> <span class="text-red-500">*</span> 需求到货时间 </template>
<template #default="scope">
<el-date-picker v-model="scope.row.arrivalTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择" style="width: 140px" />
</template>
</el-table-column>
<el-table-column prop="remark" align="center" label="备注" width="150">
<!-- 备注 -->
<el-table-column prop="remark" align="center" label="备注" >
<template #default="scope">
<el-input v-model="scope.row.remark" placeholder="请输入备注" disabled />
</template>
</el-table-column>
<!-- 操作列 -->
<el-table-column prop="remark" align="center" label="操作" width="150">
<template #default="scope">
<el-button @click="addRow" type="success" icon="Plus" circle size="small" />
<el-button @click="delRow(scope.$index)" type="danger" icon="Delete" circle size="small" />
<el-button @click="addRow" type="primary" icon="Plus" size="small" />
<el-button @click="delRow(scope.$index)" type="danger" icon="Delete" size="small" />
</template>
</el-table-column>
</el-table>
@ -206,10 +231,47 @@ import {
listSelectCailiaoshebei,
obtainTheVersion,
getDictList,
coryEngineeringList
coryEngineeringList,
mrpBaseRemaining
} from '@/api/materials/batchPlan';
import { CailiaoshebeiVO, CailiaoshebeiQuery, CailiaoshebeiForm } from '@/api/materials/batchPlan/types';
import { useUserStoreHook } from '@/store/modules/user';
import { getCurrentInstance, ComponentInternalInstance, watch, onMounted, onUnmounted } from 'vue';
import type { ElFormInstance } from 'element-plus';
// 类型定义补充
interface DialogOption {
visible: boolean;
title: string;
}
interface PlanListItem {
id?: number | undefined;
name?: string | undefined;
specification?: string | undefined;
unit?: string | undefined;
suppliespriceId?: number | undefined;
demandQuantity?: number | undefined;
qs?: string | undefined;
arrivalTime?: string | undefined;
remark?: string | undefined;
Remaining: number; // 剩余量(必存在)
quantityError: string; // 数量错误提示
versions?: string | undefined; // 版本号
duplicateError: string; // 重复错误提示
}
interface FormData {
mrpBaseBo: {
id?: number | undefined;
preparedDate?: string | undefined;
planCode?: string | undefined;
matCat?: string | undefined;
status?: string | undefined;
projectId?: number | undefined;
};
planList: PlanListItem[];
}
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
// 获取用户 store
@ -227,17 +289,17 @@ const multiple = ref(true);
const total = ref(0);
const mainTotal = ref(0);
const batchOptions = ref<any[]>([]);
const { wf_business_status } = toRefs<any>(proxy?.useDict('wf_business_status'));
const { wf_business_status } = toRefs<any>(proxy?.useDict('wf_business_status') || {});
const route = useRoute();
const queryFormRef = ref<ElFormInstance>();
const cailiaoshebeiFormRef = ref<ElFormInstance>();
const dialog = reactive<DialogOption>({
visible: false,
title: ''
});
const initFormData: any = {
// 初始化表单数据(补充版本号、重复错误提示字段)
const initFormData: FormData = {
mrpBaseBo: {
id: undefined,
preparedDate: undefined,
@ -246,7 +308,6 @@ const initFormData: any = {
status: undefined,
projectId: currentProject.value?.id
},
planList: [
{
id: undefined,
@ -257,18 +318,22 @@ const initFormData: any = {
demandQuantity: undefined,
qs: undefined,
arrivalTime: undefined,
remark: undefined
remark: undefined,
Remaining: 0, // 初始化剩余量
quantityError: '', // 初始化数量错误提示
versions: undefined, // 初始化版本号
duplicateError: '' // 初始化重复错误提示
}
]
};
const data = reactive({
form: { ...initFormData },
form: { ...initFormData } as FormData,
queryParams: {
batchData: {
pageNum: 1,
pageSize: 10,
planCode: undefined,
projectId: currentProject.value?.id
},
mainData: {
@ -285,77 +350,184 @@ const data = reactive({
'mrpBaseBo.matCat': [{ required: true, message: '物资分类不能为空', trigger: 'blur' }]
}
});
const batchNumber = ref('');
const { queryParams, form, rules } = toRefs(data);
const nameList = ref([]);
const versionList = ref([]);
const nameList = ref<any[]>([]);
const versionList = ref<any[]>([]);
/** 查询物资-材料设备列表 */
const getList = async (type?: string) => {
loading.value = true;
const res = await listBatch(queryParams.value.batchData);
batchOptions.value = res.rows;
if (res.rows && res.rows.length > 0 && !queryParams.value.mainData.mrpBaseId) {
batchTreeRef.value.setCurrentKey(res.rows[0].id);
queryParams.value.mainData.mrpBaseId = res.rows[0].id;
form.value.mrpBaseBo.status = res.rows[0].status;
try {
const res = await listBatch(queryParams.value.batchData);
batchOptions.value = res.rows || [];
// 自动选中第一条数据(如果存在且未选中)
if (batchOptions.value.length > 0 && !queryParams.value.mainData.mrpBaseId) {
batchTreeRef.value?.setCurrentKey(batchOptions.value[0].id);
queryParams.value.mainData.mrpBaseId = batchOptions.value[0].id;
form.value.mrpBaseBo.status = batchOptions.value[0].status;
}
total.value = res.total || 0;
} catch (error) {
proxy?.$modal.msgError('获取批次列表失败');
} finally {
loading.value = false;
// 非搜索场景下同步加载主列表
if (type !== 'search') {
getMainList();
}
}
total.value = res.total;
loading.value = false;
if (type === 'search') return;
getMainList();
};
const selectName = (val: any, row: any) => {
const selected = nameList.value.find((item) => item.id === val);
if (selected) {
row.name = selected.name;
row.specification = selected.specification;
row.unit = selected.unit;
row.qs = selected.qs;
row.demandQuantity = selected.quantity;
row.remark = selected.remark;
row.arrivalTime = selected.arrivalTime;
/** 数量校验:必须≤剩余量,且为合法数字 */
const validateDemandQuantity = (row: PlanListItem, index: number) => {
// 1. 清除之前的错误信息
row.quantityError = '';
// 2. 处理空值若需必填可补充row.quantityError = '数量不能为空'
if (row.demandQuantity === null || row.demandQuantity === undefined || row.demandQuantity === '') {
return;
}
// 3. 处理非数字
if (typeof row.demandQuantity !== 'number' || isNaN(row.demandQuantity)) {
row.quantityError = '请输入合法数字';
return;
}
// 4. 处理负数
if (row.demandQuantity < 0) {
row.quantityError = '数量不能为负数';
return;
}
// 5. 核心校验:数量≤剩余量
if (row.demandQuantity > row.Remaining) {
row.quantityError = `数量不能超过剩余量${row.Remaining}`;
}
};
/** 获取剩余量 */
const getMrpBaseRemaining = async (suppliespriceId: number, row: PlanListItem) => {
try {
const res = await mrpBaseRemaining({ suppliespriceId });
row.Remaining = res.data || 0;
// 剩余量更新后,重新校验当前数量
validateDemandQuantity(row, 0);
} catch (error) {
proxy?.$modal.msgError('获取剩余量失败');
row.Remaining = 0;
}
};
/** 校验重复数据:版本号+物资名称不能重复 */
const checkDuplicate = () => {
const planList = form.value.planList;
let hasDuplicate = false;
// 1. 清除所有重复错误提示
planList.forEach((item) => {
item.duplicateError = '';
});
// 2. 遍历校验重复(只校验版本号和物资名称都存在的行)
for (let i = 0; i < planList.length; i++) {
const current = planList[i];
// 跳过版本号或物资名称为空的行
if (!current.versions || !current.suppliespriceId) continue;
for (let j = i + 1; j < planList.length; j++) {
const compare = planList[j];
if (!compare.versions || !compare.suppliespriceId) continue;
// 版本号和物资ID都相同则判定为重复
if (current.versions === compare.versions && current.suppliespriceId === compare.suppliespriceId) {
current.duplicateError = `与第${j + 1}行重复(同版本+同物资)`;
compare.duplicateError = `与第${i + 1}行重复(同版本+同物资)`;
hasDuplicate = true;
}
}
}
return hasDuplicate;
};
/** 选择物资名称触发(新增索引参数,用于触发重复校验) */
const selectName = (val: number, row: PlanListItem, index: number) => {
// 1. 获取剩余量并更新基础信息
getMrpBaseRemaining(val, row).then(() => {
const selected = nameList.value.find((item: any) => item.id === val);
if (selected) {
row.name = selected.name;
row.specification = selected.specification;
row.unit = selected.unit;
row.qs = selected.qs || '';
row.remark = selected.remark || '';
row.arrivalTime = selected.arrivalTime || '';
}
// 2. 触发重复校验
checkDuplicate();
});
};
/** 节点单击事件 */
const handleNodeClick = (data: any) => {
queryParams.value.mainData.mrpBaseId = data.id;
form.value.mrpBaseBo.status = data.status;
getMainList();
};
/** 获取主列表数据 */
const getMainList = async () => {
if (!queryParams.value.mainData.mrpBaseId) return;
const res = await getBatch(queryParams.value.mainData);
cailiaoshebeiList.value = res.rows;
mainTotal.value = res.total;
loading.value = true;
try {
const res = await getBatch(queryParams.value.mainData);
cailiaoshebeiList.value = res.rows || [];
mainTotal.value = res.total || 0;
} catch (error) {
proxy?.$modal.msgError('获取物资列表失败');
} finally {
loading.value = false;
}
};
/** 搜索批次列表 */
const searchBatchList = async () => {
queryParams.value.batchData.planCode = batchNumber.value;
getList('search');
};
//删除
/** 删除表格行 */
const delRow = (index: number) => {
if (form.value.planList.length <= 1) return proxy?.$modal.msgWarning('请至少保留一项');
if (form.value.planList.length <= 1) {
return proxy?.$modal.msgWarning('请至少保留一项物资数据');
}
form.value.planList.splice(index, 1);
// 删除后重新校验重复(避免删除重复行后错误提示残留)
checkDuplicate();
};
//新增
/** 新增表格行 */
const addRow = () => {
form.value.planList.push({
const newRow: PlanListItem = {
name: undefined,
specification: undefined,
unit: undefined,
suppliespriceId: undefined,
demandQuantity: undefined,
qs: undefined,
arrivalTime: undefined,
remark: undefined
});
remark: undefined,
Remaining: 0,
quantityError: '',
versions: undefined,
duplicateError: ''
};
form.value.planList.push(newRow);
};
/** 取消按钮 */
@ -367,41 +539,22 @@ const cancel = () => {
/** 表单重置 */
const reset = () => {
const status = form.value.mrpBaseBo.status;
form.value = { ...initFormData, status }; // 重置但保留
// 重置表单(保留状态字段)
form.value = {
...JSON.parse(JSON.stringify(initFormData)),
mrpBaseBo: { ...initFormData.mrpBaseBo, status }
};
// 重置表单验证状态
cailiaoshebeiFormRef.value?.resetFields();
// 重置项目ID
form.value.mrpBaseBo.projectId = currentProject.value?.id;
form.value.planList = [
{
name: undefined,
specification: undefined,
unit: undefined,
suppliespriceId: undefined,
demandQuantity: undefined,
qs: undefined,
arrivalTime: undefined,
remark: undefined
}
];
};
// /** 搜索按钮操作 */
// const handleQuery = () => {
// queryParams.value.pageNum = 1;
// getList();
// };
// /** 重置按钮操作 */
// const resetQuery = () => {
// queryFormRef.value?.resetFields();
// handleQuery();
// };
/** 多选框选中数据 */
const handleSelectionChange = (selection: CailiaoshebeiVO[]) => {
ids.value = selection.map((item) => item.id);
single.value = selection.length != 1;
multiple.value = !selection.length;
single.value = selection.length !== 1;
multiple.value = selection.length === 0;
};
/** 新增按钮操作 */
@ -411,93 +564,154 @@ const handleAdd = () => {
dialog.title = '新增物资-需求';
};
/** 修改按钮操作 */
const handleUpdata = () => {
reset();
getCailiaoshebei(queryParams.value.mainData.mrpBaseId).then((res: any) => {
form.value.mrpBaseBo = res.data.mrpBaseBo;
const allowedKeys = Object.keys(initFormData.planList[0]);
form.value.planList = res.data.planList.map((item) => {
return allowedKeys.reduce((obj, key) => {
obj[key] = item[key] ?? undefined;
return obj;
}, {});
});
console.log(form.value.planList);
});
dialog.visible = true;
dialog.title = '修改物资-需求';
};
/** 提交数据 */
const submitTransferForm = async () => {
const result = validateAndClean(form.value.planList);
if (!result.valid) {
proxy?.$modal.msgError(result.message);
return;
if (!queryParams.value.mainData.mrpBaseId) {
return proxy?.$modal.msgError('请先选择批次');
}
reset();
loading.value = true;
getCailiaoshebei(queryParams.value.mainData.mrpBaseId)
.then((res: any) => {
// 1. 更新基础信息
form.value.mrpBaseBo = res.data.mrpBaseBo || initFormData.mrpBaseBo;
// 2. 更新表格数据(补充缺失字段)
form.value.planList = (res.data.planList || []).map((item: any) => ({
id: item.id,
name: item.name,
specification: item.specification,
unit: item.unit,
suppliespriceId: item.suppliespriceId,
demandQuantity: item.demandQuantity,
qs: item.qs,
arrivalTime: item.arrivalTime,
remark: item.remark,
Remaining: item.Remaining || 0,
quantityError: '',
versions: item.versions,
duplicateError: ''
}));
// 3. 打开对话框
dialog.visible = true;
dialog.title = '修改物资-需求';
})
.catch(() => {
proxy?.$modal.msgError('获取详情失败');
})
.finally(() => {
loading.value = false;
});
};
/** 提交数据(整合所有校验) */
const submitTransferForm = async () => {
// 1. 先校验重复数据
const hasDuplicate = checkDuplicate();
if (hasDuplicate) {
return proxy?.$modal.msgError('存在重复的版本号+物资组合,请修正后提交');
}
// 2. 校验数量合法性(检查是否有数量错误)
const hasQuantityError = form.value.planList.some((row) => row.quantityError);
if (hasQuantityError) {
return proxy?.$modal.msgError('存在非法数量,请修正后提交');
}
// 3. 执行表单基础验证
const result = validateAndClean(form.value.planList);
if (!result.valid) {
return proxy?.$modal.msgError(result.message);
}
// 4. 表单组件验证
cailiaoshebeiFormRef.value?.validate(async (valid: boolean) => {
if (valid) {
buttonLoading.value = true;
form.value.planList = result.data;
await updateCailiaoshebei(form.value).finally(() => (buttonLoading.value = false));
if (!valid) return;
buttonLoading.value = true;
try {
// 5. 提交数据
await updateCailiaoshebei({
...form.value,
planList: result.data // 使用清洗后的数据
});
proxy?.$modal.msgSuccess('操作成功');
dialog.visible = false;
// 6. 刷新列表
await getList();
} catch (error) {
proxy?.$modal.msgError('操作失败,请重试');
} finally {
buttonLoading.value = false;
}
});
};
/** 删除批次 */
const handleDeleteBatch = async () => {
const _ids = batchTreeRef.value.getCurrentNode()?.id;
await proxy?.$modal.confirm('是否确认删除批次编号为"' + _ids + '"的数据项?').finally(() => (loading.value = false));
await delBatch(_ids);
proxy?.$modal.msgSuccess('删除成功');
queryParams.value.mainData.mrpBaseId = undefined;
await getList();
const _id = batchTreeRef.value?.getCurrentNode()?.id;
if (!_id) {
return proxy?.$modal.msgError('请先选择批次');
}
try {
await proxy?.$modal.confirm('是否确认删除该批次?删除后不可恢复!');
await delBatch(_id);
proxy?.$modal.msgSuccess('删除成功');
// 重置选中状态并刷新列表
queryParams.value.mainData.mrpBaseId = undefined;
form.value.mrpBaseBo.status = undefined;
await getList();
} catch (error) {
// 取消确认时不提示错误
if (error !== 'cancel') {
proxy?.$modal.msgError('删除失败');
}
}
};
interface ValidateResult {
valid: boolean;
data: any[];
errors: { index: number; field: string; message: string }[];
}
/** 数据清洗与基础校验 */
function validateAndClean(arr: PlanListItem[]) {
// 1. 过滤掉全空的数据项
const cleanedArr = arr.filter((item) => !Object.values(item).every((v) => v === '' || v == null || v === undefined));
function validateAndClean(arr: any[]) {
// 过滤掉全空的数据项
const cleanedArr = arr.filter((item) => !Object.values(item).every((v) => v === '' || v == null));
let hasFullItem = false; // 是否有至少一条全填数据
let hasFullItem = false; // 是否有至少一条完整数据
// 2. 逐行校验必填项
for (let idx = 0; idx < cleanedArr.length; idx++) {
const item = cleanedArr[idx];
const keys = Object.keys(item).filter((k) => k !== 'remark' && k !== 'id');
const allFilled = keys.every((k) => item[k] !== '' && item[k] != null);
const allEmpty = Object.values(item).every((v) => v === '' || v == null);
// 校验版本号
if (!item.versions) {
return { valid: false, message: `${idx + 1}行:版本号不能为空`, data: cleanedArr };
}
// 单独检查 qs 和 arrivalTime
// 校验物资选择
if (!item.suppliespriceId) {
return { valid: false, message: `${idx + 1}行:请选择物资名称`, data: cleanedArr };
}
// 校验质量标准
if (!item.qs) {
return { valid: false, message: `${idx + 1}行:质量标准不能为空`, data: cleanedArr };
}
// 校验需求到货时间
if (!item.arrivalTime) {
return { valid: false, message: `${idx + 1}行:需求到货时间不能为空`, data: cleanedArr };
}
// 检查其他字段是否部分填
if (!allFilled && !allEmpty) {
return { valid: false, message: `${idx + 1}行:主要信息存在部分字段缺失的数据项`, data: cleanedArr };
// 校验数量必填且≥0
if (item.demandQuantity === null || item.demandQuantity === undefined || item.demandQuantity < 0) {
return { valid: false, message: `${idx + 1}行:请输入合法的需求数量`, data: cleanedArr };
}
if (allFilled) {
hasFullItem = true;
}
hasFullItem = true;
}
// 检查是否至少有一条完整数据
// 3. 检查是否至少有一条完整数据
if (!hasFullItem) {
return { valid: false, message: '至少需要一条完整的数据', data: cleanedArr };
return { valid: false, message: '至少需要填写一条完整的物资数据', data: cleanedArr };
}
return { valid: true, message: '', data: cleanedArr };
@ -506,54 +720,95 @@ function validateAndClean(arr: any[]) {
/** 审核按钮操作 */
const handleAudit = async () => {
if (!form.value.mrpBaseBo.status) {
proxy?.$modal.msgError('请选择批次号');
return;
return proxy?.$modal.msgError('请选择批次号');
}
if (!queryParams.value.mainData.mrpBaseId) {
return proxy?.$modal.msgError('请选择批次号');
}
// 关闭当前页并打开审核页
proxy?.$tab.closePage(route);
proxy?.$tab.openPage('/approval/batchPlan/indexEdit', '审核物资设备批次需求计划', {
id: queryParams.value.mainData.mrpBaseId,
status: form.value.mrpBaseBo.status + '_batchRequirements',
status: `${form.value.mrpBaseBo.status}_batchRequirements`,
type: 'update'
});
};
const getNameList = (versions) => {
coryEngineeringList({ projectId: currentProject.value?.id, versions }).then((res) => {
nameList.value = res.data;
});
};
// 获取版本号
const getVersion = () => {
obtainTheVersion({ projectId: currentProject.value?.id }).then((res) => {
versionList.value = res.data;
});
};
const selectNameVersion = (val, row) => {
row.suppliespriceId = undefined;
getNameList(val);
/** 获取物资列表(按版本号筛选) */
const getNameList = (versions: string) => {
coryEngineeringList({
projectId: currentProject.value?.id,
versions
})
.then((res: any) => {
nameList.value = res.data || [];
})
.catch(() => {
nameList.value = [];
proxy?.$modal.msgError('获取物资列表失败');
});
};
/** 获取版本号列表 */
const getVersion = () => {
obtainTheVersion({ projectId: currentProject.value?.id })
.then((res: any) => {
versionList.value = res.data || [];
})
.catch(() => {
versionList.value = [];
proxy?.$modal.msgError('获取版本号失败');
});
};
/** 选择版本号触发(新增索引参数,用于触发重复校验) */
const selectNameVersion = (val: string, row: PlanListItem, index: number) => {
row.versions = val;
row.suppliespriceId = undefined; // 切换版本号时清空物资选择
row.name = undefined;
row.specification = undefined;
row.unit = undefined;
row.qs = undefined;
row.remark = undefined;
row.arrivalTime = undefined;
row.demandQuantity = undefined;
row.quantityError = '';
row.duplicateError = '';
// 1. 获取对应版本的物资列表
getNameList(val);
// 2. 触发重复校验(清空物资后可能消除重复)
checkDuplicate();
};
/** 页面挂载时初始化 */
onMounted(() => {
getList();
// getNameList();
getVersion();
});
//监听项目id刷新数据
/** 监听项目ID变化刷新数据 */
const listeningProject = watch(
() => currentProject.value?.id,
(nid, oid) => {
queryParams.value.mainData.projectId = nid;
queryParams.value.batchData.projectId = nid;
form.value.mrpBaseBo.projectId = nid;
getList();
(newId, oldId) => {
if (newId !== oldId && newId) {
queryParams.value.mainData.projectId = newId;
queryParams.value.batchData.projectId = newId;
form.value.mrpBaseBo.projectId = newId;
getList();
getVersion(); // 重新获取对应项目的版本号
}
}
);
/** 页面卸载时清理监听 */
onUnmounted(() => {
listeningProject();
});
</script>
<style scoped lang="scss">
.custom-tree-node {
flex: 1;
@ -563,4 +818,17 @@ onUnmounted(() => {
font-size: 14px;
padding-right: 8px;
}
/* 错误提示样式补充 */
.text-red-500 {
color: #f56c6c;
}
.text-xs {
font-size: 12px;
}
.dialog-footer {
text-align: right;
}
</style>

View File

@ -156,18 +156,38 @@
<el-form-item
label="库存"
:prop="`itemList.${index}.stockQuantity`"
:rules="[{ required: true, message: '库存不能为空', trigger: 'blur' }]"
:rules="[
{ required: true, message: '库存不能为空', trigger: 'blur' },
{ type: 'number', min: 0, message: '库存不能小于0', trigger: ['blur', 'change'] }
]"
>
<el-input v-model="item.stockQuantity" placeholder="请输入库存" />
<el-input
v-model.number="item.stockQuantity"
placeholder="请输入库存"
@input="handleStockChange(index)"
@blur="handleStockChange(index)"
/>
</el-form-item>
</el-col>
<el-col :span="12">
<el-form-item
label="领取"
:prop="`itemList.${index}.issuedQuantity`"
:rules="[{ required: true, message: '领取数量不能为空', trigger: 'blur' }]"
:rules="[
{ required: true, message: '领取数量不能为空', trigger: 'blur' },
{ type: 'number', min: 0, message: '领取数量不能小于0', trigger: ['blur', 'change'] },
{
validator: (rule, value, callback) => validateIssuedQuantity(rule, value, callback, index),
trigger: ['blur', 'change']
}
]"
>
<el-input v-model="item.issuedQuantity" placeholder="请输入领取数量" />
<el-input
v-model.number="item.issuedQuantity"
placeholder="请输入领取数量"
@input="handleIssuedChange(index)"
@blur="handleIssuedChange(index)"
/>
</el-form-item>
</el-col>
<el-col :span="12">
@ -176,7 +196,7 @@
:prop="`itemList.${index}.remainingQuantity`"
:rules="[{ required: true, message: '剩余数量不能为空', trigger: 'blur' }]"
>
<el-input v-model="item.remainingQuantity" placeholder="请输入剩余数量" />
<el-input v-model.number="item.remainingQuantity" placeholder="请输入剩余数量" readonly />
</el-form-item>
</el-col>
<el-col :span="12">
@ -248,6 +268,9 @@ import {
import { MaterialIssueVO, MaterialIssueQuery, MaterialIssueForm } from '@/api/materials/materialIssue/types';
import { useUserStoreHook } from '@/store/modules/user';
import wordllssue from './word/index.vue';
import { watch, onMounted, onUnmounted, ref, reactive, computed, getCurrentInstance } from 'vue';
import type { ComponentInternalInstance, ElFormInstance, DialogOption } from 'element-plus';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
// 获取用户 store
const userStore = useUserStoreHook();
@ -265,6 +288,8 @@ const total = ref(0);
const wordllssueRef = ref<InstanceType<typeof wordllssue>>();
const queryFormRef = ref<ElFormInstance>();
const materialIssueFormRef = ref<ElFormInstance>();
// 存储每个条目的watch停止函数
const itemWatchStopFns = ref<Array<() => void>>([]);
const dialog = reactive<DialogOption>({
visible: false,
@ -303,12 +328,14 @@ const getInitFormData = () => {
issuedQuantity: undefined,
remainingQuantity: undefined,
name: undefined,
remark: undefined
remark: undefined,
materialsId: undefined
}
]
};
};
const data = reactive<PageData<MaterialIssueForm, MaterialIssueQuery>>({
const data = reactive({
form: getInitFormData(),
queryParams: {
pageNum: 1,
@ -326,7 +353,13 @@ const data = reactive<PageData<MaterialIssueForm, MaterialIssueQuery>>({
params: {}
},
rules: {
id: [{ required: true, message: '主键id不能为空', trigger: 'blur' }]
formCode: [{ required: true, message: '请输入表单编号', trigger: 'blur' }],
projectName: [{ required: true, message: '请输入工程名称', trigger: 'blur' }],
materialName: [{ required: true, message: '请输入设备材料名称', trigger: 'blur' }],
orderingUnit: [{ required: true, message: '请输入订货单位', trigger: 'blur' }],
supplierUnit: [{ required: true, message: '请输入供货单位', trigger: 'blur' }],
issueUnit: [{ required: true, message: '请输入领料单位', trigger: 'blur' }],
storageUnit: [{ required: true, message: '请输入保管单位', trigger: 'blur' }]
}
});
@ -335,34 +368,94 @@ const { queryParams, form, rules } = toRefs(data);
/** 查询物料领料单列表 */
const getList = async () => {
loading.value = true;
const res = await listMaterialIssue(queryParams.value);
materialIssueList.value = res.rows;
total.value = res.total;
loading.value = false;
};
const optionsName: any = ref([]);
//获取一起名称
const getName = async () => {
const res = await getMaterialName(currentProject.value.id);
console.log(res);
if (res.code == 200) {
optionsName.value = res.data;
try {
const res = await listMaterialIssue(queryParams.value);
materialIssueList.value = res.rows;
total.value = res.total;
} finally {
loading.value = false;
}
};
const optionsName: any = ref([]);
// 获取材料名称列表
const getName = async () => {
try {
const res = await getMaterialName(currentProject.value.id);
if (res.code == 200) {
optionsName.value = res.data;
}
} catch (error) {
proxy?.$modal.msgError('获取材料名称失败');
}
};
// 材料名称选择变化处理
const getNameChange = (value, index, item) => {
// 这里可以添加处理逻辑
console.log(value);
const data = optionsName.value.find((item) => item.id == value);
console.log(data);
if (data) {
form.value.itemList[index].name = data.materialsName;
form.value.itemList[index].materialsId = data.id;
form.value.itemList[index].specification = data.typeSpecificationName;
form.value.itemList[index].unit = data.weightId;
form.value.itemList[index].stockQuantity = data.inventoryNumber;
// 触发剩余数量计算
calculateRemaining(index);
}
};
form.value.itemList[index].name = data.materialsName;
form.value.itemList[index].materialsId = data.id;
form.value.itemList[index].specification = data.typeSpecificationName;
form.value.itemList[index].unit = data.weightId;
form.value.itemList[index].stockQuantity = data.inventoryNumber;
/** 验证领取数量不能超过库存 */
const validateIssuedQuantity = (rule, value, callback, index) => {
const item = form.value.itemList[index];
const stock = Number(item.stockQuantity) || 0;
const issued = Number(value) || 0;
if (stock === 0) {
callback();
return;
}
if (issued > stock) {
callback(new Error(`领取数量不能超过库存(${stock})`));
} else {
callback();
}
};
/** 计算剩余数量(库存 - 领取数量) */
const calculateRemaining = (index: number) => {
const item = form.value.itemList[index];
const stock = Number(item.stockQuantity) || 0;
const issued = Number(item.issuedQuantity) || 0;
// 确保领取数量不超过库存
if (issued > stock) {
item.issuedQuantity = stock;
proxy?.$modal.msgWarning(`领取数量不能超过库存(${stock}),已自动调整`);
}
// 计算剩余数量
item.remainingQuantity = stock - (item.issuedQuantity || 0);
};
/** 库存变化时重新计算剩余数量 */
const handleStockChange = (index: number) => {
calculateRemaining(index);
// 触发验证
if (materialIssueFormRef.value) {
materialIssueFormRef.value.validateField(`itemList.${index}.issuedQuantity`);
materialIssueFormRef.value.validateField(`itemList.${index}.remainingQuantity`);
}
};
/** 领取数量变化时重新计算剩余数量 */
const handleIssuedChange = (index: number) => {
calculateRemaining(index);
// 触发验证
if (materialIssueFormRef.value) {
materialIssueFormRef.value.validateField(`itemList.${index}.remainingQuantity`);
}
};
/** 取消按钮 */
@ -373,8 +466,36 @@ const cancel = () => {
/** 表单重置 */
const reset = () => {
// 停止所有监听
itemWatchStopFns.value.forEach((stop) => stop());
itemWatchStopFns.value = [];
form.value = getInitFormData();
materialIssueFormRef.value?.resetFields();
// 重新监听初始条目
if (form.value.itemList.length > 0) {
watchItemChanges(0);
}
};
/** 监听条目变化,自动计算剩余数量 */
const watchItemChanges = (index: number) => {
// 停止已有监听
if (itemWatchStopFns.value[index]) {
itemWatchStopFns.value[index]();
}
// 监听库存和领取数量变化
const stop = watch(
() => [form.value.itemList[index].stockQuantity, form.value.itemList[index].issuedQuantity],
() => {
calculateRemaining(index);
},
{ immediate: true }
);
itemWatchStopFns.value[index] = stop;
};
/** 搜索按钮操作 */
@ -407,10 +528,42 @@ const handleAdd = () => {
const handleUpdate = async (row?: MaterialIssueVO) => {
reset();
const _id = row?.id || ids.value[0];
const res = await getMaterialIssue(_id);
Object.assign(form.value, res.data);
dialog.visible = true;
dialog.title = '修改物料领料单';
try {
const res = await getMaterialIssue(_id);
Object.assign(form.value, res.data);
// 确保itemList存在
if (!form.value.itemList) {
form.value.itemList = [];
}
// 转换数据类型并计算剩余数量(关键修复)
form.value.itemList = form.value.itemList.map((item) => ({
...item,
stockQuantity: Number(item.stockQuantity) || 0,
issuedQuantity: Number(item.issuedQuantity) || 0,
remainingQuantity: Number(item.remainingQuantity) || 0
}));
// 为每个条目添加监听并强制计算剩余数量
form.value.itemList.forEach((_, index) => {
watchItemChanges(index);
calculateRemaining(index); // 强制计算确保数据一致性
});
// 手动触发一次验证(关键修复)
setTimeout(() => {
if (materialIssueFormRef.value) {
form.value.itemList.forEach((_, index) => {
materialIssueFormRef.value.validateField(`itemList.${index}.issuedQuantity`);
materialIssueFormRef.value.validateField(`itemList.${index}.remainingQuantity`);
});
}
}, 0);
dialog.visible = true;
dialog.title = '修改物料领料单';
} catch (error) {
proxy?.$modal.msgError('获取详情失败');
}
};
/** 提交按钮 */
@ -418,21 +571,38 @@ const submitForm = () => {
materialIssueFormRef.value?.validate(async (valid: boolean) => {
if (valid) {
buttonLoading.value = true;
if (form.value.id) {
await updateMaterialIssue(form.value).finally(() => (buttonLoading.value = false));
} else {
await addMaterialIssue(form.value).finally(() => (buttonLoading.value = false));
try {
// 处理提交数据,确保数量为数字类型
const submitData = {
...form.value,
itemList: form.value.itemList.map((item) => ({
...item,
stockQuantity: Number(item.stockQuantity),
issuedQuantity: Number(item.issuedQuantity),
remainingQuantity: Number(item.remainingQuantity)
}))
};
if (form.value.id) {
await updateMaterialIssue(submitData);
} else {
await addMaterialIssue(submitData);
}
proxy?.$modal.msgSuccess('操作成功');
dialog.visible = false;
await getList();
} catch (error) {
proxy?.$modal.msgError('操作失败');
} finally {
buttonLoading.value = false;
}
proxy?.$modal.msgSuccess('操作成功');
dialog.visible = false;
await getList();
}
});
};
// 添加数量验收条目
const addItem = () => {
form.value.itemList.push({
const newItem = {
id: undefined,
specification: undefined,
unit: undefined,
@ -440,46 +610,68 @@ const addItem = () => {
issuedQuantity: undefined,
remainingQuantity: undefined,
name: undefined,
remark: undefined
});
remark: undefined,
materialsId: undefined
};
form.value.itemList.push(newItem);
// 监听新条目
watchItemChanges(form.value.itemList.length - 1);
};
// 删除数量验收条目
const removeItem = (index: number) => {
if (form.value.itemList.length > 1) {
// 停止该条目的监听
if (itemWatchStopFns.value[index]) {
itemWatchStopFns.value[index]();
}
form.value.itemList.splice(index, 1);
itemWatchStopFns.value.splice(index, 1);
} else {
proxy?.$modal.msgWarning('至少需要保留一条数量验收记录');
}
};
/** 删除按钮操作 */
const handleDelete = async (row?: MaterialIssueVO) => {
const _ids = row?.id || ids.value;
await proxy?.$modal.confirm('是否确认删除物料领料单编号为"' + _ids + '"的数据项?').finally(() => (loading.value = false));
await delMaterialIssue(_ids);
proxy?.$modal.msgSuccess('删除成功');
await getList();
try {
await proxy?.$modal.confirm(`是否确认删除物料领料单编号为"${_ids}"的数据项?`);
await delMaterialIssue(_ids);
proxy?.$modal.msgSuccess('删除成功');
await getList();
} catch (error) {
// 取消删除不提示
} finally {
loading.value = false;
}
};
const handleView = (row) => {
// 查看详情
wordllssueRef.value?.openDialog(row);
};
onMounted(() => {
getList();
getName();
});
//监听项目id刷新数据
// 监听项目id刷新数据
const listeningProject = watch(
() => currentProject.value?.id,
(nid, oid) => {
(nid) => {
queryParams.value.projectId = nid;
form.value.projectId = nid;
getList();
getName();
}
);
onUnmounted(() => {
listeningProject();
// 清理所有监听
itemWatchStopFns.value.forEach((stop) => stop());
});
</script>
<style scoped lang="scss">

View File

@ -57,16 +57,15 @@
<el-table-column label="备注" align="center" prop="remark" />
<el-table-column label="操作" align="center" min-width="120" fixed="right">
<template #default="scope">
<el-tooltip content="查看" placement="top">
<el-button link type="primary" icon="View" @click="handleView(scope.row)" v-hasPermi="['materials:materialReceive:query']"
>查看</el-button
>
</el-tooltip>
<el-tooltip content="删除" placement="top">
<el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['materials:materialReceive:remove']"
>删除</el-button
>
</el-tooltip>
<!-- <el-button link type="primary" icon="edit" @click="handleUpdate(scope.row)" v-hasPermi="['materials:materialReceive:edit']"
>修改</el-button
> -->
<el-button link type="primary" icon="View" @click="handleView(scope.row)" v-hasPermi="['materials:materialReceive:query']"
>查看</el-button
>
<el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['materials:materialReceive:remove']"
>删除</el-button
>
</template>
</el-table-column>
</el-table>
@ -74,7 +73,15 @@
</el-card>
<!-- 添加或修改物料接收单对话框 -->
<el-dialog draggable :title="dialog.title" v-model="dialog.visible" width="800px" append-to-body>
<el-dialog
:close-on-click-modal="false"
:close-on-press-escape="false"
draggable
:title="dialog.title"
v-model="dialog.visible"
width="800px"
append-to-body
>
<el-form ref="materialReceiveFormRef" :model="form" :rules="rules" label-width="110px">
<el-row>
<el-col :span="12">
@ -122,7 +129,6 @@
:value="item.contractCode"
></el-option>
</el-select>
<!-- <el-input v-model="form.contractName" placeholder="请输入合同名称" /> -->
</el-form-item>
</el-col>
<el-col :span="24">
@ -131,14 +137,13 @@
</el-form-item>
</el-col>
<!-- 数量验收区域修复v-for key问题 -->
<!-- 数量验收区域 -->
<el-col :span="24">
<div class="detail">
<div class="detail-header">
<span>数量验收</span>
<el-button type="primary" v-if="form.materialSource == '1'" link @click="addItem" icon="Plus">添加数量验收</el-button>
</div>
<!-- 关键修复v-for key改为item.id唯一标识而非index -->
<div v-for="(item, index) in form.itemList" :key="item.id" class="detail-item">
<el-row>
<el-col :span="12">
@ -161,21 +166,27 @@
</el-form-item>
</el-col>
<el-col :span="12">
<el-form-item
label="数量"
:prop="`itemList.${index}.quantity`"
:rules="{ required: true, message: '数量不能为空', trigger: 'blur' }"
>
<el-input :disabled="form.materialSource == '2'" type="number" v-model="item.quantity" placeholder="请输入数量" />
<el-form-item label="数量" :prop="`itemList.${index}.quantity`" :rules="rules.quantityRule" ref="quantityFormItemRefs[index]">
<el-input
:disabled="form.materialSource == '2'"
type="number"
v-model.number="item.quantity"
placeholder="请输入数量"
min="0"
@input="handleQuantityInput(index)"
@blur="handleQuantityBlur(index)"
/>
</el-form-item>
</el-col>
<el-col :span="12">
<el-form-item
label="验收"
:prop="`itemList.${index}.acceptedQuantity`"
:rules="{ required: true, message: '验收数量不能为空', trigger: 'blur' }"
>
<el-input type="number" v-model="item.acceptedQuantity" placeholder="请输入验收" />
<el-form-item label="验收" :prop="`itemList.${index}.acceptedQuantity`" :rules="rules.acceptedQuantityRule">
<el-input
type="number"
v-model.number="item.acceptedQuantity"
placeholder="请输入验收"
min="0"
@input="handleAcceptedInput(index)"
/>
</el-form-item>
</el-col>
<el-col :span="12">
@ -184,13 +195,13 @@
:prop="`itemList.${index}.shortageQuantity`"
:rules="{ required: true, message: '缺件数量不能为空', trigger: 'blur' }"
>
<el-input type="number" v-model="item.shortageQuantity" placeholder="自动计算(数量-验收数量)" readonly />
<el-input type="number" min="0" v-model="item.shortageQuantity" placeholder="自动计算" readonly />
<span class="tips">*自动计算数量-验收数量</span>
</el-form-item>
</el-col>
<el-col :span="12">
<el-col :span="24">
<el-form-item label="备注" :prop="`itemList.${index}.remark`">
<el-input v-model="item.remark" placeholder="请输入备注" />
<el-input v-model="item.remark" type="textarea" placeholder="请输入备注" />
</el-form-item>
</el-col>
<el-col :span="12" v-if="form.itemList.length > 1 && form.materialSource == '1'">
@ -205,26 +216,26 @@
<el-col :span="12">
<el-form-item label="合格证文件" prop="certCountFileId">
<file-upload :isShowTip="false" v-model="form.certCountFileId" />
<file-upload :isShowTip="false" :fileType="['pdf', 'png', 'jpg', 'jpeg']" v-model="form.certCountFileId" />
</el-form-item>
</el-col>
<el-col :span="12">
<el-form-item label="出厂报告文件" prop="reportCountFileId">
<file-upload :isShowTip="false" v-model="form.reportCountFileId" />
<file-upload :isShowTip="false" :fileType="['pdf', 'png', 'jpg', 'jpeg']" v-model="form.reportCountFileId" />
</el-form-item>
</el-col>
<el-col :span="12">
<el-form-item label="技术资料文件" prop="techDocCountFileId">
<file-upload :isShowTip="false" v-model="form.techDocCountFileId" />
<file-upload :isShowTip="false" :fileType="['pdf', 'png', 'jpg', 'jpeg']" v-model="form.techDocCountFileId" />
</el-form-item>
</el-col>
<el-col :span="12">
<el-form-item label="厂家资质文件" prop="licenseCountFileId">
<file-upload :isShowTip="false" v-model="form.licenseCountFileId" />
<file-upload :isShowTip="false" :fileType="['pdf', 'png', 'jpg', 'jpeg']" v-model="form.licenseCountFileId" />
</el-form-item>
</el-col>
<el-col :span="24">
<span style="color: #ff0000ab; margin-bottom: 10px; display: block">注意请上传doc/xls/ppt/txt/pdf/png/jpg/jpeg/zip格式文件</span>
<span style="color: #ff0000ab; margin-bottom: 10px; display: block">注意pdf/png/jpg/jpeg格式文件</span>
</el-col>
<el-col :span="24">
<el-form-item label="备注" prop="remark">
@ -258,7 +269,7 @@ import { useUserStoreHook } from '@/store/modules/user';
import wordllReceive from './word/index.vue';
import { listPurchaseDoc, purchaseDocPlanList } from '@/api/materials/purchaseDoc';
import { watch, onMounted, onUnmounted, ref, reactive, computed, toRefs, getCurrentInstance } from 'vue';
import type { ComponentInternalInstance, ElFormInstance, DialogOption } from 'element-plus';
import type { ComponentInternalInstance, ElFormInstance, DialogOption, ElFormItem } from 'element-plus';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { storage_type } = toRefs<any>(proxy?.useDict('storage_type'));
@ -266,8 +277,10 @@ const userStore = useUserStoreHook();
const currentProject = computed(() => userStore.selectedProject);
const wordllReceiveRef = ref<InstanceType<typeof wordllReceive>>();
// 核心修复1存储每个验收条目的watch停止函数,避免内存泄漏
// 存储每个验收条目的watch停止函数
const itemWatchStopFns = ref<Array<() => void>>([]);
// 存储数量表单项的引用,用于手动触发验证
const quantityFormItemRefs = ref<(ElFormItem | null)[]>([]);
// 列表数据
const materialReceiveList = ref<MaterialReceiveVO[]>([]);
@ -285,18 +298,19 @@ const materialReceiveFormRef = ref<ElFormInstance>();
const purchaseDocList = ref([]); // 物资采购单列表
const purchaseMap = new Map(); // 采购单映射id -> 采购单对象)
const contractNameList = ref([]); //合同列表
// 对话框配置
const dialog = reactive<DialogOption>({
visible: false,
title: ''
});
// 生成验收条目唯一ID用于v-for key
// 生成验收条目唯一ID
const generateItemId = () => {
return Date.now() + Math.random().toString(36).substr(2, 9);
};
// 初始化表单数据修复给验收条目添加唯一ID
// 初始化表单数据
const getInitFormData = (): MaterialReceiveForm => {
return {
id: undefined,
@ -323,7 +337,7 @@ const getInitFormData = (): MaterialReceiveForm => {
docCode: undefined,
itemList: [
{
id: generateItemId(), // 新增唯一ID解决v-for渲染问题
id: generateItemId(),
name: undefined,
specification: undefined,
unit: undefined,
@ -357,7 +371,38 @@ const data = reactive({
formCode: [{ required: true, message: '请输入表单编号', trigger: 'blur' }],
docId: [{ required: true, message: '请选择物资采购单', trigger: 'change' }],
supplierUnit: [{ required: true, message: '请输入供货单位', trigger: 'blur' }],
orderingUnit: [{ required: true, message: '请输入订货单位', trigger: 'blur' }]
orderingUnit: [{ required: true, message: '请输入订货单位', trigger: 'blur' }],
// 数量校验规则确保触发时机包含change且类型为number
quantityRule: [
{ required: true, message: '数量不能为空', trigger: ['blur', 'change'] },
{ type: 'number', min: 0, message: '数量不能小于0', trigger: ['blur', 'change'] }
],
// 验收数量规则(允许≤数量)
acceptedQuantityRule: [
{ required: true, message: '验收数量不能为空', trigger: ['blur', 'change'] },
{ type: 'number', min: 0, message: '验收数量不能小于0', trigger: ['blur', 'change'] },
{
validator: (rule, value, callback) => {
const prop = rule.field;
const index = Number(prop.split('.')[1]);
const quantity = Number(form.value.itemList[index].quantity) || 0;
// 数量未填写时不验证大小关系数量有值但验收数量未填时也不阻断由required规则处理
if (form.value.itemList[index].quantity === undefined || form.value.itemList[index].quantity === null) {
callback();
return;
}
// 处理value为undefined/null的情况避免Number(undefined)转为NaN
const acceptedVal = Number(value) || 0;
if (acceptedVal > quantity) {
callback(new Error('验收数量必须小于等于数量'));
} else {
callback();
}
},
trigger: ['blur', 'change']
}
]
}
});
@ -374,25 +419,29 @@ const getList = async () => {
loading.value = false;
}
};
// 获取合同列表数据
const getContractList = async () => {
let res = await getContractNameList(currentProject.value?.id);
contractNameList.value = res.rows;
};
/** 取消按钮 */
const cancel = () => {
reset();
dialog.visible = false;
};
/** 表单重置(修复:清理验收条目监听) */
/** 表单重置 */
const reset = () => {
// 停止所有验收条目的watch监听
itemWatchStopFns.value.forEach((stopFn) => stopFn());
itemWatchStopFns.value = [];
form.value = getInitFormData();
materialReceiveFormRef.value?.resetFields();
if (materialReceiveFormRef.value) {
materialReceiveFormRef.value.resetFields();
}
// 重新监听初始条目
if (form.value.itemList.length > 0) {
@ -408,7 +457,9 @@ const handleQuery = () => {
/** 重置按钮操作 */
const resetQuery = () => {
queryFormRef.value?.resetFields();
if (queryFormRef.value) {
queryFormRef.value.resetFields();
}
handleQuery();
};
@ -427,24 +478,35 @@ const handleAdd = () => {
form.value.projectName = currentProject.value?.name;
};
/** 修改按钮操作(修复:清理旧监听+添加唯一ID */
/** 修改按钮操作(核心修复:赋值后主动触发验证+数据类型转换 */
const handleUpdate = async (row?: MaterialReceiveVO) => {
reset();
const _id = row?.id || ids.value[0];
try {
const res = await getMaterialReceive(_id);
// 给验收条目补充唯一ID避免后端返回无ID
const formData = res.data;
// 修复1处理itemList数据类型确保数量/验收数量为数字避免字符串与number规则冲突
formData.itemList = formData.itemList.map((item) => ({
...item,
id: item.id || generateItemId()
id: item.id || generateItemId(),
quantity: item.quantity !== undefined ? Number(item.quantity) : undefined, // 转为数字
acceptedQuantity: item.acceptedQuantity !== undefined ? Number(item.acceptedQuantity) : undefined, // 转为数字
shortageQuantity: item.shortageQuantity !== undefined ? Number(item.shortageQuantity) : undefined // 转为数字
}));
Object.assign(form.value, formData);
// 重新监听所有条目
// 修复2重新监听所有条目,并主动触发每个条目的验证(更新验证状态)
form.value.itemList.forEach((_, index) => {
watchItemChanges(index);
// 手动触发当前条目的数量、验收数量、缺件数量验证
if (materialReceiveFormRef.value) {
materialReceiveFormRef.value.validateField(`itemList.${index}.quantity`, () => {});
materialReceiveFormRef.value.validateField(`itemList.${index}.acceptedQuantity`, () => {});
materialReceiveFormRef.value.validateField(`itemList.${index}.shortageQuantity`, () => {});
}
});
dialog.visible = true;
@ -460,13 +522,24 @@ const submitForm = () => {
if (valid) {
buttonLoading.value = true;
try {
// 提交前确保数据类型正确(数字)
const submitForm = {
...form.value,
itemList: form.value.itemList.map((item) => ({
...item,
quantity: Number(item.quantity),
acceptedQuantity: Number(item.acceptedQuantity),
shortageQuantity: Number(item.shortageQuantity)
}))
};
if (form.value.id) {
await updateMaterialReceive({ ...form.value });
await updateMaterialReceive(submitForm);
} else {
form.value.itemList.forEach((item) => {
submitForm.itemList.forEach((item) => {
delete item.id;
});
await addMaterialReceive({ ...form.value });
await addMaterialReceive(submitForm);
}
proxy?.$modal.msgSuccess('操作成功');
dialog.visible = false;
@ -495,10 +568,10 @@ const handleDelete = async (row?: MaterialReceiveVO) => {
}
};
/** 添加数量验收条目修复添加唯一ID+监听) */
/** 添加数量验收条目 */
const addItem = () => {
const newItem = {
id: generateItemId(), // 唯一ID
id: generateItemId(),
name: undefined,
specification: undefined,
unit: undefined,
@ -508,33 +581,79 @@ const addItem = () => {
remark: undefined
};
form.value.itemList.push(newItem);
// 监听新条目变化
// 监听新条目变化并触发初始验证
watchItemChanges(form.value.itemList.length - 1);
validateQuantityField(form.value.itemList.length - 1);
};
/** 监听验收条目变化,自动计算缺件数量(修复:存储停止函数) */
// 数量输入事件处理
const handleQuantityInput = (index: number) => {
// 确保值为数字类型
if (form.value.itemList[index].quantity !== undefined) {
form.value.itemList[index].quantity = Number(form.value.itemList[index].quantity);
}
// 手动触发验证
validateQuantityField(index);
};
// 数量失焦事件
const handleQuantityBlur = (index: number) => {
validateQuantityField(index);
};
// 验收数量输入事件
const handleAcceptedInput = (index: number) => {
// 确保值为数字类型
if (form.value.itemList[index].acceptedQuantity !== undefined) {
form.value.itemList[index].acceptedQuantity = Number(form.value.itemList[index].acceptedQuantity);
}
// 手动触发相关字段验证
validateQuantityField(index);
};
// 手动验证数量和验收数量字段
const validateQuantityField = (index: number) => {
if (materialReceiveFormRef.value) {
materialReceiveFormRef.value.validateField(`itemList.${index}.quantity`, () => {});
materialReceiveFormRef.value.validateField(`itemList.${index}.acceptedQuantity`, () => {});
materialReceiveFormRef.value.validateField(`itemList.${index}.shortageQuantity`, () => {});
}
};
// 监听条目变化,自动计算缺件数量(修复:计算后触发验证)
const watchItemChanges = (index: number) => {
// 停止该索引已有的监听(避免重复监听)
if (itemWatchStopFns.value[index]) {
itemWatchStopFns.value[index]();
}
// 监听数量和验收数量变化
const stopFn = watch(
() => [form.value.itemList[index].quantity, form.value.itemList[index].acceptedQuantity],
([quantity, acceptedQuantity]) => {
const qty = Number(quantity) || 0;
const acceptedQty = Number(acceptedQuantity) || 0;
let acceptedQty = Number(acceptedQuantity) || 0;
// 仅当验收数量>数量时才修正(允许等于)
if (acceptedQty > qty && qty > 0) {
acceptedQty = qty; // 修正为数量值(最大合法值)
form.value.itemList[index].acceptedQuantity = acceptedQty;
proxy?.$modal.msgWarning(`验收数量不能大于数量,已自动修正为${acceptedQty}`);
}
// 计算缺件数量允许为0
form.value.itemList[index].shortageQuantity = qty - acceptedQty;
// 修复3计算后触发当前条目的验证确保缺件数量状态更新
validateQuantityField(index);
},
{ immediate: true } // 初始时立即计算
{ immediate: true }
);
// 存储停止函数,用于后续删除时清理
itemWatchStopFns.value[index] = stopFn;
};
/** 删除数量验收条目(修复:清理监听+删除条目) */
/** 删除数量验收条目 */
const removeItem = (index: number) => {
if (form.value.itemList.length <= 1) {
proxy?.$modal.msgWarning('至少需要保留一条数量验收记录');
@ -549,6 +668,7 @@ const removeItem = (index: number) => {
// 删除条目和对应的停止函数
form.value.itemList.splice(index, 1);
itemWatchStopFns.value.splice(index, 1);
quantityFormItemRefs.value.splice(index, 1);
};
/** 查看详情 */
@ -564,7 +684,6 @@ const getlistPurchase = async () => {
status: 'finish'
});
purchaseDocList.value = res.rows;
// 构建采购单映射
purchaseDocList.value.forEach((item) => {
purchaseMap.set(item.id, item);
});
@ -573,7 +692,7 @@ const getlistPurchase = async () => {
}
};
/** 通过采购单获取需求信息(修复:清理旧监听+添加新监听 */
/** 通过采购单获取需求信息(修复:数据类型转换 */
const getdemandInfo = async (docId: string) => {
if (!docId) return;
@ -583,25 +702,25 @@ const getdemandInfo = async (docId: string) => {
// 清空旧监听和条目
itemWatchStopFns.value.forEach((stopFn) => stopFn());
itemWatchStopFns.value = [];
quantityFormItemRefs.value = [];
form.value.itemList = [];
// 赋值需求数据并添加监听
// 赋值需求数据并添加监听(确保数量为数字)
res.data.forEach((item, index) => {
const qty = Number(item.demandQuantity) || 0;
const newItem = {
id: generateItemId(), // 唯一ID
id: generateItemId(),
name: item.name,
specification: item.specification,
unit: item.unit,
quantity: qty,
acceptedQuantity: 0,
shortageQuantity: qty, // 初始缺件=数量
quantity: qty, // 确保数字类型
acceptedQuantity: 0, // 初始值为0数字
shortageQuantity: qty, // 初始缺件=数量(数字)
remark: item.remark,
planId: item.id,
id: null // 保留后端需要的空id字段
id: null
};
form.value.itemList.push(newItem);
// 监听当前条目
watchItemChanges(index);
});
}
@ -621,21 +740,25 @@ const handleSelect = (val: string) => {
form.value.materialName = obj.name || '';
}
// 获取采购单对应的需求信息
getdemandInfo(val);
};
/** 核心修复2监听材料来源变化,重置数量验收列表 */
/** 监听材料来源变化,重置数量验收列表 */
watch(
() => form.value.materialSource,
(newSource, oldSource) => {
if (newSource === oldSource) return;
// 1. 停止所有验收条目的监听
// 停止所有验收条目的监听
itemWatchStopFns.value.forEach((stopFn) => stopFn());
itemWatchStopFns.value = [];
// 2. 重置数量验收列表为初始状态1条空记录
quantityFormItemRefs.value = [];
// 清空所有文件上传字段的值
form.value.certCountFileId = undefined; // 合格证文件
form.value.reportCountFileId = undefined; // 出厂报告文件
form.value.techDocCountFileId = undefined; // 技术资料文件
form.value.licenseCountFileId = undefined; // 厂家资质文件
// 重置数量验收列表为初始状态
form.value.itemList = [
{
id: generateItemId(),
@ -649,10 +772,11 @@ watch(
}
];
// 3. 重新监听初始条目
// 重新监听初始条目并触发验证
watchItemChanges(0);
validateQuantityField(0);
// 4. 切换到乙供时,清空采购单相关数据
// 切换到乙供时,清空采购单相关数据
if (newSource === '2') {
form.value.docId = undefined;
form.value.supplierUnit = undefined;
@ -668,9 +792,10 @@ onMounted(() => {
getContractList();
getList();
getlistPurchase();
// 监听初始验收条目
// 监听初始验收条目并触发验证
if (form.value.itemList.length > 0) {
watchItemChanges(0);
validateQuantityField(0);
}
});
@ -689,7 +814,6 @@ const listeningProject = watch(
/** 页面卸载时清理监听 */
onUnmounted(() => {
listeningProject();
// 清理验收条目监听
itemWatchStopFns.value.forEach((stopFn) => stopFn());
});
</script>

View File

@ -116,6 +116,9 @@
<el-button link type="primary" icon="View" @click="handleDetail(scope.row)" v-hasPermi="['cailiaoshebei:purchaseDoc:remove']"
>详情</el-button
>
<el-button link type="primary" icon="Download" @click="handleDownload(scope.row)" v-hasPermi="['cailiaoshebei:purchaseDoc:downloadWord']"
>下载</el-button
>
</template>
</el-table-column>
</el-table>
@ -379,6 +382,15 @@ const cancel = () => {
reset();
dialog.visible = false;
};
const handleDownload = async (row) => {
proxy?.download(
'/cailiaoshebei/purchaseDoc/export/word',
{
id: row.id
},
`${row.docCode}.doc`
);
};
const handleDetail = async (row?: PurchaseDocVO) => {
proxy?.$modal.loading('加载中');