Browse Source

refactor(commodityPriceList): 优化商品分类逻辑,使用parentCode替代categoryName判断物料表

yusheng 9 months ago
parent
commit
7556d796dd

+ 283 - 256
src/views/commodityManagement/commodityPriceList/components/addDialog.vue

@@ -52,6 +52,7 @@
               placeholder="请选择商品分类"
               v-model="form.categoryLevelId"
               :disabled="type == 'view'"
+             
             />
           </el-form-item>
         </el-col>
@@ -219,7 +220,8 @@
       ref="inventoryTable"
       :type="type"
       :default-price="defaultPrice"
-      :category-name="form.categoryLevelName"
+
+      :parentCode="parentCode"
       v-show="activeComp == 'main'"
     />
     <template slot="footer">
@@ -236,284 +238,309 @@
   </ele-modal>
 </template>
 <script>
-const formDef = {
-  id: '', //商品id
-  categoryLevelId: '', //商品分类ID
-  categoryLevelName: '', // 商品分类名称(新增)
-  goodsName: '', //商品名称
-  goodsCode: '', //商品编码
-  imagesPaths: '', //商品图片
-  imagesFileIds: '', //商品图片id
-  categoryId: '', //物品id
-  productName: '', //物品名称
-  productCategoryName: '', //物品类型
-  productCode: '', //物品编码
-  produceType: '', //属性类型
-  warehouseId: '', //仓库名称
-  warehouseNum: '', //库存
-  packingSpecification: '', //包装规格
-  measuringUnit: '', //计量单位
-  weightUnit: '', //重量单位
-  warehouseList: [], //仓库
-  level: '2',
-  children: [] //价格数组
-};
-import BIZproductList from '@/BIZComponents/product-list.vue';
-import SelectTree from './selectTree.vue';
-import modalTitle from '@/BIZComponents/modalTitle.vue';
-import dictMixins from '@/mixins/dictMixins';
-import ProductTable from './productTable.vue';
-import { saveGoods } from '@/api/goodsManage/index';
-import { getTreeByPid, getPcTreeByPids } from '@/api/classifyManage';
-import { getByCode } from '@/api/system/dictionary-data';
-import { copyObj } from '@/utils/util';
-import {
-  getWarehouseOutStock,
-  getIdWarehouseList,
-  getProductPrice
-} from '@/api/saleManage/saleorder';
-import { lbjtList } from '@/enum/dict.js';
-import { getCode } from '@/api/login/index';
-import ImgUpload from './imgUpload.vue';
-import { getGoodsById, updateGoods } from '@/api/goodsManage/index';
-import { levelList } from '@/enum/dict.js';
-import bpmDetail from '@/views/bpm/processInstance/detail.vue';
+  const formDef = {
+    id: '', //商品id
+    categoryLevelId: '', //商品分类ID
+    categoryLevelName: '', // 商品分类名称(新增)
+    goodsName: '', //商品名称
+    goodsCode: '', //商品编码
+    imagesPaths: '', //商品图片
+    imagesFileIds: '', //商品图片id
+    categoryId: '', //物品id
+    productName: '', //物品名称
+    productCategoryName: '', //物品类型
+    productCode: '', //物品编码
+    produceType: '', //属性类型
+    warehouseId: '', //仓库名称
+    warehouseNum: '', //库存
+    packingSpecification: '', //包装规格
+    measuringUnit: '', //计量单位
+    weightUnit: '', //重量单位
+    warehouseList: [], //仓库
+    level: '2',
+    children: [] //价格数组
+  };
+  import BIZproductList from '@/BIZComponents/product-list.vue';
+  import SelectTree from './selectTree.vue';
+  import modalTitle from '@/BIZComponents/modalTitle.vue';
+  import dictMixins from '@/mixins/dictMixins';
+  import ProductTable from './productTable.vue';
+  import { saveGoods } from '@/api/goodsManage/index';
+  import { getTreeByPid, getPcTreeByPids } from '@/api/classifyManage';
+  import { getByCode } from '@/api/system/dictionary-data';
+  import { copyObj } from '@/utils/util';
+  import {
+    getWarehouseOutStock,
+    getIdWarehouseList,
+    getProductPrice
+  } from '@/api/saleManage/saleorder';
+  import { lbjtList } from '@/enum/dict.js';
+  import { getCode } from '@/api/login/index';
+  import ImgUpload from './imgUpload.vue';
+  import { getGoodsById, updateGoods } from '@/api/goodsManage/index';
+  import { levelList } from '@/enum/dict.js';
+  import bpmDetail from '@/views/bpm/processInstance/detail.vue';
 
