Commit 09dec86f by Lin

feat: 提成方案表单校验

1 parent cccf21a7
...@@ -67,7 +67,7 @@ ...@@ -67,7 +67,7 @@
</el-form-item> </el-form-item>
<el-form-item label="适配业务:" prop="businessType"> <el-form-item label="适配业务:" prop="businessType">
<el-radio-group v-model="businessType"> <el-radio-group v-model="businessType" @change="handleBusinessTypeChange">
<el-radio :label="0"> <el-radio :label="0">
轻改 轻改
</el-radio> </el-radio>
...@@ -148,6 +148,8 @@ export default { ...@@ -148,6 +148,8 @@ export default {
// TODO: 强力设置表格内的所有goodType // TODO: 强力设置表格内的所有goodType
} }
// 只验证当前字段
this.validateCurrentField("goodsConfigTypes");
}, },
/** /**
...@@ -209,6 +211,8 @@ export default { ...@@ -209,6 +211,8 @@ export default {
this.setCommissionTypes(newTypes); this.setCommissionTypes(newTypes);
this.$nextTick(() => { this.$nextTick(() => {
this.isUpdating = false; this.isUpdating = false;
// 只验证当前字段
this.validateCurrentField("commissionBases");
}); });
}, },
...@@ -221,6 +225,8 @@ export default { ...@@ -221,6 +225,8 @@ export default {
this.setCommissionBases(newBases); this.setCommissionBases(newBases);
this.$nextTick(() => { this.$nextTick(() => {
this.isUpdating = false; this.isUpdating = false;
// 只验证当前字段
this.validateCurrentField("commissionTypes");
}); });
}, },
...@@ -228,6 +234,20 @@ export default { ...@@ -228,6 +234,20 @@ export default {
// 根据 value 数组从 assessmentFactorOptions 中找出对应的完整项 // 根据 value 数组从 assessmentFactorOptions 中找出对应的完整项
const selectedItems = this.assessmentFactorOptions.filter(item => value.includes(item.value)); const selectedItems = this.assessmentFactorOptions.filter(item => value.includes(item.value));
this.touchAssessment(selectedItems); this.touchAssessment(selectedItems);
// 只验证当前字段
this.validateCurrentField("assessmentFactorValue");
},
handleBusinessTypeChange() {
// 只验证当前字段
this.validateCurrentField("businessType");
},
// 验证当前字段(只验证单个字段,不触发全表单验证)
validateCurrentField(prop) {
// 通过 $parent 访问父组件的表单引用
const form = this.$parent?.$refs?.form;
if (form && !this.$parent?.shouldValidateAll) {
form.validateField(prop, () => {});
}
}, },
}, },
}; };
......
...@@ -36,7 +36,8 @@ ...@@ -36,7 +36,8 @@
:picker-options="pickerOptions" :picker-options="pickerOptions"
placeholder="请选择" placeholder="请选择"
type="month" type="month"
value-format="yyyy-MM"> value-format="yyyy-MM"
@change="handleEffectiveMonthChange">
</el-date-picker> </el-date-picker>
</el-form-item> </el-form-item>
<el-dialog v-if="dialog.storeApply.visible" <el-dialog v-if="dialog.storeApply.visible"
...@@ -165,6 +166,18 @@ export default { ...@@ -165,6 +166,18 @@ export default {
this.setMerchantBrandRefList(deepClone(selectedMerchantList)); this.setMerchantBrandRefList(deepClone(selectedMerchantList));
this.changeStoreApplyVisible(); this.changeStoreApplyVisible();
}, },
handleEffectiveMonthChange() {
// 只验证当前字段
this.validateCurrentField("effectiveMonth");
},
// 验证当前字段(只验证单个字段,不触发全表单验证)
validateCurrentField(prop) {
// 通过 $parent 访问父组件的表单引用
const form = this.$parent?.$refs?.form;
if (form && !this.$parent?.shouldValidateAll) {
form.validateField(prop, () => {});
}
},
}, },
}; };
</script> </script>
......
...@@ -108,17 +108,31 @@ function getPerformanceParamConfigConditions(paramsType2Item, paramsConfig) { ...@@ -108,17 +108,31 @@ function getPerformanceParamConfigConditions(paramsType2Item, paramsConfig) {
const conditionParamsData = paramsType2Item[`conditionType${paramsType2Item.condition}`]; const conditionParamsData = paramsType2Item[`conditionType${paramsType2Item.condition}`];
console.log(paramsConfig.goodsCategory === 0 // 如果 conditionParamsData 不存在,直接返回空的 conditionItem
? buildGoodsTypePayload(goodsCategory, conditionParamsData.productValue, buildGoodsTypePayloadOptions) if (!conditionParamsData) {
: buildProductDefinePayload(productDefineList, conditionParamsData.productValue, buildProductDefinePayloadOptions)); return conditionItem;
}
if (paramsType2Item.condition === 1) { if (paramsType2Item.condition === 1) {
// 检查四个渗透率字段是否有值
const hasPermeabilityValue
= (conditionParamsData.permeabilityMax !== undefined && conditionParamsData.permeabilityMax !== null && conditionParamsData.permeabilityMax !== "")
|| (conditionParamsData.permeabilityMax1 !== undefined && conditionParamsData.permeabilityMax1 !== null && conditionParamsData.permeabilityMax1 !== "")
|| (conditionParamsData.permeabilityMin !== undefined && conditionParamsData.permeabilityMin !== null && conditionParamsData.permeabilityMin !== "")
|| (conditionParamsData.permeabilityMin1 !== undefined && conditionParamsData.permeabilityMin1 !== null && conditionParamsData.permeabilityMin1 !== "");
// 如果四个渗透率字段全部没有值,直接返回空的 conditionItem,不进行后续处理
if (!hasPermeabilityValue) {
return conditionItem;
}
extend.conditionStartValue = conditionParamsData.permeabilityMin; extend.conditionStartValue = conditionParamsData.permeabilityMin;
extend.conditionEndValue = conditionParamsData.permeabilityMax; extend.conditionEndValue = conditionParamsData.permeabilityMax;
extend = { extend = {
...extend, ...extend,
...paramsConfig.goodsCategory === 0 ...paramsConfig.goodsCategory === 0
? buildGoodsTypePayload(goodsCategory, conditionParamsData.productValue, buildGoodsTypePayloadOptions) ? buildGoodsTypePayload(goodsCategory, conditionParamsData.productValue || [], buildGoodsTypePayloadOptions)
: buildProductDefinePayload(productDefineList, conditionParamsData.productValue, buildProductDefinePayloadOptions), : buildProductDefinePayload(productDefineList, conditionParamsData.productValue || [], buildProductDefinePayloadOptions),
}; };
conditionItem.push({ conditionItem.push({
conditionType: paramsType2Item.condition, conditionType: paramsType2Item.condition,
...@@ -126,8 +140,8 @@ function getPerformanceParamConfigConditions(paramsType2Item, paramsConfig) { ...@@ -126,8 +140,8 @@ function getPerformanceParamConfigConditions(paramsType2Item, paramsConfig) {
conditionEndValue: conditionParamsData.permeabilityMax1, conditionEndValue: conditionParamsData.permeabilityMax1,
conditionGoodsConfigType: paramsConfig.goodsCategory, conditionGoodsConfigType: paramsConfig.goodsCategory,
...paramsConfig.goodsCategory === 0 ...paramsConfig.goodsCategory === 0
? buildGoodsTypePayload(goodsCategory, conditionParamsData.productValue1, buildGoodsTypePayloadOptions) ? buildGoodsTypePayload(goodsCategory, conditionParamsData.productValue1 || [], buildGoodsTypePayloadOptions)
: buildProductDefinePayload(productDefineList, conditionParamsData.productValue1, buildProductDefinePayloadOptions), : buildProductDefinePayload(productDefineList, conditionParamsData.productValue1 || [], buildProductDefinePayloadOptions),
}); });
} }
if (paramsType2Item.condition === 2) { if (paramsType2Item.condition === 2) {
...@@ -141,8 +155,8 @@ function getPerformanceParamConfigConditions(paramsType2Item, paramsConfig) { ...@@ -141,8 +155,8 @@ function getPerformanceParamConfigConditions(paramsType2Item, paramsConfig) {
extend = { extend = {
...extend, ...extend,
...paramsConfig.goodsCategory === 0 ...paramsConfig.goodsCategory === 0
? buildGoodsTypePayload(goodsCategory, conditionParamsData.productValue, buildGoodsTypePayloadOptions) ? buildGoodsTypePayload(goodsCategory, conditionParamsData.productValue || [], buildGoodsTypePayloadOptions)
: buildProductDefinePayload(productDefineList, conditionParamsData.productValue, buildProductDefinePayloadOptions), : buildProductDefinePayload(productDefineList, conditionParamsData.productValue || [], buildProductDefinePayloadOptions),
}; };
} }
...@@ -159,6 +173,15 @@ function buildProductDefinePayload(tree, pathIds, options = { ...@@ -159,6 +173,15 @@ function buildProductDefinePayload(tree, pathIds, options = {
name: "productDefineName", name: "productDefineName",
type: "goodsConfigType", type: "goodsConfigType",
}) { }) {
// 如果 pathIds 不存在或不是数组,返回空对象
if (!pathIds || !Array.isArray(pathIds) || pathIds.length === 0) {
return {
[options.id]: null,
[options.name]: null,
[options.type]: null,
};
}
let currentLevel = tree; let currentLevel = tree;
let targetNode = null; let targetNode = null;
...@@ -186,7 +209,11 @@ function buildGoodsTypePayload(tree, pathIds, options = { ...@@ -186,7 +209,11 @@ function buildGoodsTypePayload(tree, pathIds, options = {
}) { }) {
const result = {}; const result = {};
let currentLevel = tree;
// 如果 pathIds 不存在或不是数组,返回空对象
if (!pathIds || !Array.isArray(pathIds) || pathIds.length === 0) {
return result;
}
pathIds.forEach((id, index) => { pathIds.forEach((id, index) => {
let node = {}; let node = {};
...@@ -208,8 +235,6 @@ function buildGoodsTypePayload(tree, pathIds, options = { ...@@ -208,8 +235,6 @@ function buildGoodsTypePayload(tree, pathIds, options = {
result[options.level3Id] = node.categoryType; result[options.level3Id] = node.categoryType;
result[options.level3Name] = node.categoryName; result[options.level3Name] = node.categoryName;
} }
currentLevel = node.children || [];
}); });
return result; return result;
......
<template> <template>
<d2-container v-loading="$store.state.d2admin.loading.value" class="performance-scheme-wrapper"> <d2-container v-loading="$store.state.d2admin.loading.value" class="performance-scheme-wrapper">
<el-form class="form-performance-name" <el-form ref="form"
class="form-performance-name"
label-width="170px" label-width="170px"
:model="formData" :model="formData"
:rules="rules"> :rules="rules"
:validate-on-rule-change="false">
<div class="warp-box"> <div class="warp-box">
<div class="title space-b"> <div class="title space-b">
...@@ -22,12 +24,13 @@ ...@@ -22,12 +24,13 @@
</div> </div>
</div> </div>
<div class="warp-content"> <div class="warp-content">
<el-form-item label="当前方案名称:" prop="name"> <el-form-item label="当前方案名称:" prop="schemeName">
<el-input v-model="schemeName" <el-input v-model="schemeName"
clearable clearable
maxlength="20" maxlength="20"
placeholder="请输入当前方案名称" placeholder="请输入当前方案名称"
style="width:290px" /> style="width:290px"
@blur="handleFieldBlur('schemeName')" />
</el-form-item> </el-form-item>
<ParamConfigList v-for="(parameter, index) in formData.paramConfigList" <ParamConfigList v-for="(parameter, index) in formData.paramConfigList"
...@@ -76,7 +79,7 @@ ...@@ -76,7 +79,7 @@
<script> <script>
import { groupBy } from "lodash-es"; import { groupBy } from "lodash-es";
import { mapGetters, mapMutations, mapState } from "vuex"; import { mapMutations, mapState } from "vuex";
import { getAllCategory } from "@/api/product.js"; import { getAllCategory } from "@/api/product.js";
import { getPerformanceConfigDetailAPI, getTargetProductConfigListAPI, postSalaryPerformanceScheme } from "@/api/resident"; import { getPerformanceConfigDetailAPI, getTargetProductConfigListAPI, postSalaryPerformanceScheme } from "@/api/resident";
import DetailDialog from "../../components/approvalView"; import DetailDialog from "../../components/approvalView";
...@@ -87,6 +90,7 @@ import StoreApply from "../components/storeApply/index.vue"; ...@@ -87,6 +90,7 @@ import StoreApply from "../components/storeApply/index.vue";
import { bindFormFields } from "../store/helper.js"; import { bindFormFields } from "../store/helper.js";
import { convertBackendToData } from "../utils/convertBackendToData.js"; import { convertBackendToData } from "../utils/convertBackendToData.js";
import { convertDataToBackend } from "../utils/index.js"; import { convertDataToBackend } from "../utils/index.js";
import { getFormRules, validateParamConfigList } from "../utils/rules.js";
// 提成方案配置 // 提成方案配置
export default { export default {
...@@ -110,12 +114,30 @@ export default { ...@@ -110,12 +114,30 @@ export default {
id: 0, id: 0,
rules: {}, rules: {},
detailVisible: false, detailVisible: false,
shouldValidateAll: false, // 是否应该验证所有字段
}; };
}, },
computed: { computed: {
...mapState("PerformanceFormStore", ["formData", "merchantBrandRefList"]), ...mapState("PerformanceFormStore", ["formData", "merchantBrandRefList"]),
schemeName: bindFormFields("schemeName"), schemeName: bindFormFields("schemeName"),
}, },
watch: {
formData: {
handler() {
// 当formData变化时,更新rules
this.rules = getFormRules(this.formData, this.merchantBrandRefList);
},
deep: true,
immediate: true,
},
merchantBrandRefList: {
handler() {
// 当门店列表变化时,更新rules
this.rules = getFormRules(this.formData, this.merchantBrandRefList);
},
deep: true,
},
},
async mounted() { async mounted() {
await this.initLoad(); await this.initLoad();
if (this.$route?.query?.id) { if (this.$route?.query?.id) {
...@@ -148,8 +170,41 @@ export default { ...@@ -148,8 +170,41 @@ export default {
this.handleCancelSubmit(); this.handleCancelSubmit();
} }
}, },
// 处理单个字段失焦事件,只验证当前字段
handleFieldBlur(prop) {
if (!this.shouldValidateAll && this.$refs.form) {
this.$refs.form.validateField(prop, () => {});
}
},
// 提交保存 // 提交保存
async handleSubmitSave(isConfirm = false) { async handleSubmitSave(isConfirm = false) {
console.log("handleSubmitSave", this.formData);
// 设置需要验证所有字段
this.shouldValidateAll = true;
// 表单校验
try {
await this.$refs.form.validate();
} catch (error) {
this.$message.warning("请完善表单信息");
this.shouldValidateAll = false;
return;
}
this.shouldValidateAll = false;
// 校验门店列表
if (!this.merchantBrandRefList || this.merchantBrandRefList.length === 0) {
this.$message.warning("请至少选择一个门店");
return;
}
// 校验参数配置列表
const paramConfigError = validateParamConfigList(this.formData);
if (paramConfigError) {
this.$message.warning(paramConfigError);
return;
}
console.log(this.formData, "this.formData");
const params = convertDataToBackend({ const params = convertDataToBackend({
...this.formData, ...this.formData,
merchantBrandRefList: this.merchantBrandRefList, merchantBrandRefList: this.merchantBrandRefList,
...@@ -160,7 +215,7 @@ export default { ...@@ -160,7 +215,7 @@ export default {
params.schemeType = this.formData.schemeType; params.schemeType = this.formData.schemeType;
} }
} }
let res = await postSalaryPerformanceScheme(params); const res = await postSalaryPerformanceScheme(params);
this.id = res; this.id = res;
console.log(res, "res"); console.log(res, "res");
if (res && isConfirm) { if (res && isConfirm) {
......
  • @limin
    commented
    Owner

    你好,我是负责此次代码审查的资深软件开发工程师。

    你提交的代码主要涉及提成方案配置的表单校验逻辑,包括新增校验规则文件、修改组件间的交互方式以及增强数据处理的健壮性。虽然功能逻辑看起来比较完整,但在工程实践、性能优化和组件解耦方面存在较为严重的问题。

    以下是我的审查结果:

    一、关键问题与优化建议(Top 3)

    1. 严重性能隐患:对 formData 进行深层监听 (Deep Watch)

    • 问题描述:在 configureCommissionPlan.vue 中,你使用了 watch: { formData: { handler: ..., deep: true } } 来监听整个表单数据的变化,并在每次变化时重新生成所有校验规则 (getFormRules)。
    • 影响分析:formData 包含大量嵌套数组(如 paramConfigList, ParamsType1 等)。开启 deep: true 意味着表单中任何一个字符的输入都会触发深度遍历和规则重算。随着配置项增多,会导致严重的输入卡顿(Input Lag)和页面性能下降。此外,el-form 的校验规则通常不需要随值的变化而重新生成对象,校验器函数本身就是在校验时动态执行的。
    • 优化建议:
      1. 移除对 formData 的深度监听。
      2. 将 rules 定义为 computed 属性(如果规则确实依赖某些状态开关),或者直接在 data 中定义静态规则结构。
      3. 对于依赖动态数据的校验(如校验某行数据是否大于另一行),直接在 Validator 函数内部获取最新数据进行判断,而不是重新生成规则对象。
    // 优化示例:移除 watch,直接在 validator 中处理逻辑
    data() {
        return {
            rules: {
                schemeName: [{ required: true, validator: this.validateSchemeName, trigger: "blur" }],
                // ... 其他静态规则
            }
        }
    },
    methods: {
        validateSchemeName(rule, value, callback) {
            // 校验逻辑...
        }
    }
    

    2. 组件强耦合:子组件直接访问父组件实例 ($parent)

    • 问题描述:在 performanceRuleSelection/index.vue 和 storeApply/index.vue 中,使用了 this.$parent?.$refs?.form 来触发校验。
    • 影响分析:这是 Vue 开发中的反模式(Anti-pattern)。子组件强依赖了父组件的实现细节(必须有 $refs.form,必须叫 form)。如果未来重构父组件结构(例如包裹了一层 div 或组件),$parent 指向将改变,导致代码静默失效,极难维护。
    • 优化建议:遵循“单向数据流,事件向上通知”的原则。
      1. 子组件通过 $emit('validate-change', fieldName) 通知父组件。
      2. 父组件监听该事件并调用 el-form 的 validateField 方法。
    // 子组件
    handleBusinessTypeChange() {
        this.$emit('validate-request', 'businessType');
    }
    
    // 父组件模板
    <PerformanceRuleSelection @validate-request="handleFieldValidate" />
    
    // 父组件方法
    handleFieldValidate(prop) {
        this.$refs.form.validateField(prop);
    }
    

    3. 代码复杂度过高:validateParamConfigList 缺乏拆分

    • 问题描述:src/views/residentManage/salaryPerformance/performanceScheme/utils/rules.js 中的 validateParamConfigList 函数是一个巨大的“上帝函数”,包含多层嵌套循环和大量的 if-else 分支,不仅校验 ParamsType1 还校验 ParamsType2 及其各种条件。
    • 影响分析:该函数圈复杂度(Cyclomatic Complexity)极高,可读性差,极难进行单元测试。后续如果增加新的模版类型或条件,该函数将变得不可维护。
    • 优化建议:采用策略模式或简单的函数拆分。
      1. 将校验逻辑拆分为 validateParamsType1 和 validateParamsType2。
      2. 将行级校验拆分为 validateRowCondition。
      3. 主函数只负责遍历和分发。
    // 优化思路示例
    function validateParamConfigList(formData) {
        if (!formData.paramConfigList?.length) return "请至少配置一个绩效参数";
    
        for (let i = 0; i < formData.paramConfigList.length; i++) {
            const config = formData.paramConfigList[i];
            const error = config.templateType === 'ParamsType1' 
                ? validateType1(config, i) 
                : validateType2(config, i);
            if (error) return error;
        }
        return null;
    }
    

    二、评分明细

    1. 功能实现的正确性与健壮性(32/40分)

      • 优点:在 utils/index.js 中增加了不少防御性代码(如空值检查、数组检查),有效防止了运行时错误。
      • 缺点:表单校验逻辑虽然覆盖面广,但混合了 el-form 的自动校验和提交时的手动校验(validateParamConfigList),用户体验不一致(部分错误显示在输入框下,部分通过 Message 弹窗)。
    2. 安全性与潜在风险(28/30分)

      • 优点:未发现明显的 XSS 或注入风险,前端逻辑主要处理业务规则。
      • 缺点:无明显安全漏洞,但复杂的逻辑分支可能隐藏边界条件的 Bug。
    3. 最佳实践与可维护性(10/20分)

      • 缺点:严重扣分项。使用了 $parent 访问父组件实例;rules.js 中的校验函数过于臃肿;将所有逻辑堆砌在 helper 文件中而不是拆分管理。
    4. 性能与资源利用(2/5分)

      • 缺点:对大型表单对象进行 deep: true 的监听是严重的性能杀手,尤其是在低性能设备上会造成明显的输入延迟。
    5. 提交信息质量(4/5分)

      • 评价:feat: 提成方案表单校验 简洁明了,但考虑到修改了多个文件且包含重构性质,描述可以更具体一些,例如 feat: 实现提成方案复杂表单校验及防御性代码增强。

    三、总分

    总分:76分

Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!