-export default {
-  components: {
-    ProductTable,
-    modalTitle,
-    SelectTree,
-    BIZproductList,
-    ImgUpload,
-    bpmDetail
-  },
-  mixins: [dictMixins],
-  data() {
-    return {
-      activeComp: 'main',
-      tabOptions: [
-        { key: 'main', name: '详情' },
-        { key: 'bpm', name: '流程详情' }
-      ],
-      imgs: [],
-      title: '',
-      visible: false,
-      type: '',
-      fullscreen: false,
-      form: copyObj(formDef),
-      loading: false,
-      isUpdate: false,
-      gList: [], //商品分类
-      levelList,
-      rules: {
-        categoryLevelId: [
-          { required: true, message: '请选择商品分类', trigger: 'change' }
-        ],
-        goodsName: [
-          { required: true, message: '请输入商品名称', trigger: 'blur' }
+  export default {
+    components: {
+      ProductTable,
+      modalTitle,
+      SelectTree,
+      BIZproductList,
+      ImgUpload,
+      bpmDetail
+    },
+    mixins: [dictMixins],
+    data() {
+      return {
+        activeComp: 'main',
+        tabOptions: [
+          { key: 'main', name: '详情' },
+          { key: 'bpm', name: '流程详情' }
         ],
-        goodsCode: [
-          { required: true, message: '请输入商品编码', trigger: 'blur' }
-        ]
-      }
-    };
-  },
-  // 核心:监听商品分类ID变化,实时更新分类名称
-  watch: {
-    'form.categoryLevelId': {
-      immediate: true, // 初始化时立即执行
-      deep: true,
-      handler(newVal) {
-        if (!newVal) {
-          this.form.categoryLevelName = '';
-          return;
+        imgs: [],
+        title: '',
+        visible: false,
+        parentCode:'',
+        type: '',
+        fullscreen: false,
+        form: copyObj(formDef),
+        loading: false,
+        isUpdate: false,
+        gList: [], //商品分类
+        levelList,
+        defaultPrice: '',
+        rules: {
+          categoryLevelId: [
+            { required: true, message: '请选择商品分类', trigger: 'change' }
+          ],
+          goodsName: [
+            { required: true, message: '请输入商品名称', trigger: 'blur' }
+          ],
+          goodsCode: [
+            { required: true, message: '请输入商品编码', trigger: 'blur' }
+          ]
         }
-        // 从分类列表中查找对应名称
-        this.form.categoryLevelName = this.findCategoryName(this.gList, newVal);
-      }
-    }
-  },
-  created() {
-    this.getTreeData();
-  },
-  methods: {
-    // 递归查找分类名称(确保能从树形结构中找到对应ID的名称)
-    findCategoryName(tree, targetId) {
-      for (const node of tree) {
-        if (node.id === targetId) {
-          return node.name;
-        }
-        if (node.children && node.children.length) {
-          const childName = this.findCategoryName(node.children, targetId);
-          if (childName) return childName;
+      };
+    },
+    // 核心:监听商品分类ID变化,实时更新分类名称
+    watch: {
+      'form.categoryLevelId': {
+        immediate: true, // 初始化时立即执行
+        deep: true,
+        handler(newVal) {
+          if (!newVal) {
+            this.form.categoryLevelName = '';
+            return;
+          }
+          // 从分类列表中查找对应名称
+          this.form.categoryLevelName = this.findCategoryName(
+            this.gList,
+            newVal
+          );
         }
       }
-      return '';
     },
-
-    // 打开弹出框
-    async open(type, row, contactCategoryId) {
-      this.form.categoryLevelId = contactCategoryId;
-      this.title = type === 'add' ? '新增' : type === 'view' ? '详情' : '修改';
-      this.type = type;
-      this.visible = true;
-      this.isUpdate = type !== 'add';
-      if (type !== 'add') {
-        this.getGoodsById(row.id);
-      }
+    created() {
+      this.getTreeData();
     },
+    methods: {
+      // 递归查找分类名称(确保能从树形结构中找到对应ID的名称)
+      findCategoryName(tree, targetId) {
+      
+        for (const node of tree) {
+          if (node.id === targetId) {
+            this.parentCode = node.parentCode||node.code
+            return node.name;
+          }
+          if (node.children && node.children.length) {
+            const childName = this.findCategoryName(node.children, targetId);
+            if (childName) return childName;
+          }
+        }
+        return '';
+      },
 
-    // 获取详情数据
-    async getGoodsById(id) {
-      const res = await getGoodsById(id);
-      // 处理图片
-      if (res.imagesPaths) {
-        this.imgs = res.imagesPaths.split(',').map((item, index) => ({
-          id: res.imagesFileIds.split(',')[index],
-          url: `${window.location.origin}/api/main/file/getFile?objectName=${item}`,
-          status: 'done'
-        }));
-      }
-      // 赋值表单数据(会触发categoryLevelId的watch)
-      this.form = { ...res };
-      this.$refs.imgUploadRef?.putValue(this.imgs);
-      this.$refs.inventoryTable?.putTableList(res.goodsPriceList || []);
-    },
+      // 打开弹出框
+      async open(type, row, contactCategoryId) {
+        this.form.categoryLevelId = contactCategoryId;
+        this.title =
+          type === 'add' ? '新增' : type === 'view' ? '详情' : '修改';
+        this.type = type;
+        this.visible = true;
+        this.isUpdate = type !== 'add';
+        if (type !== 'add') {
+          this.getGoodsById(row.id);
+        }
+      },
 
-    // 查询商品分类
-    async getTreeData() {
-      const res = await getTreeByPid('1789827921908150274');
-      if (res?.code === '0') {
-        this.gList = res.data;
-      }
-    },
+      // 获取详情数据
+      async getGoodsById(id) {
+        const res = await getGoodsById(id);
+        // 处理图片
+        if (res.imagesPaths) {
+          this.imgs = res.imagesPaths.split(',').map((item, index) => ({
+            id: res.imagesFileIds.split(',')[index],
+            url: `${window.location.origin}/api/main/file/getFile?objectName=${item}`,
+            status: 'done'
+          }));
+        }
+        // 赋值表单数据(会触发categoryLevelId的watch)
+        this.form = { ...res };
+        this.$refs.imgUploadRef?.putValue(this.imgs);
+        this.$refs.inventoryTable?.putTableList(res.goodsPriceList || []);
+      },
 
-    // 库存计算
-    async warehouseChange(e) {
-      const warehouseOutStock = await getWarehouseOutStock({
-        warehouseId: e,
-        code: this.form.productCode
-      });
-      this.form.warehouseNum = warehouseOutStock || 0;
-    },
+      // 查询商品分类
+      async getTreeData() {
+        const res = await getTreeByPid('1789827921908150274');
+        if (res?.code === '0') {
+          if (res.data[0].children) {
+            res.data[0].children.forEach((item) => {
+              if (item.code == 'material') {
+               this.setTree(item.children || []);
+              }
+            });
+          }
+          this.gList = res.data;
+        }
+      },
+      //递归吧产品 物料的code赋值给子级
+      setTree(data) {
+        data.forEach((item) => {
+          item.parentCode = 'material';
+          if (item.children&&item.children.length) {
+            this.setTree(item.children);
+          }
+        });
+       
+      },
 
-    // 选择物品
-    handParent() {
-      this.$refs.BIZproductListRef.open('', 1);
-    },
+      // 库存计算
+      async warehouseChange(e) {
+        const warehouseOutStock = await getWarehouseOutStock({
+          warehouseId: e,
+          code: this.form.productCode
+        });
+        this.form.warehouseNum = warehouseOutStock || 0;
+      },
 
-    changeParentBiz(obj = []) {
-      this.getGoodsCode('goods_code');
-      obj.forEach(async (item) => {
-        this.form.categoryId = item.id;
-        this.form.productName = item.name;
-        this.form.goodsName = item.name;
-        this.form.productCategoryName = item.categoryLevelPath;
-        this.form.packingSpecification = item.extField?.packingSpecification;
-        this.form.productCode = item.code;
-        this.form.produceType =
-          lbjtList[item.componentAttribute]?.toString() || '';
-        this.form.warehouseId = item.warehouseId;
-        this.form.measuringUnit = item.measuringUnit;
-        this.form.weightUnit = item.weightUnit;
-        console.log(item)
-        const priceRes = await getProductPrice(item.code);
-        if (priceRes) {
-          console.log(priceRes)
-          this.defaultPrice = priceRes.singlePrice || null;
-        }
-        this.form.warehouseList = await getIdWarehouseList({
-          categoryId: item.id
+      // 选择物品
+      handParent() {
+        this.$refs.BIZproductListRef.open('', 1);
+      },
+
+      changeParentBiz(obj = []) {
+        this.getGoodsCode('goods_code');
+        obj.forEach(async (item) => {
+          this.form.categoryId = item.id;
+          this.form.productName = item.name;
+          this.form.goodsName = item.name;
+          this.form.productCategoryName = item.categoryLevelPath;
+          this.form.packingSpecification = item.extField?.packingSpecification;
+          this.form.productCode = item.code;
+          this.form.produceType =
+            lbjtList[item.componentAttribute]?.toString() || '';
+          this.form.warehouseId = item.warehouseId;
+          this.form.measuringUnit = item.measuringUnit;
+          this.form.weightUnit = item.weightUnit;
+          console.log(item);
+          const priceRes = await getProductPrice(item.code);
+          if (priceRes) {
+            console.log(priceRes);
+            this.defaultPrice = priceRes.singlePrice || null;
+          }
+          this.form.warehouseList = await getIdWarehouseList({
+            categoryId: item.id
+          });
         });
-      });
-    },
+      },
 
-    // 提交保存
-    async save() {
-      try {
-        if (!this.form.categoryId) {
-          this.$message.error('请选择物品');
-          return;
-        }
-        await this.getValidate();
+      // 提交保存
+      async save() {
+        try {
+          if (!this.form.categoryId) {
+            this.$message.error('请选择物品');
+            return;
+          }
+          await this.getValidate();
 
-        const commitData = this.$refs?.inventoryTable?.getTableValue();
-        if (!commitData || commitData.length < 1) {
-          this.$message.error('请添加价格信息');
-          return;
-        }
+          const commitData = this.$refs?.inventoryTable?.getTableValue();
+          if (!commitData || commitData.length < 1) {
+            this.$message.error('请添加价格信息');
+            return;
+          }
 
-        const comitDatasource = {
-          categoryId: this.form.categoryId,
-          categoryLevelId: this.form.categoryLevelId,
-          goodsCode: this.form.goodsCode,
-          goodsName: this.form.goodsName,
-          imagesFileIds: this.imgs?.map((item) => item.id).toString(),
-          level: this.form.level,
-          packingSpecification: this.form.packingSpecification,
-          priceList: commitData
-        };
+          const comitDatasource = {
+            categoryId: this.form.categoryId,
+            categoryLevelId: this.form.categoryLevelId,
+            goodsCode: this.form.goodsCode,
+            goodsName: this.form.goodsName,
+            imagesFileIds: this.imgs?.map((item) => item.id).toString(),
+            level: this.form.level,
+            packingSpecification: this.form.packingSpecification,
+            priceList: commitData
+          };
 
-        this.loading = true;
-        const res = this.isUpdate
-          ? await updateGoods({ ...comitDatasource, id: this.form.id })
-          : await saveGoods(comitDatasource);
+          this.loading = true;
+          const res = this.isUpdate
+            ? await updateGoods({ ...comitDatasource, id: this.form.id })
+            : await saveGoods(comitDatasource);
 
-        if (res?.code === '0') {
-          this.$message.success('操作成功');
-          this.cancel();
-          this.$emit('done');
+          if (res?.code === '0') {
+            this.$message.success('操作成功');
+            this.cancel();
+            this.$emit('done');
+          }
+        } catch (error) {
+          this.$message.error('操作失败');
+        } finally {
+          this.loading = false;
         }
-      } catch (error) {
-        this.$message.error('操作失败');
-      } finally {
-        this.loading = false;
-      }
-    },
+      },
 
-    // 获取商品编码
-    async getGoodsCode(code) {
-      this.form.goodsCode = await getCode(code);
-    },
+      // 获取商品编码
+      async getGoodsCode(code) {
+        this.form.goodsCode = await getCode(code);
+      },
 
-    // 取消
-    cancel() {
-      this.$nextTick(() => {
-        this.$refs.inventoryTable?.putTableList([]);
-        this.$refs.imgUploadRef?.putValue();
-        this.imgs = [];
-        this.form = copyObj(formDef);
-        this.visible = false;
-      });
-    },
+      // 取消
+      cancel() {
+        this.$nextTick(() => {
+          this.$refs.inventoryTable?.putTableList([]);
+          this.$refs.imgUploadRef?.putValue();
+          this.imgs = [];
+          this.form = copyObj(formDef);
+          this.visible = false;
+        });
+      },
 
-    // 表单校验
-    getValidate() {
-      return Promise.all([
-        new Promise((resolve, reject) => {
-          this.$refs.form.validate((valid) =>
-            valid ? resolve(true) : reject(false)
-          );
-        }),
-        new Promise((resolve, reject) => {
-          this.$refs.inventoryTable.validateForm((valid) =>
-            valid ? resolve(true) : reject(false)
-          );
-        })
-      ]);
+      // 表单校验
+      getValidate() {
+        return Promise.all([
+          new Promise((resolve, reject) => {
+            this.$refs.form.validate((valid) =>
+              valid ? resolve(true) : reject(false)
+            );
+          }),
+          new Promise((resolve, reject) => {
+            this.$refs.inventoryTable.validateForm((valid) =>
+              valid ? resolve(true) : reject(false)
+            );
+          })
+        ]);
+      }
     }
-  }
-};
+  };
 </script>
 <style lang="scss" scoped>
-.el-form-item {
-  margin-bottom: 20px !important;
-}
+  .el-form-item {
+    margin-bottom: 20px !important;
+  }
 
-.el-form-item__error {
-  display: block !important;
-  color: red;
-  padding-top: 4px;
-}
-</style>
+  .el-form-item__error {
+    display: block !important;
+    color: red;
+    padding-top: 4px;
+  }
+</style>

+ 3 - 14
src/views/commodityManagement/commodityPriceList/components/productTable.vue

@@ -133,7 +133,7 @@ export default {
   props: {
     groupId: String,
     type: String,
-    categoryName: String, // 接收主组件传递的分类名称
+    parentCode: String, // 接收主组件传递的商品code 
     defaultPrice: {
       type: Number,
       default: null
@@ -148,14 +148,7 @@ export default {
       goodsCode: ''
     };
   },
-  watch: {
-    categoryName: {
-      immediate: true,
-      handler() {
-        this.$forceUpdate();
-      }
-    }
-  },
+
   computed: {
     columns() {
       return [
@@ -168,7 +161,6 @@ export default {
           label: '序号'
         },
         {
-          width: 200,
           prop: 'priceType',
           label: '价格类型',
           slot: 'priceType',
@@ -176,7 +168,6 @@ export default {
           align: 'center'
         },
         {
-          width: 200,
           prop: 'unitPrice',
           headerSlot: 'headerUnitPrice',
           label: '含税单价',
@@ -184,14 +175,12 @@ export default {
           align: 'center'
         },
         {
-          width: 200,
           prop: 'taxRate',
           slot: 'taxRate',
           label: '税率',
           align: 'center'
         },
         {
-          width: 200,
           prop: 'excludeTaxPrice',
           label: '不含税单价',
           slot: 'excludeTaxPrice',
@@ -250,7 +239,7 @@ export default {
         .filter((type) => type !== currentValue);
       let filtered = data.filter((item) => !usedTypes.includes(item.dictCode));
 
-      const isMaterialTable = this.categoryName?.trim() === '物料表';
+      const isMaterialTable = this.parentCode=='material';
       if (isMaterialTable) {
         filtered = filtered.filter((item) => item.dictCode === '5');
       } else {

+ 1 - 1
src/views/commodityManagement/commodityPriceList/components/selectTree.vue

@@ -26,7 +26,7 @@
       // 提示信息
       placeholder: {
         type: String,
-        default: '请选择机构'
+        default: '请选择'
       },
       // 机构数据
       data: Array