浏览代码

Merge branch 'master' of http://192.168.1.41:3000/SmartCost/YangHuCost

# Conflicts:
#	web/over_write/js/hunan_2020.js
vian 5 年之前
父节点
当前提交
62aa72918a
共有 42 个文件被更改,包括 3066 次插入723 次删除
  1. 13 0
      modules/all_models/divide_setting.js
  2. 1 0
      modules/all_models/ration.js
  3. 34 0
      modules/main/controllers/divide_controller.js
  4. 0 9
      modules/main/controllers/project_controller.js
  5. 6 1
      modules/main/controllers/ration_controller.js
  6. 170 0
      modules/main/facade/divide_facade.js
  7. 64 140
      modules/main/facade/project_facade.js
  8. 64 7
      modules/main/facade/ration_facade.js
  9. 2 1
      modules/main/models/project.js
  10. 2 1
      modules/main/models/project_consts.js
  11. 17 0
      modules/main/routes/divide_route.js
  12. 1 0
      modules/main/routes/ration_route.js
  13. 43 16
      modules/pm/facade/pm_facade.js
  14. 83 32
      modules/ration_glj/facade/glj_calculate_facade.js
  15. 20 14
      modules/ration_glj/facade/ration_glj_facade.js
  16. 7 8
      public/web/scMathUtil.js
  17. 79 78
      public/web/sheet/sheet_common.js
  18. 8 5
      public/web/tree_sheet/tree_sheet_helper.js
  19. 6 6
      web/building_saas/css/main.css
  20. 3 11
      web/building_saas/glj/html/project_glj.html
  21. 181 0
      web/building_saas/main/html/divide.html
  22. 9 4
      web/building_saas/main/html/main.html
  23. 1 1
      web/building_saas/main/js/main.js
  24. 16 0
      web/building_saas/main/js/models/bills.js
  25. 210 182
      web/building_saas/main/js/models/calc_program.js
  26. 2 1
      web/building_saas/main/js/models/main_consts.js
  27. 102 23
      web/building_saas/main/js/models/project.js
  28. 15 3
      web/building_saas/main/js/models/project_glj.js
  29. 10 1
      web/building_saas/main/js/models/ration_coe.js
  30. 1614 0
      web/building_saas/main/js/views/divide_view.js
  31. 0 2
      web/building_saas/main/js/views/electrovalence_view.js
  32. 4 4
      web/building_saas/main/js/views/glj_col.js
  33. 5 2
      web/building_saas/main/js/views/glj_view.js
  34. 3 2
      web/building_saas/main/js/views/material_calc_view.js
  35. 22 17
      web/building_saas/main/js/views/project_glj_view.js
  36. 2 1
      web/building_saas/main/js/views/project_info.js
  37. 1 0
      web/building_saas/main/js/views/project_view.js
  38. 5 0
      web/building_saas/main/js/views/side_tools.js
  39. 64 44
      web/building_saas/main/js/views/std_ration_lib.js
  40. 148 105
      web/building_saas/main/js/views/zmhs_view.js
  41. 1 1
      web/building_saas/unit_price_file/index.html
  42. 28 1
      web/over_write/js/hunan_2020.js

+ 13 - 0
modules/all_models/divide_setting.js

@@ -0,0 +1,13 @@
+let mongoose = require('mongoose');
+let Schema = mongoose.Schema;
+
+let divideSchema = {
+  ID:{type:String,index: true},
+  projectID:Number,
+  divideList:[Schema.Types.Mixed],
+  ration_gljs:[Schema.Types.Mixed],
+  ration_coes:[Schema.Types.Mixed],
+  divideType:Number//分摊方式(3种)
+}
+
+mongoose.model("divide_setting", new Schema(divideSchema, {versionKey: false, collection: "divide_setting"}));

+ 1 - 0
modules/all_models/ration.js

@@ -73,6 +73,7 @@ let rationSchema = new Schema({
     ruleText: String,                            // 计算规则
     prefix: {type: String, default: ''},                              //定额是补充、借用时用  补 借
     referenceRationID:String,//如果是通过模板关联子目生成的定额,这里记录对应的主定额ID
+    divideID:String,//分摊项生成的量价关联的ID
 
     //工料机特有属性
     projectGLJID:Number,  //项目工料机ID

+ 34 - 0
modules/main/controllers/divide_controller.js

@@ -0,0 +1,34 @@
+/**
+ * Created by zhang on 2018/9/12.
+ */
+
+let divideFacade = require('../facade/divide_facade');
+let logger = require("../../../logs/log_helper").logger;
+let controller = {
+    updateItem:async function(req) {
+        let data = req.body.data;
+        return await divideFacade.updateItem(JSON.parse(data));
+    },
+    updateCoeAdjust:async function(req){
+      let data = req.body.data;
+      return await divideFacade.updateCoeAdjust(JSON.parse(data),req.session.sessionCompilation);
+    }
+   
+};
+
+module.exports ={
+    action:async function(req,res){//自动跳转到URL对应的controller方法
+        let result={
+            error:0
+        };
+        try {
+            let functionName = req.url.replace(/\//g,"");
+            result.data = controller[functionName]?await controller[functionName](req):"";
+        }catch (err){
+            logger.err(err);
+            result.error=1;
+            result.message = err.message;
+        }
+        res.json(result);
+    }
+};

+ 0 - 9
modules/main/controllers/project_controller.js

@@ -81,15 +81,6 @@ module.exports = {
         res.json(result);
     },
     updateNodes:async function (req,res) {
-    /*    var data = JSON.parse(req.body.data);
-        project_facade.updateNodes(data, function (err, message, result) {
-            if (err) {
-                logger.err(err);
-                callback(req, res, err, message, null);
-            } else {
-                callback(req, res, err, message, result);
-            }
-        });*/
         let result={
             error:0
         }

+ 6 - 1
modules/main/controllers/ration_controller.js

@@ -40,7 +40,6 @@ let controller = {
     updateMaterialRation:async function(req){
         let data = req.body.data;
         data = JSON.parse(data);
-        console.log(data);
         let result = await ration_facade.updateMaterialRation(data,req.session.sessionCompilation);
         //取运费和原价数据
        if(result.projectGLJList){
@@ -52,6 +51,12 @@ let controller = {
        }
         return result
     },
+    updateDivideRation:async function(req){
+      let data = req.body.data;
+      data = JSON.parse(data);
+      let result = await ration_facade.updateDivideRation(data,req.session.sessionCompilation);
+      return result
+    },
     addMultiRation: async function (req) {
         let data = req.body.data;
         if(typeof data === 'object'){

+ 170 - 0
modules/main/facade/divide_facade.js

@@ -0,0 +1,170 @@
+module.exports = {
+  getData: getData,
+  updateItem:updateItem,
+  updateCoeAdjust:updateCoeAdjust
+};
+
+let mongoose = require('mongoose');
+let divideModel = mongoose.model("divide_setting");
+let consts = require('../models/project_consts');
+let calculate_facade = require("../../ration_glj/facade/glj_calculate_facade");
+let ration_glj_facade = require("../../ration_glj/facade/ration_glj_facade");
+let projectConsts = consts.projectConst;
+const uuidV1 = require('uuid/v1');
+
+
+async function updateItem(data){
+  let ID = data.ID;
+  let tasks= [];
+  let udatas = [];
+  let proportioRationID = null;
+  for(let u of data.updateDatas){
+    if(u.type == 'add'){
+      tasks.push({updateOne: {filter: {ID: ID}, update: {"$push":{divideList:u.doc} }}});
+    }
+    if(u.type == "update"){
+      let ndoc = {};
+      let pre = "divideList.$."
+      if(u.model) pre= u.model+".$."; 
+      for(let key in u.doc){
+        ndoc[pre+key] = u.doc[key]
+      }
+      if(u.model){//改定额工料机的自定消耗或者子目换算时,要重算消耗量,所以就不走task流程了,另外算
+        let query = {"ID": ID};
+        query[u.model+".ID"] = u.ID;
+        if(u.updateProportion == true){//更新稳定土的时候要先把所有定额工料机更新后,再计算消耗量,所以放在builkWrite后面
+          tasks.push({updateOne: {filter: query, update: ndoc}});
+          proportioRationID = u.rationID;
+        }else{
+          await divideModel.update(query,ndoc);
+          //重新计算消耗量
+          let [ntasks,ndatas] = await calculate_facade.calculateQuantityFromDivide(ID,u.rationID);
+          if(ntasks.length > 0) tasks = tasks.concat(ntasks);
+          if(ndatas.length > 0) udatas = udatas.concat(ndatas);
+        }   
+      }else if(u.updateAss == true){//修改辅助定额
+        await divideModel.update({"ID": ID,"divideList.ID":u.ID},ndoc);
+        let [ntasks,ndatas] = await calculate_facade.calculateQuantityFromDivide(ID,u.ID);
+        if(ntasks.length > 0) tasks = tasks.concat(ntasks);
+        if(ndatas.length > 0) udatas = udatas.concat(ndatas);
+      }else{
+        tasks.push({updateOne: {filter: {"ID": ID,"divideList.ID":u.ID}, update: ndoc}});
+      }
+    }
+    if(u.type == "delete"){
+      tasks.push({updateOne: {filter: {ID: ID}, update: {"$pull":{divideList:{ID:u.ID}} }}});
+      if(u.itemType == "定额"){
+        await divideModel.update(
+          {ID:ID},
+          { $pull: {ration_gljs:{rationID:u.ID},ration_coes:{rationID:u.ID}}},
+          { multi: true })
+      }
+    }
+  }
+
+  if(tasks.length > 0) await divideModel.bulkWrite(tasks);
+  if(udatas.length > 0) data.updateDatas = data.updateDatas.concat(udatas);
+
+  if(proportioRationID!=null){//说明更新了稳定土
+    let [ptasks,pdatas] = await calculate_facade.calculateQuantityFromDivide(ID,proportioRationID);
+    if(ptasks.length > 0) await divideModel.bulkWrite(ptasks);
+    if(pdatas.length > 0) data.updateDatas = data.updateDatas.concat(pdatas);
+  }
+
+
+  return data;
+}
+
+async function updateCoeAdjust(data,compilation){
+  let replace = [],projectGLJList=[],ration_gljs=[];
+  let result = {updateDatas:[]}
+  let ndoc = {};
+  let pre = "ration_coes.$."
+  for(let key in data.doc){
+    ndoc[pre+key] = data.doc[key]
+  }
+  await divideModel.update({ID:data.divideID,"ration_coes.ID":data.ID},ndoc);
+  result.updateDatas.push({ID:data.ID,type:'update',model:'ration_coes',doc:data.doc});
+   //添加单个工料机的情况
+   if (data.add.length > 0){
+     let [tg,pl] = await ration_glj_facade.insertAddTypeGLJ(data.add,compilation,false);
+     await divideModel.update({ID:data.divideID},{$push:{ration_gljs:{$each:tg}}});
+     ration_gljs = ration_gljs.concat(tg);
+     if(pl.length > 0) projectGLJList = projectGLJList.concat(pl);
+   }
+  //删除的情况 
+  if(data.delete.length > 0){
+    await divideModel.update({ID:data.divideID},{$pull:{ration_gljs:{$in: data.delete}}});
+  } 
+  //替换工料机的情况
+  if (data.replace.length > 0){
+    let rationGLJlist = await getRationGLJs(data.divideID,data.rationID);
+    for(let r of data.replace){
+        let ration_glj_ID = r.ID;
+        if(data.toCommercial == true) ration_glj_ID = r.originalID;
+        let r_result = await  ration_glj_facade.replaceGLJByData(r,compilation,false,rationGLJlist);
+        let rdoc = {};
+        for(let key in r_result.data){
+          rdoc[pre+key] = result.data[key]
+        }
+        //修改定额工料机
+        await divideModel.update({ID:data.divideID,"ration_gljs.ID":ration_glj_ID},rdoc);
+        result.updateDatas.push({ID:data.ID,type:'update',model:'ration_gljs',doc:r_result.data});
+        projectGLJList.push(r_result.projectGLJ);
+        
+        //新增定额工料机
+        if(r_result.newRecodes.length > 0){
+          await divideModel.update({ID:data.divideID},{$push:{ration_gljs:{$each:r_result.newRecodes}}});
+          ration_gljs = ration_gljs.concat(r_result.newRecodes);
+        }
+        //删除定额工料机
+        if(r_result.deleteList.length > 0){
+          await divideModel.update({ID:data.divideID},{$pull:{ration_gljs:{$in: r_result.deleteList}}});
+          data.delete = data.delete.concat(r_result.deleteList);
+        } 
+    }
+  }
+
+  let [ptasks,pdatas] = await calculate_facade.calculateQuantityFromDivide(data.divideID,data.rationID);
+  if(ptasks.length > 0) await divideModel.bulkWrite(ptasks);
+  if(pdatas.length > 0) result.updateDatas = result.updateDatas.concat(pdatas);
+  result.ration_gljs= ration_gljs;
+  result.projectGLJList = projectGLJList;
+  result.delete = data.delete;
+
+  return result;
+}
+
+
+async function getRationGLJs(divideID,rationID){
+  let gljList = [];
+  let divide_setting = await divideModel.findOne({ID:divideID}).lean();
+  for(let rg of divide_setting.ration_gljs){
+    if(rg.rationID == rationID) gljList.push(rg);
+  }
+  return gljList;
+}
+
+function getData(projectID, callback) {
+  divideModel.findOne({projectID: projectID}, '-_id', async function (err, datas) {
+    if (!err) {
+        // 旧项目没有人工系数文件,默认给它生成一个。
+        if (!datas) {
+          datas = {
+            ID: uuidV1(),
+            projectID:projectID,
+            divideList:[],
+            ration_gljs:[],
+            ration_coes:[]
+          }
+          await divideModel.create(datas);
+          callback(0, projectConsts.DIVIDE_SETTING, datas);
+        } else {
+            callback(0, projectConsts.DIVIDE_SETTING, datas);
+        };
+    } else {
+        callback(1, projectConsts.DIVIDE_SETTING, null);
+    };
+  });
+
+}

+ 64 - 140
modules/main/facade/project_facade.js

@@ -6,7 +6,6 @@ module.exports = {
     markUpdateProject:markUpdateProject,
     removeProjectMark:removeProjectMark,
     updateNodes:updateNodes,
-    calcInstallationFee:calcInstallationFee,
     saveProperty: saveProperty,
     getDefaultColSetting: getDefaultColSetting,
     markProjectsToChange:markProjectsToChange,
@@ -38,77 +37,13 @@ const { fixedFlag } = require('../../../public/common_constants');
 import GLJListModel from "../../glj/models/glj_list_model";
 const projectDao = require('../../pm/models/project_model').project;
 
-
-
-async function calcInstallationFee(data) {
-    let result={};
-    let projectGLJList = [];
-    let billTasks  = generateTasks(data.bills,data.useID);
-    let rationTasks = generateTasks(data.ration,data.useID);
-    if(billTasks.length>0){
-        await bill_model.model.bulkWrite(billTasks);
-    }
-    console.log(rationTasks);
-    if(rationTasks.length>0){
-        await ration_model.model.bulkWrite(rationTasks);
-    }
-    //如果删除定额,需要删除对应的工料机
-    if(data.ration.delete.length>0){
-        let rationIDS = _.map(data.ration.delete,'ID');
-        await ration_glj_model.deleteMany({projectID: data.ration.delete[0].projectID, rationID: {"$in": rationIDS}});//删除定额工料机
-    }
-
-    let rationGLJTasks = [];
-    let updateList = [];
-    if(data.ration.update.length>0){//如果有需要更新的定额工料机
-        for(let ur of data.ration.update){
-            for(let g of ur.glj){
-                let gTasks = {
-                    updateOne:{
-                        filter:{
-                            ID:g.ID,
-                            projectID:g.projectID
-                        },
-                        update :{
-                            quantity:g.quantity,
-                            rationItemQuantity:g.rationItemQuantity
-                        }
-                    }
-                };
-                rationGLJTasks.push(gTasks);
-                updateList.push(g);
-            }
-        }
-    }
-    if(rationGLJTasks.length>0){
-       await ration_glj_model.bulkWrite(rationGLJTasks);
-    }
-
-    let newGljList = [];
-    if(data.ration.add.length>0){//新增的安装子目要增加对应的工料机
-        for(let nr of data.ration.add){
-            for(let tkey in nr.glj){
-                let [newRecode,projectGLJ] = await addInstallationGLJ(nr.glj[tkey]);
-                newGljList.push(newRecode);
-            }
-        }
-    }
-    if(newGljList.length>0){
-        await ration_glj_model.insertMany(newGljList);
-    }
-    result.update = updateList;
-    result.add = newGljList;
-    return result;
+async function createRationGLJData(glj) {
+  glj.ID = uuidV1();
+  let [info,projectGLJ ] = await ration_glj_facade.getInfoFromProjectGLJ(glj);
+  let newRecode  = ration_glj_facade.createNewRecord(info);
+  return [newRecode,projectGLJ];
 }
 
-async function addInstallationGLJ(glj) {
-    glj.ID = uuidV1();
-    let [info,projectGLJ ] = await ration_glj_facade.getInfoFromProjectGLJ(glj);
-    let newRecode  = ration_glj_facade.createNewRecord(info);
-    return [newRecode,projectGLJ];
-}
-
-
 function generateTasks(data,userID) {
     let tasks=[];
     let deleteInfo={deleted: true, deleteDateTime: new Date(), deleteBy: userID};
@@ -151,81 +86,70 @@ function generateTasks(data,userID) {
 }
 
 async function updateNodes(datas){
-    let nodeGroups = _.groupBy(datas,'type');
-    let rationTasks = [];
-    let billTasks = [];
-    let rationGLJTasks = [];
-    let projectGLJTasks = [];
-    let projectTasks = [];
-    let rationTemplateTasks = [];
-    let asyncTasks = [];
-    for(let type in nodeGroups){
-        for(let node of nodeGroups[type]){
-            if(type == projectConsts.BILLS){
-                billTasks.push(getTask(node));
-            }else if(type == projectConsts.RATION){
-                rationTasks.push(getTask(node));
-            }else if(type == projectConsts.RATION_GLJ){
-                rationGLJTasks.push(getTask(node));
-            }else if(type == projectConsts.PROJECTGLJ){
-                projectGLJTasks.push(getTask(node,'id'));
-            }else if(type == projectConsts.PROJECT){
-                projectTasks.push(getTask(node));
-            }else if(type == projectConsts.RATION_TEMPLATE){
-                rationTemplateTasks.push(getTask(node))
-            }
+  let nodeGroups = _.groupBy(datas,'type');
+  let asyncTasks = [];
+  let deleteRationIDs=[];
+  let taskMap = {};
+  taskMap[projectConsts.BILLS] = {tasks:[],model:bill_model.model};
+  taskMap[projectConsts.RATION] = {tasks:[],model:ration_model.model};
+  taskMap[projectConsts.RATION_GLJ] = {tasks:[],model:ration_glj_model};
+  taskMap[projectConsts.PROJECTGLJ] = {tasks:[],model:project_glj_model};
+  taskMap[projectConsts.PROJECT] = {tasks:[],model:projectsModel};
+  taskMap[projectConsts.RATION_TEMPLATE] = {tasks:[],model:rationTemplateModel};
+
+  for(let type in nodeGroups){
+      for(let node of nodeGroups[type]){
+          if(taskMap[type]){
+              if(type == projectConsts.RATION){
+                  if(node.action == "delete") deleteRationIDs.push(node.data.ID);
+              }
+              if(type == projectConsts.RATION_GLJ){
+                  if(node.action == "add"){//添加定額工料机的時候,要先走项目工料机的逻辑
+                      let [newRecode,projectGLJ] = await createRationGLJData(node.data);
+                      node.data =newRecode;
+                      node.projectGLJ = projectGLJ;
+                  }
+              }
+              taskMap[type].tasks.push(getTask(node));
+          }
+      }
+  }
 
-        }
-    }
-    rationTasks.length>0?asyncTasks.push(ration_model.model.bulkWrite(rationTasks)):'';
-    billTasks.length>0?asyncTasks.push(bill_model.model.bulkWrite(billTasks)):"";
-    rationGLJTasks.length>0?asyncTasks.push(ration_glj_model.bulkWrite(rationGLJTasks)):"";
-    projectGLJTasks.length>0?asyncTasks.push(project_glj_model.bulkWrite(projectGLJTasks)):"";
-    projectTasks.length>0?asyncTasks.push(projectsModel.bulkWrite(projectTasks)):"";
-    rationTemplateTasks.length>0?asyncTasks.push(rationTemplateModel.bulkWrite(rationTemplateTasks)):"";
-    return  asyncTasks.length>0?await Promise.all(asyncTasks):"";
+  for(let key in taskMap){
+      if(taskMap[key].tasks.length> 0) asyncTasks.push(taskMap[key].model.bulkWrite(taskMap[key].tasks))
+  }
 
-    function getTask(node,idFiled = 'ID') {
+  if(asyncTasks.length>0) await Promise.all(asyncTasks);
+  if(deleteRationIDs.length > 0) await ration_glj_model.deleteMany({rationID: {$in: deleteRationIDs}});
 
-        let task={
-            updateOne:{
-                filter:{},
-                update :_.cloneDeep(node.data)
-            }
-        };
-        task.updateOne.filter[idFiled] = node.data[idFiled];//现在复制项目也重新生成一个新的ID了,所以ID是唯一的
-        delete task.updateOne.update[idFiled];//防止误操作
-        return task;
-    }
-}
 
+  return datas;
+
+
+  function getTask(node,idFiled = 'ID') {
+      let task={};
+      if(node.action == "add"){
+          task.insertOne ={
+              document:node.data
+          }
+      }else if(node.action =="delete"){
+          task.deleteOne ={
+              filter:{}
+          };
+          task.deleteOne.filter[idFiled] = node.data[idFiled];
+      }else {
+          task.updateOne = {
+              filter:{},
+              update :_.cloneDeep(node.data)
+          };
+          task.updateOne.filter[idFiled] = node.data[idFiled];//现在复制项目也重新生成一个新的ID了,所以ID是唯一的
+          delete task.updateOne.update[idFiled];//防止误操作
+      }
+
+      return task;
+  }
+}
 
-/*function updateNodes(datas,callback) {
-    let tasks = [];
-    for(let node of datas){
-        tasks.push(updateOne(node))
-    }
-    async_n.parallel(tasks, function(err, results) {
-        if (!err){
-            callback(0, '', results);
-        }
-        else{
-            console.log(err);
-            callback(1, 'save project failed'+err.message, null);
-        }
-    });
-    function updateOne(node) {
-        if(node.type == projectConsts.BILLS){
-            return function (asCallback) {
-                bill_model.model.findOneAndUpdate({projectID: node.data.projectID, ID: node.data.ID,deleteInfo: null}, node.data,{new: true}, asCallback);
-            }
-        }else if(node.type ==projectConsts.RATION){
-            return function (asCallback) {
-                ration_model.model.findOneAndUpdate({projectID: node.data.projectID, ID: node.data.ID,deleteInfo: null}, node.data,{new: true}, asCallback);
-            }
-        }
-    }
-}*/
 
 //data = {feeRateID:111111,projectID:1245}; type = feeRate
 async function markUpdateProject(data,type) {

+ 64 - 7
modules/main/facade/ration_facade.js

@@ -6,6 +6,7 @@ module.exports = {
   replaceRations: replaceRations,
   addNewRation:addNewRation,
   updateMaterialRation:updateMaterialRation,
+  updateDivideRation:updateDivideRation,
   addMaterialRation:addMaterialRation,
   addMultiRation: addMultiRation,
   getSameSectionRations:getSameSectionRations,
@@ -33,6 +34,7 @@ let ration_coe = mongoose.model('ration_coe');
 let ration_model = require('../models/ration');
 let bill_model = require('../models/bills');
 let decimal_facade = require('./decimal_facade');
+let divide_facade = require('./divide_facade');
 let installationFeeModel = mongoose.model("installation_fee");
 let rationInstallationModel = mongoose.model('ration_installation');
 let rationTemplateModel = mongoose.model('ration_template');
@@ -57,6 +59,7 @@ let projectModel = mongoose.model('projects');
 let unitPriceModel = mongoose.model('unit_price');
 let unitPriceFileModel = mongoose.model('unit_price_file');
 let vvTaxModel =  mongoose.model("std_vehicleVesselTax_items");
+let divideModel = mongoose.model("divide_setting");
 
 const fs = require('fs');
 
@@ -98,6 +101,19 @@ async function updateMaterialRation(data,compilation){
     return result;
 }
 
+async function updateDivideRation(data,compilation){
+  let result = {};
+    switch (data.type){
+        case "add":
+            result = await addDivideRation(data,compilation);
+            break;
+        case "update":
+            result = await modifyDivideRation(data,compilation);
+            break;
+    }
+    return result;
+}
+
 async function deleteMaterialRation(data) {
     let model = data.type == "freight"?freightCalcModel:originaltCalcModel;
     await model.update(
@@ -146,14 +162,52 @@ async function addMaterialRation(data,compilation) {
     return{ration:newRation,ration_gljs:ration_gljs,projectGLJList:projectGLJList};
 }
 
-async function getNewMaterialRationDatas(data,compilation){
+
+async function addDivideRation(data,compilation){
+  let [newRation,ration_gljs,projectGLJList,ration_coes] = await getNewMaterialRationDatas(data,compilation,true);
+  delete newRation.projectID; 
+  newRation.type=1;
+  newRation.ParentID = data.ParentID;
+  newRation.itemType = "定额";
+  newRation.programID = data.programID;
+  newRation.seq = data.seq;
+  await divideModel.update({ID:data.divideID},{$push:{divideList:newRation,ration_gljs:{$each:ration_gljs},ration_coes:{$each:ration_coes}}});
+  if(data.divideDatas.length > 0)await divide_facade.updateItem({ID:data.divideID,updateDatas:data.divideDatas});
+  return{ration:newRation,ration_gljs:ration_gljs,projectGLJList:projectGLJList,ration_coes};
+}
+
+async function modifyDivideRation(data,compilation){//目前只有替换分摊的定额走这个逻辑
+  let [newRation,ration_gljs,projectGLJList,ration_coes] = await getNewMaterialRationDatas(data,compilation,true);
+  newRation.quantity = data.oldData.quantity;
+  newRation.type=1;
+  newRation.itemType = "定额";
+  if(data.oldData.programID && data.oldData.programID!="")newRation.programID = data.oldData.programID; 
+  newRation.seq = data.oldData.seq;
+  newRation.ParentID = data.oldData.ParentID;
+  await divideModel.update({ID:data.ID},{$push:{divideList:newRation,ration_gljs:{$each:ration_gljs},ration_coes:{$each:ration_coes}}});
+  await divideModel.update(
+    {ID:data.ID},
+    { 
+      $pull: {divideList:{ID:data.rationID},ration_gljs:{rationID:data.rationID},ration_coes:{rationID:data.rationID}}
+    },
+    { multi: true })
+    return {ration:newRation,ration_gljs:ration_gljs,projectGLJList:projectGLJList,ration_coes}
+}
+
+
+async function getNewMaterialRationDatas(data,compilation,withCoe = false){
     let searchDao = new SearchDao();
     let stdRation = await searchDao.getRationItem(data.userID, compilation._id, data.rationRepIds,data.code);
     if(!stdRation) throw  "找不到指定的定额!";//new Error("找不到指定的定额!");
 
     let newRation = await createNewMaterialRation(stdRation,data.quantityDecimal,data.projectID);
     let [ration_gljs,projectGLJList] = await addRationGLJ(stdRation,newRation,compilation,true,data.connect_key);
-    return [newRation,ration_gljs,projectGLJList];
+    let result = [newRation,ration_gljs,projectGLJList]
+    if(withCoe == true){
+      let ration_coes = await addRationCoe(stdRation,newRation,compilation,true);
+      result.push(ration_coes);
+    }
+    return result;
 }
 
 
@@ -170,6 +224,11 @@ async function createNewMaterialRation(std,quantityDecimal,projectID){
     newData.quantity=scMathUtil.roundForObj(1 / FilterNumberFromUnit(std.unit),quantityDecimal);
     newData.from = std.type === 'complementary' ? 'cpt' : 'std';
     newData.rationAssList =await  createRationAss(std,true);
+    if(std.feeType == undefined || std.feeType == null || std.feeType ==''){//定额取费专业为空的情况下,取项目属性中的定额取费专业ID
+      newData.programID = await getProgramForProject(projectID);
+    }else {
+      newData.programID = std.feeType;
+    }
     return newData;
 }
 
@@ -410,11 +469,9 @@ async function addRationTemplate(std,newRation) {
 }
 
 
-async function addRationCoe(std,newRation,compilation) {
+async function addRationCoe(std,newRation,compilation,notInsert = false) {
     let ration_coe_list = [];
     let seq = 0;
-    let stdCoeIDs = [];
-    let coeMap={}
 
     if(std.hasOwnProperty('rationCoeList')&&std.rationCoeList.length>0){//添加标准库的工料机
         for(let sub of std.rationCoeList){
@@ -445,7 +502,7 @@ async function addRationCoe(std,newRation,compilation) {
     }
     let lastCoe = await getCustomerCoe(newRation.projectID,newRation.ID,seq,compilation);
     ration_coe_list.push(lastCoe);
-    await ration_coe.insertMany(ration_coe_list);
+    if(notInsert!=true) await ration_coe.insertMany(ration_coe_list);//分摊下的时候不保存在这里
     return ration_coe_list;
 
 }
@@ -1111,7 +1168,7 @@ async function  updateRation(std,defaultLibID,rationID,billsItemID,projectID,cal
     //定额前缀 none:0, complementary:1, borrow: 2
     ration.prefix = '';
     //借用优先级比补充高
-    if(ration.from === ' std' && std.rationRepId !== parseInt(defaultLibID)){//借用
+    if(ration.from === 'std' && std.rationRepId !== parseInt(defaultLibID)){//借用
         ration.prefix = '借';
     } else if(ration.from === 'cpt') {
         ration.prefix = '补';

+ 2 - 1
modules/main/models/project.js

@@ -18,7 +18,7 @@ var calc_program_facade = require('../facade/calc_program_facade');
 import GLJController from "../../glj/controllers/glj_controller";
 let installation_facade = require('../facade/installation_facade');
 let pmController = require('../../pm/controllers/pm_controller');
-
+let divide_facade = require('../facade/divide_facade');
 
 const ProjectModel = require('../../pm/models/project_model').project;
 import GLJListModel from "../../glj/models/glj_list_model";
@@ -45,6 +45,7 @@ moduleMap[projectConsts.PROJECTGLJ] = new GLJController();
 moduleMap[projectConsts.INSTALLATION_FEE] = installation_facade;
 moduleMap[projectConsts.RATION_TEMPLATE] = ration_template;
 moduleMap[projectConsts.PROJECT_INFO] = pmController;
+moduleMap[projectConsts.DIVIDE_SETTING] = divide_facade;
 
 var Project = function (){};
 

+ 2 - 1
modules/main/models/project_consts.js

@@ -21,7 +21,8 @@ let projectConst = {
     LABOUR_COE:'labour_coe',
     CALC_PROGRAM:'calc_program',
     INSTALLATION_FEE:'installation_fee',
-    PROJECT_INFO: 'project_info'
+    PROJECT_INFO: 'project_info',
+    DIVIDE_SETTING:'divide_setting'
 };
 
 let projectConstList = [

+ 17 - 0
modules/main/routes/divide_route.js

@@ -0,0 +1,17 @@
+/**
+ * Created by zhang on 2018/9/12.
+ */
+
+let express = require('express');
+let divideController = require('../controllers/divide_controller');
+
+module.exports = function (app) {
+
+    var divideRouter = express.Router();
+
+    divideRouter.post('/updateItem', divideController.action);
+    divideRouter.post('/updateCoeAdjust', divideController.action);
+    //materialRouter.post('/replace', materialController.action);//材料替换,其实是材料修改
+
+    app.use('/divide',divideRouter);
+}

+ 1 - 0
modules/main/routes/ration_route.js

@@ -20,5 +20,6 @@ module.exports = function (app) {
     rationRouter.post('/applyTemplate', rationController.action);
     rationRouter.post('/updateRationAss', rationController.action);
     rationRouter.post('/updateCoeAdjust', rationController.action);
+    rationRouter.post('/updateDivideRation', rationController.action);
     app.use('/ration', rationRouter);
 };

+ 43 - 16
modules/pm/facade/pm_facade.js

@@ -90,7 +90,7 @@ let progressiveModel = mongoose.model('std_progressive_lib');
 let importLogsModel = mongoose.model("import_logs");
 const shareListModel = mongoose.model('share_list');
 let welcomeModel = mongoose.model("welcome_setting");
-
+let divideModel = mongoose.model("divide_setting");
 
 let featureLibModel =  mongoose.model("std_project_feature_lib");
 let scMathUtil = require('../../../public/scMathUtil').getUtil();
@@ -587,6 +587,10 @@ async function copyProject(userID, compilationID, data, newProjectID = null, del
     if(originalProperty.labourCoeFile){
         copyTasks.push(commonCopy(newProjectID,originalProperty.labourCoeFile.ID,labourCoeFileID,labourCoesModel));
     }
+    //复制分摊信息
+    let divide_setting = await divideModel.findOne({projectID:originalID}, '-_id').lean();
+    if(divide_setting) copyTasks.push(copyDivide(divide_setting,newProjectID,projectGLJMap.IDMap));
+
     // 处理单价、费率文件
     if (saveAsFile) {
         let feeRateFileName = isSaveAs ? projectName : originalProperty.feeFile.name;
@@ -754,6 +758,15 @@ async  function commonCopy(newProjectID,oldID,newID,model) { //对于只需更
     return result;
 }
 
+async function copyDivide(divide_setting,newProjectID,projectGLJIDMap){
+  divide_setting.ID = uuidV1();
+  divide_setting.projectID = newProjectID;
+  for(let rg of divide_setting.ration_gljs){
+    rg.projectGLJID = projectGLJIDMap[rg.projectGLJID]
+  }
+  return await divideModel.create(divide_setting);
+}
+
 async function copyFeeRate(rootProjectID,userID,originalFeeRateFileID,feeRateFileID,newName) {//复制费率和费率文件
     let [feeRateFile,feeRate] =await feeRate_facade.getFeeRateByID(originalFeeRateFileID);
     let newFeeRateID = uuidV1();
@@ -1591,17 +1604,18 @@ async function exportTenderData(data){
     let result = {};
     let projectSetting =  await projectSettingModel.findOne({"projectID": data.projectID}, '-_id');
     if(projectSetting) result['projSetting'] = projectSetting;
-    result.bills = await billsModel.find({"projectID": data.projectID});
-    result.rations = await rationModel.find({'$or': [{projectID: data.projectID, deleteInfo: null}, {projectID: data.projectID, 'deleteInfo.deleted': {$in: [null, false]}}]});
-    result.projectGLJs = await gljListModel.find({'project_id':data.projectID});
-    result.installationFees =  await installationFeeModel.find({projectID:data.projectID});
-    result.rationGLJs = await rationGLJModel.find({projectID:data.projectID});
-    result.rationCoes = await rationCoeModel.find({projectID:data.projectID});
-    result.quantityDetails = await quantityDetailModel.find({projectID:data.projectID});
-    result.rationInstallations = await rationInstallationModel.find({projectID:data.projectID});
-    result.rationTemplates = await rationTemplateModel.find({projectID:data.projectID});
-    result.calcProgramsFile = await calcProgramsModel.findOne({projectID:data.projectID});
-    result.labourCoes = await labourCoesModel.findOne({projectID:data.projectID});
+    result.bills = await billsModel.find({"projectID": data.projectID}).lean();
+    result.rations = await rationModel.find({'$or': [{projectID: data.projectID, deleteInfo: null}, {projectID: data.projectID, 'deleteInfo.deleted': {$in: [null, false]}}]}).lean();
+    result.projectGLJs = await gljListModel.find({'project_id':data.projectID}).lean();
+    result.installationFees =  await installationFeeModel.find({projectID:data.projectID}).lean();
+    result.rationGLJs = await rationGLJModel.find({projectID:data.projectID}).lean();
+    result.rationCoes = await rationCoeModel.find({projectID:data.projectID}).lean();
+    result.quantityDetails = await quantityDetailModel.find({projectID:data.projectID}).lean();
+    result.rationInstallations = await rationInstallationModel.find({projectID:data.projectID}).lean();
+    result.rationTemplates = await rationTemplateModel.find({projectID:data.projectID}).lean();
+    result.calcProgramsFile = await calcProgramsModel.findOne({projectID:data.projectID}).lean();
+    result.labourCoes = await labourCoesModel.findOne({projectID:data.projectID}).lean();
+    result.divide_setting = await divideModel.findOne({projectID:data.projectID}, '-_id').lean();
 
     return cipher.aesEncrypt(JSON.stringify(result));
 }
@@ -1747,9 +1761,9 @@ async function importProject(data,req,updateData) {
             let [constructionProjectID,projectIDMap,labourCoeFileIDMap,calcProgramFileIDMap] = await handleMainProjectDatas(mainData,updateData,req.session.sessionUser.id);
             result.constructionProjectID = constructionProjectID;
             if(datas.length > 1 ){//生成后统一次插入 2020-05-29
-              let newProjectSettings=[],bills=[],rations=[],projectGLJs=[],rationGLJs=[],rationCoes=[],quantityDetails=[],rationInstallations=[],rationTemplates=[],newCalcProgramsFiles=[],newLabourCoes=[];
+              let newProjectSettings=[],bills=[],rations=[],projectGLJs=[],rationGLJs=[],rationCoes=[],quantityDetails=[],rationInstallations=[],rationTemplates=[],newCalcProgramsFiles=[],newLabourCoes=[],newDivides=[];
                 for(let i = 1;i<datas.length;i++){
-                  let [newProjectSetting,tbills,trations,tprojectGLJs,trationGLJs,trationCoes,tquantityDetails,trationInstallations,trationTemplates,newCalcProgramsFile,newLabourCoe] =  await handleEachProject(datas[i],projectIDMap,labourCoeFileIDMap,calcProgramFileIDMap)
+                  let [newProjectSetting,tbills,trations,tprojectGLJs,trationGLJs,trationCoes,tquantityDetails,trationInstallations,trationTemplates,newCalcProgramsFile,newLabourCoe,newDivide] =  await handleEachProject(datas[i],projectIDMap,labourCoeFileIDMap,calcProgramFileIDMap)
                   if(newProjectSetting) newProjectSettings.push(newProjectSetting);
                   if(tbills.length > 0) bills = bills.concat(tbills);
                   if(trations.length > 0) rations = rations.concat(trations);
@@ -1761,6 +1775,7 @@ async function importProject(data,req,updateData) {
                   if(trationTemplates.length > 0) rationTemplates = rationTemplates.concat(trationTemplates); 
                   if(newCalcProgramsFile) newCalcProgramsFiles.push(newCalcProgramsFile);
                   if(newLabourCoe) newLabourCoes.push(newLabourCoe);
+                  if(newDivide) newDivides.push(newDivide);
                 }
 
                 if(newProjectSettings.length > 0) await insertMany(newProjectSettings,projectSettingModel);
@@ -1774,6 +1789,7 @@ async function importProject(data,req,updateData) {
                 if(rationTemplates.length > 0) await insertMany(rationTemplates,rationTemplateModel);
                 if(newCalcProgramsFiles.length > 0) await insertMany(newCalcProgramsFiles,calcProgramsModel);
                 if(newLabourCoes.length>0) await insertMany(newLabourCoes,labourCoesModel);
+                if(newDivides.length>0) await divideModel.insertMany(newDivides);
             }
 
          }
@@ -1783,7 +1799,7 @@ async function importProject(data,req,updateData) {
 
 async function handleEachProject(data,projectIDMap,labourCoeFileIDMap,calcProgramFileIDMap){
     let bills = [],rations = [],projectGLJs = [],rationGLJs=[],rationCoes=[],quantityDetails=[],rationInstallations=[],rationTemplates=[];
-    let newProjectSetting =null,newCalcProgramsFile = null,newLabourCoe = null;
+    let newProjectSetting =null,newCalcProgramsFile = null,newLabourCoe = null,newDivide=null;
     let billsIDMap = {},projectGLJIDMap={},rationIDMap = {};
     let newProjectID = projectIDMap[data.projSetting.projectID];
     //生成新的清单;
@@ -1852,7 +1868,18 @@ async function handleEachProject(data,projectIDMap,labourCoeFileIDMap,calcProgra
         newLabourCoe = data.labourCoes;
         delete newLabourCoe._id;
     }
-    return [newProjectSetting,bills,rations,projectGLJs,rationGLJs,rationCoes,quantityDetails,rationInstallations,rationTemplates,newCalcProgramsFile,newLabourCoe]
+
+    if(data.divide_setting){
+      data.divide_setting.ID = uuidV1();
+      data.divide_setting.projectID = newProjectID;
+      for(let rg of data.divide_setting.ration_gljs){
+        rg.projectGLJID = projectGLJIDMap[rg.projectGLJID]
+      }
+      newDivide = data.divide_setting
+      delete newDivide._id;
+    } 
+
+    return [newProjectSetting,bills,rations,projectGLJs,rationGLJs,rationCoes,quantityDetails,rationInstallations,rationTemplates,newCalcProgramsFile,newLabourCoe,newDivide]
 
 }
 

+ 83 - 32
modules/ration_glj/facade/glj_calculate_facade.js

@@ -11,6 +11,7 @@ let ration_coe = mongoose.model('ration_coe');
 const ProjectModel = require('../../pm/models/project_model').project;
 let mixRatioModel = mongoose.model('mix_ratio');
 let std_ration_lib_ration_items = mongoose.model('std_ration_lib_ration_items');
+let divideModel = mongoose.model("divide_setting");
 let std_glj_lib_gljList_model = mongoose.model('std_glj_lib_gljList');
 let glj_type_util = require('../../../public/cache/std_glj_type_util');
 const scMathUtil = require('../../../public/scMathUtil').getUtil();
@@ -20,6 +21,7 @@ const common_util = require('../../../public/common_util');
 
 module.exports={
     calculateQuantity:calculateQuantity,
+    calculateQuantityFromDivide:calculateQuantityFromDivide,
     getGLJTypeByID:getGLJTypeByID
 }
 //辅助定额调整、稳定土配合比、替换工料机、标准附注条件调整、添加工料机、自定义消耗量(包括删除工料机)、自定义乘系数、市场单价调整
@@ -44,6 +46,78 @@ let coeTypeMap = {
 };
 
 
+async function handleAndGetAssList(impactRation,adjustState){
+  let assList=[], assRation = null;
+  if(impactRation && impactRation.rationAssList.length>0){
+    prepareAss(impactRation.rationAssList);
+    let temTimes = [];
+    let thirdRationCodes=[];
+    for(let i=0;i<impactRation.rationAssList.length;i++){
+        let times = calculateTimes(impactRation.rationAssList[i]);
+        if(times!=0){
+            let thirdRationCode = impactRation.rationAssList[i].thirdRationCode;
+            if(thirdRationCode && thirdRationCode !=''){
+                temTimes.push(times);
+                thirdRationCodes.push(thirdRationCode)
+            }
+            assRation = await  std_ration_lib_ration_items.findOne({rationRepId:impactRation.libID,code:impactRation.rationAssList[i].assistCode});
+            assList.push({times:times,assRation:assRation});
+            adjustState.push({index:stateSeq.ass,content:impactRation.rationAssList[i].name+" "+impactRation.rationAssList[i].actualValue+" : +"+impactRation.rationAssList[i].assistCode+"x"+times});
+        }
+    }
+    if(temTimes.length == 2 &&thirdRationCodes[0] == thirdRationCodes[1] ){ //说明有第三定额
+        let times_t = temTimes[0] * temTimes[1];
+        let tration =  await  std_ration_lib_ration_items.findOne({rationRepId:impactRation.libID,code:thirdRationCodes[0]});
+        if(tration){
+            assList.push({times:times_t,assRation:tration});
+            adjustState.push({index:stateSeq.ass,content:"+"+thirdRationCodes[0]+"x"+times_t});
+        }
+    }
+  }
+  return assList;
+}
+
+
+async function calculateQuantityFromDivide(ID,rationID){
+  let tasks=[],udatas=[];
+  let divide_setting = await divideModel.findOne({ID:ID}).lean();
+  let impactRation = null,gljList=[],coeList=[],assList=[], adjustState=[],mixRatioMap = {};
+  for(let r of divide_setting.divideList){
+    if(r.ID == rationID){
+      impactRation = r;
+      break; 
+    } 
+  }
+  if(impactRation == null) return null;
+  for(let rg of divide_setting.ration_gljs){
+    if(rg.rationID == rationID) gljList.push(rg);
+  }
+  for(let co of divide_setting.ration_coes){
+    if(co.rationID == rationID) coeList.push(co);
+  }
+  assList = await handleAndGetAssList(impactRation,adjustState);
+  for(let glj of gljList){//先把混凝土,砂浆,配合比有自定义消耗的挑出来
+    if(gljUtil.isConcreteType(glj.type)) await getMixRatioMap(glj,gljList,coeList,assList,mixRatioMap);
+  }
+  for(let i =0;i<gljList.length;i++ ){
+    let r = await calculateQuantityPerGLJ(gljList[i],gljList,coeList,assList,adjustState,mixRatioMap,null);
+    if(quantityUpdateCheck(gljList[i],r) == true){
+      let ndoc={};
+      for(let key in r.doc){
+        ndoc["ration_gljs.$."+key] = r.doc[key]
+      }
+      udatas.push({ID:gljList[i].ID,model:"ration_gljs",type:"update",doc:r.doc});
+      tasks.push({updateOne: {filter: {"ID": ID,"ration_gljs.ID":gljList[i].ID}, update: ndoc}});
+    } 
+  }
+  let newName = generateRationName(impactRation,gljList);
+  udatas.push({ID:impactRation.ID,type:"update",doc:{name:newName}});
+  tasks.push({updateOne: {filter: {"ID": ID,"divideList.ID":impactRation.ID}, update: {"divideList.$.name":newName}}});
+  return [tasks,udatas];
+}
+  
+
+
 async function calculateQuantity(query,noNeedCal=null,refreshRationName = false){
     try {
         let  result ={
@@ -53,35 +127,12 @@ async function calculateQuantity(query,noNeedCal=null,refreshRationName = false)
         let impactRation = await ration.findOne({ID:query.rationID});
         let gljList = await ration_glj.find(query);//{projectID:query.projectID,rationID:query.rationID}
         let coeList = await ration_coe.find({rationID:query.rationID}).sort('seq').exec();
-        let assList=[], assRation = null, adjustState=[],mixRatioMap = {};
+        let assList=[], adjustState=[],mixRatioMap = {};
         if(!impactRation){//如果定额不存在或者已删除,返回空
             return null;
         }
         if(impactRation._doc.hasOwnProperty("rationAssList")&&impactRation.rationAssList.length>0){
-            prepareAss(impactRation.rationAssList);
-            let temTimes = [];
-            let thirdRationCodes=[];
-            for(let i=0;i<impactRation.rationAssList.length;i++){
-                let times = calculateTimes(impactRation.rationAssList[i]);
-                if(times!=0){
-                    let thirdRationCode = impactRation.rationAssList[i].thirdRationCode;
-                    if(thirdRationCode && thirdRationCode !=''){
-                        temTimes.push(times);
-                        thirdRationCodes.push(thirdRationCode)
-                    }
-                    assRation = await  std_ration_lib_ration_items.findOne({rationRepId:impactRation.libID,code:impactRation.rationAssList[i].assistCode});
-                    assList.push({times:times,assRation:assRation});
-                    adjustState.push({index:stateSeq.ass,content:impactRation.rationAssList[i].name+" "+impactRation.rationAssList[i].actualValue+" : +"+impactRation.rationAssList[i].assistCode+"x"+times});
-                }
-            }
-            if(temTimes.length == 2 &&thirdRationCodes[0] == thirdRationCodes[1] ){ //说明有第三定额
-                let times_t = temTimes[0] * temTimes[1];
-                let tration =  await  std_ration_lib_ration_items.findOne({rationRepId:impactRation.libID,code:thirdRationCodes[0]});
-                if(tration){
-                    assList.push({times:times_t,assRation:tration});
-                    adjustState.push({index:stateSeq.ass,content:"+"+thirdRationCodes[0]+"x"+times_t});
-                }
-            }
+          assList = await handleAndGetAssList(impactRation,adjustState);
         }
         // 稳定土调整状态
         const proportionStr = gljList.filter(glj => glj.rationProportion).map(glj => glj.adjustProportion || 0).join(':');
@@ -119,7 +170,7 @@ async function calculateQuantity(query,noNeedCal=null,refreshRationName = false)
 
 function quantityUpdateCheck(glj,r) {//检查,有改变的才更新
     for(let key in r.doc){
-        if(glj._doc[key] != r.doc[key]) return true
+        if(glj[key] != r.doc[key]) return true
     }
     return false
 }
@@ -290,7 +341,7 @@ async function getMixRatioMap(glj,gljList,coeList,assList,mixRatioMap) {//生成
 
 
 function noCustomQuantiyt(glj) {//是否有自定义消耗量
-    return !glj._doc.hasOwnProperty('customQuantity')||glj.customQuantity==null||glj.customQuantity==""
+    return glj.customQuantity===undefined||glj.customQuantity===null||glj.customQuantity==""
 }
 
 async function calculateAss(quantity,assList,glj) {
@@ -320,11 +371,11 @@ async function calculateAss(quantity,assList,glj) {
 
 function generateAdjustState(glj,coeList,adjustState,gljList,quantity) {
    //替换工料机 and 添加工料机
-    if(glj._doc.createType=='replace'&&glj.rcode!=glj.code){
+    if(glj.createType=='replace'&&glj.rcode!=glj.code){
         adjustState.push({index:stateSeq.replace,content:glj.rcode+'换'+glj.code});
-    }else if(glj._doc.createType=='add'){
+    }else if(glj.createType=='add'){
         let displayQuantity = quantity;
-        if(glj._doc.hasOwnProperty('customQuantity')&&(glj.customQuantity != null||glj.customQuantity != '')){
+        if(glj.hasOwnProperty('customQuantity')&&(glj.customQuantity != null||glj.customQuantity != '')){
             displayQuantity = glj.customQuantity;
         }
         displayQuantity = displayQuantity&&displayQuantity!=""?parseFloat(displayQuantity):0;
@@ -354,13 +405,13 @@ function generateAdjustState(glj,coeList,adjustState,gljList,quantity) {
     }
 
     //自定义消耗量
-    if(glj._doc.createType!='add'&&glj._doc.hasOwnProperty('customQuantity')){
+    if(glj.createType!='add'&&glj.hasOwnProperty('customQuantity')){
         if(glj.customQuantity!==null&&glj.customQuantity!=""){
             adjustState.push({index:stateSeq.cusQuantity,content:glj.code+'量'+parseFloat(glj.customQuantity)});
         }
     }
     //市场单价调整
-    if(glj._doc.hasOwnProperty('marketPriceAdjust')&&glj.marketPriceAdjust&&glj.marketPriceAdjust!=0){
+    if(glj.hasOwnProperty('marketPriceAdjust')&&glj.marketPriceAdjust&&glj.marketPriceAdjust!=0){
         //0101005价66.00
         adjustState.push({index:stateSeq.adjMak,content:glj.code+'价'+glj.marketPriceAdjust});
     }

+ 20 - 14
modules/ration_glj/facade/ration_glj_facade.js

@@ -732,7 +732,7 @@ async function addGLJ(rgList,compilation) {
     return result;
 }
 
-async function insertAddTypeGLJ(rgList,compilation) {
+async function insertAddTypeGLJ(rgList,compilation,needInsert=true) {
     let newRecodes = [],GLJMap=null;
     let projectGLJList = [];
     let [unitFileId,ext] = await  prepareExtData(rgList[0].projectID,compilation);
@@ -764,7 +764,8 @@ async function insertAddTypeGLJ(rgList,compilation) {
         newRecodes.push(createNewRecord(g));
         projectGLJList.push(result);
     }
-    await ration_glj.insertMany(newRecodes);
+    //分摊那里调用时不用真的插入
+    if(needInsert == true) await ration_glj.insertMany(newRecodes);
     return [newRecodes,projectGLJList];
 }
 
@@ -843,32 +844,37 @@ function addMixRatioToRationGLJ(g,subList,newRecodes,GLJMap){
     return newMap;
 }
 
-async  function replaceGLJByData(data,compilation) {
+async  function replaceGLJByData(data,compilation,needUpdate = true,rationGLJList) {
     let projectGljModel = new GLJListModel(),newRecodes=[],deleteList=[];
     let [unitFileId,ext] = await  prepareExtData(data.projectID,compilation);
     let result = await projectGljModel.addList(getGLJSearchInfo(data),unitFileId,ext);
     data.projectGLJID = result.id;
     if(data.toCommercial == true){//从混凝土改成商品混凝土,
-       let [contype,newR] =  await concreteTypeToCommercial(data);
+       let [contype,newR] =  await concreteTypeToCommercial(data,needUpdate);
         newRecodes.push(newR);
         data=contype;
     }else {
-        let [newList,tdelList] = await replaceMixRatio(data,result,unitFileId);
+        let [newList,tdelList] = await replaceMixRatio(data,result,unitFileId,needUpdate,rationGLJList);
         newRecodes = newList;
         deleteList = tdelList;
-        let updateResult = await ration_glj.findOneAndUpdate({ID: data.ID, projectID: data.projectID}, data);//更新定额工料机
+        if(needUpdate==true) await ration_glj.findOneAndUpdate({ID: data.ID, projectID: data.projectID}, data);//更新定额工料机
     }
 
     return {data:data,newRecodes:newRecodes,deleteList:deleteList,projectGLJ:result};
 }
 
 
-async function concreteTypeToCommercial(data) {
-   //旧的自定义消耗量改为0
-   let contype =  await ration_glj.findOneAndUpdate({ID: data.originalID}, {customQuantity:'0'});
+async function concreteTypeToCommercial(data,needUpdate) {
+    //旧的自定义消耗量改为0
+    let contype = null;
+    if(needUpdate == true){
+      contype =  await ration_glj.findOneAndUpdate({ID: data.originalID}, {customQuantity:'0'});
+    }else{
+      contype = {customQuantity:'0'}
+    }
     //因为商品混凝土是没有组成物的,所以不用考虑组成物的情况
     let new_glj =  createComercialConcreteData(data);
-    await ration_glj.create(new_glj);
+    if(needUpdate == true) await ration_glj.create(new_glj);
     return [contype,new_glj];
 }
 
@@ -878,12 +884,12 @@ function createComercialConcreteData(data){
 }
 
 
-async function replaceMixRatio(g,result,unitFileId){
+async function replaceMixRatio(g,result,unitFileId,needUpdate,trationGLJList){
     let newRecodes=[],deleteList = [];
     if(gljUtil.isConcreteType(g.type)||gljUtil.isCommercialConcreteType(g.type)){//混凝土大类,商品混凝土属于相同大类,替换前和替换后只判断一个就好了
         let IDMap = {}, projectGLJMap = {},referenceMap={},concreteList=[],newMap={};
         let projectGljModel = new GLJListModel();
-        let rationGLJList = await ration_glj.find({'rationID':g.rationID});
+        let rationGLJList = trationGLJList?trationGLJList:await ration_glj.find({'rationID':g.rationID});
         for(let r of rationGLJList){
             IDMap[r.ID] = r;
             projectGLJMap[r.projectGLJID] = r;
@@ -906,8 +912,8 @@ async function replaceMixRatio(g,result,unitFileId){
         }
     }
 
-    if(deleteList.length > 0) await ration_glj.deleteMany({'ID': {"$in": deleteList}});//删除定额工料机
-    if(newRecodes.length > 0)  await ration_glj.insertMany(newRecodes);
+    if(deleteList.length > 0 && needUpdate==true) await ration_glj.deleteMany({'ID': {"$in": deleteList}});//删除定额工料机
+    if(newRecodes.length > 0 && needUpdate==true)  await ration_glj.insertMany(newRecodes);
     return [newRecodes,deleteList]
 }
 

+ 7 - 8
public/web/scMathUtil.js

@@ -173,21 +173,20 @@ let scMathUtil = {
     roundForObj:function(obj,decimal){
         let me = this;
         let value;
+        if(obj === undefined || obj === null) return 0;
+        let n = Math.pow(10,decimal);
         if(me.isNumber(obj)){
-            value = me.roundTo(obj,-decimal)
+          value = Math.round(obj * n) / n;
+          //value = me.roundTo(obj,-decimal)
         }else {
-            value = me.roundTo(Number(obj),-decimal);
+          value = Math.round(Number(obj) * n) / n;
+          //value = me.roundTo(Number(obj),-decimal);
         }
         return value
     },
     roundToString:function(obj,decimal){
         let me = this;
-        let value;
-        if(me.isNumber(obj)){
-            value = me.roundTo(obj,-decimal)
-        }else {
-            value = me.roundTo(Number(obj),-decimal);
-        }
+        let value = me.roundForObj(obj,decimal);
         return value.toFixed(decimal);
     },
     isNumOrFormula:function (text) {

+ 79 - 78
public/web/sheet/sheet_common.js

@@ -229,6 +229,80 @@ var sheetCommonObj = {
             sheet.setStyle(row, -1, setting.getStyle(data[row]));
         }
     },
+    showTreeData:function (sheet,setting,data) {
+      let ch = GC.Spread.Sheets.SheetArea.viewport;
+      let parentMap=_.groupBy(data, 'ParentID');
+      let visibleMap = {};
+      let styleRow=[];
+      let treeCol =  setting.treeCol?setting.treeCol:0;
+      sheet.suspendPaint();
+      sheet.suspendEvent();
+      for (let col = 0; col < setting.header.length; col++) {
+          let hAlign = "left", vAlign = "center";
+          if (setting.header[col].hAlign) {
+              hAlign = setting.header[col].hAlign;
+          } else if (setting.header[col].dataType !== "String"){
+              hAlign = "right";
+          }
+          vAlign = setting.header[col].vAlign?setting.header[col].vAlign:vAlign;
+          sheetCommonObj.setAreaAlign(sheet.getRange(-1, col, -1, 1), hAlign, vAlign);
+          if (setting.header[col].formatter) {
+              sheet.setFormatter(-1, col, setting.header[col].formatter, GC.Spread.Sheets.SheetArea.viewport);
+          }
+          if(setting.header[col].cellType === "comboBox"){
+              this.setComboBox(-1,col,sheet,setting.header[col].options,setting.header[col].editorValueType,setting.header[col].editable,setting.header[col].maxDropDownItems);
+          }
+          for (let row = 0; row < data.length; row++) {
+              if(data[row].cellType === 'comboBox'){
+                  let options = data[row].options ? data[row].options.split("@") : [];
+                  this.setComboBox(row,col,sheet,options);
+              }else if(data[row].cellType === 'String'){//默认设置字符输入,避免出现输入10:01变成日期的情况
+                  sheet.setFormatter(row, col,"@", GC.Spread.Sheets.SheetArea.viewport);
+              }
+              let val = data[row][setting.header[col].dataCode];
+              if(val&&setting.header[col].dataType === "Number"){
+                  if(setting.header[col].hasOwnProperty('decimalField')){
+                      let decimal = getDecimal(setting.header[col].decimalField);
+                      val =scMathUtil.roundToString(val,decimal);
+                      sheet.setFormatter(-1, col,getFormatter(decimal), GC.Spread.Sheets.SheetArea.viewport);
+                  }else {
+                    val = val + '';
+                  }
+              }
+              if(val!=null && setting.header[col].cellType == "checkBox"){
+                  this.setCheckBoxCell(row,col,sheet,val);
+              }
+              if(setting.header[col].getText) {
+                val = setting.getText[setting.header[col].getText](data[row], val)
+              }
+              sheet.setValue(row, col, val, ch);
+              if(col==treeCol){
+                  let treeType = sheetCommonObj.getTreeNodeCellType(data,row,parentMap,treeCol);
+                  sheet.getCell(row, col).cellType(treeType);
+                  visibleMap[data[row].ID] = treeType.collapsed;
+                  this.setRowVisible(data,row,visibleMap,sheet);
+              }
+              if(data[row].bgColour) styleRow.push(row)
+          }
+      }
+      for(let r of styleRow){
+          this.setRowStyle(r,sheet,data[r].bgColour);
+      }
+      this.lockCells(sheet,setting);
+      sheet.resumeEvent();
+      sheet.resumePaint();
+    },
+    setRowVisible:function (data,row,visibleMap,sheet) {
+      sheet.getRange(row , -1, 1, -1).visible(getVisible(data[row].ParentID));//显示或隐藏
+      function getVisible(ParentID) {
+          if(visibleMap[ParentID]) return false //如果父节点是缩起的,那就隐藏本身。
+          if(visibleMap[ParentID] == false){//如果父节点不是缩起的,要再往父节点找看
+              let pnode = _.find(data,{'ID':ParentID});
+              if(pnode) return getVisible(pnode.ParentID);//如果有父节点,递归调用
+              return true;//没有,返回显示
+          }
+      }
+    },
     checkData: function (col, setting, value) {
         let result = true;
         let validator = setting.header[col].validator !== undefined ? setting.header[col].validator : null;
@@ -398,81 +472,7 @@ var sheetCommonObj = {
         sheet.showRow(showRow, GC.Spread.Sheets.VerticalPosition.top);
 
     },
-    setSelectButton(row, col, sheet, header) {
-        /*  let getSelectButton = function (cellWidth=100) {
-              function moreButton() {
-  
-              }
-              moreButton.prototype = new GC.Spread.Sheets.CellTypes.Button();
-              moreButton.prototype.paint = function (ctx, value, x, y, w, h, style, options){
-                  GC.Spread.Sheets.CellTypes.Button.prototype.paint.call(this, ctx, value, x, y, w, h, style, options);
-                  let buttonW = cellWidth/5;
-                  let endX = x+w-2;
-                  if(value){
-                      let textWidth = ctx.measureText(value).width;
-                      let spaceWidth = cellWidth - buttonW;
-                      let textEndX = x+2+textWidth;
-                      if(spaceWidth<textWidth){
-                          for(let i = value.length-1;i>1;i--){
-                              let newValue = value.substr(0,i);
-                              let newTestWidth =  ctx.measureText(newValue).width;
-                              if(spaceWidth>newTestWidth){
-                                  value = newValue;
-                                  textEndX = x+2+newTestWidth;
-                                  break;
-                              }
-                          }
-                      }
-                      ctx.fillText(value,textEndX,y+h-5);
-                  }
-  
-                  //画三个点
-                  ctx.save();
-                  ctx.beginPath();
-                  ctx.arc(endX-buttonW/2,y+h/2,1,0,360,false);
-                  ctx.arc(endX-buttonW/2-4,y+h/2,1,0,360,false);
-                  ctx.arc(endX-buttonW/2+4,y+h/2,1,0,360,false);
-                  ctx.fillStyle="black";//填充颜色,默认是黑色
-                  ctx.fill();//画实心圆
-                  ctx.closePath();
-                  ctx.restore();
-              };
-  
-              moreButton.prototype.processMouseLeave= function (hitinfo) {
-                  let newCell = new selectButton();
-                  hitinfo.sheet.setCellType(hitinfo.row, hitinfo.col, newCell, GC.Spread.Sheets.SheetArea.viewport);
-                  hitinfo.sheet.getCell(hitinfo.row, hitinfo.col).locked(false);
-              };
-  
-              function selectButton() {
-              }
-  
-              selectButton.prototype = new GC.Spread.Sheets.CellTypes.Text();
-  
-              selectButton.prototype.paint = function (ctx, value, x, y, w, h, style, options){
-                  GC.Spread.Sheets.CellTypes.Text.prototype.paint.apply(this,arguments);
-              };
-              selectButton.prototype.getHitInfo = function (x, y, cellStyle, cellRect, context) {
-                  return {
-                      x: x,
-                      y: y,
-                      row: context.row,
-                      col: context.col,
-                      cellStyle: cellStyle,
-                      cellRect: cellRect,
-                      sheetArea: context.sheetArea
-                  };
-              };
-              selectButton.prototype.processMouseDown = function (hitinfo){
-                  if(hitinfo.sheet.getCell(hitinfo.row,hitinfo.col).locked()!=true){
-                      let b1 = new moreButton();
-                      b1.marginLeft(cellWidth*4/5);
-                      hitinfo.sheet.setCellType(hitinfo.row, hitinfo.col, b1, GC.Spread.Sheets.SheetArea.viewport);
-                      hitinfo.sheet.getCell(hitinfo.row, hitinfo.col).locked(true);
-                  }
-              };
-              return new selectButton();
-          };*/
+    setSelectButton(row, col, sheet, header) { 
         sheet.setCellType(row, col, this.getSelectButton(header.headerWidth), GC.Spread.Sheets.SheetArea.viewport);
     },
     getSelectButton(cellWidth = 100) {
@@ -773,7 +773,7 @@ var sheetCommonObj = {
         }
         return new getTipsCombo();
     },
-    getTreeNodeCellType: function (datas, row, parentMap) {// 2018-09-26  不用spreadjs默认的树结构,自定义控件
+    getTreeNodeCellType: function (datas, row, parentMap,treeCol) {// 2018-09-26  不用spreadjs默认的树结构,自定义控件
         var ns = GC.Spread.Sheets;
         let rectW = 10;
         let rectH = 10;
@@ -867,7 +867,8 @@ var sheetCommonObj = {
                     let parent = getParent(item.ParentID, datas);
                     if (!parent) return true;
                     let p_row = datas.indexOf(parent);
-                    let visible = !sheet.getCellType(p_row, 0).collapsed;
+                    treeCol = treeCol?treeCol:0;
+                    let visible = !sheet.getCellType(p_row, treeCol).collapsed;
                     if (visible == true) { //如果是显示的,则要再往父节点的父节点检查,只要有一个节点是隐藏的,则都是隐藏
                         return getVisible(parent);
                     } else {
@@ -883,7 +884,7 @@ var sheetCommonObj = {
         return new TreeNodeCellType()
 
         function getTreeLevel(item, data) {
-            if (item.ParentID) {
+            if (item.ParentID && item.ParentID!=-1) {
                 let pitem = _.find(data, { 'ID': item.ParentID });
                 return getTreeLevel(pitem, data) + 1;
             } else {

+ 8 - 5
public/web/tree_sheet/tree_sheet_helper.js

@@ -432,7 +432,7 @@ var TREE_SHEET_HELPER = {
                 sheetCommonObj.drowTriangle(ctx,x+w-12,y+h/2+2);
             }
             //定额库章节树问号
-            if(sheet.name() === 'stdRationLib_chapter' && this.enterCell && options.row === this.enterCell.row
+            if((sheet.name() === 'stdRationLib_chapter'|| sheet.name() === 'divide_stdRationLib_chapter') && this.enterCell && options.row === this.enterCell.row
                 && typeof rationLibObj !== 'undefined' && rationLibObj.hasExplanationRuleText(options.row)){
                 let centerX = Math.floor(x) + w - 20;
                 let centerY = Math.floor((y + (y + h)) / 2);
@@ -453,9 +453,9 @@ var TREE_SHEET_HELPER = {
         };
         TreeNodeCellType.prototype.processMouseDown = function (hitinfo) {
             //点击问号符,弹出说明、工程量计算规则窗口
-            if(hitinfo.sheet.name() === 'stdRationLib_chapter' && typeof rationLibObj !== 'undefined' && rationLibObj.hasExplanationRuleText(hitinfo.row)) {
+            if((hitinfo.sheet.name() === 'stdRationLib_chapter'|| sheet.name() === 'divide_stdRationLib_chapter') && typeof rationLibObj !== 'undefined' && rationLibObj.hasExplanationRuleText(hitinfo.row)) {
                 if(hitinfo.x < hitinfo.cellRect.x + hitinfo.cellRect.width && hitinfo.x > hitinfo.cellRect.x + hitinfo.cellRect.width - questionImgWidth) {
-                    rationLibObj.initQuestionModal(hitinfo.row);
+                    rationLibObj.initQuestionModal(hitinfo.row,sheet.name());
                 }
             }
             let offset = -1;
@@ -482,6 +482,9 @@ var TREE_SHEET_HELPER = {
                 else if(sheetName === 'stdRationLib_chapter'){
                     sessionStorage.setItem('stdRationLibExpState', rationLibObj.tree.getExpState(rationLibObj.tree.items));
                 }
+                else if(sheetName === 'divide_stdRationLib_chapter'){
+                  sessionStorage.setItem('divide_stdRationLibExpState', rationLibObj["divide_tree"].getExpState(rationLibObj["divide_tree"].items));
+                } 
                 else if(sheetName === 'stdBillsGuidance_bills'){
                     sessionStorage.setItem('stdBillsGuidanceExpState', billsGuidance.bills.tree.getExpState(billsGuidance.bills.tree.items));
                 }
@@ -501,7 +504,7 @@ var TREE_SHEET_HELPER = {
         TreeNodeCellType.prototype.processMouseEnter = function(hitinfo){
             if(hitinfo.sheet.name() === 'stdBillsGuidance_bills'){
                 TREE_SHEET_HELPER.delayShowTips(hitinfo,setting);
-            } else if(hitinfo.sheet.name() === 'stdRationLib_chapter'){
+            } else if(hitinfo.sheet.name() === 'stdRationLib_chapter'||hitinfo.sheet.name() === 'divide_stdRationLib_chapter'){
                 if(this.enterCell==null){
                     this.enterCell={
                         row:hitinfo.row,
@@ -524,7 +527,7 @@ var TREE_SHEET_HELPER = {
         };
         TreeNodeCellType.prototype.processMouseLeave = function (hitinfo) {
             TREE_SHEET_HELPER.hideTipsDiv();
-            if(hitinfo.sheet.name() === 'stdRationLib_chapter') {
+            if(hitinfo.sheet.name() === 'stdRationLib_chapter'||hitinfo.sheet.name() === 'divide_stdRationLib_chapter') {
                 this.enterCell = null;
                 hitinfo.sheet.invalidateLayout();
                 hitinfo.sheet.repaint();

+ 6 - 6
web/building_saas/css/main.css

@@ -287,7 +287,7 @@ height:300px
   background: #f7f7f9;
   padding:1px 0 0 2px
 }
-.bottom-content .nav-tabs .nav-link, .side-tabs .nav-tabs .nav-link {
+.bottom-content .nav-tabs .nav-link, .side-tabs .divide_side-tabs .nav-tabs .nav-link {
   border-radius: 0;
   padding: 0.2em 0.5em
 }
@@ -299,14 +299,14 @@ height:300px
   left:22px;
   z-index: 999
 }
-.side-tabs .nav-tabs .nav-item {
+.side-tabs .divide_side-tabs .nav-tabs .nav-item {
 z-index: 999
 }
-.side-tabs .nav-tabs {
+.side-tabs .divide_side-tabs .nav-tabs {
   border-bottom: none;
   margin-bottom: -1px
 }
-.side-tabs .nav-tabs .nav-link {
+.side-tabs .divide_side-tabs .nav-tabs .nav-link {
   border-radius: 0;
   padding: 0em 0.5em;
   line-height: 30px;
@@ -316,11 +316,11 @@ z-index: 999
   border:2px solid #ff6501;
   border-bottom: 1px solid #fff
 }
-.side-tabs .nav-tabs .nav-link.active {
+.side-tabs .divide_side-tabs .nav-tabs .nav-link.active {
   border-top: none;
   border-bottom:1px solid #fff
 }
-.side-tabs a.active, .sub-nav a.active {
+.side-tabs .divide_side-tabs a.active, .sub-nav a.active {
   background: #ccc
 }
 .poj-manage {

+ 3 - 11
web/building_saas/glj/html/project_glj.html

@@ -16,7 +16,6 @@
         </div>
         <a class="btn btn-sm ml-1" id="editUnitFile" href="/unitPrice/index/123" target="_"> 编辑单价文件</a>
     </div>
-
 </div>
 
 <div class="container-fluid">
@@ -26,18 +25,11 @@
                 <div class=" gl-side  filterType" id='filterType'>
                     <ul class="nav flex-column nav-side mt-2 mb-2"  style="margin-top: 0px!important;">
                         <li class="nav-item"><a class="nav-link active" href="#" id="ALL">所有工料机</a></li>
-
-                        <!--  <li class="nav-item"><a class="nav-link" href="javascript:void(0)" id="FBFX">分部分项人材机</a></li>
-                          <li class="nav-item"><a class="nav-link" href="javascript:void(0)" id="TECH">措施项目人材机</a></li>
-                          <li class="nav-item"><a class="nav-link" href="javascript:void(0)" id="JGCL">甲供材料</a></li>
-                          <li class="nav-item"><a class="nav-link" href="javascript:void(0)" id="ZGCL">暂估材料</a></li>
-                          <li class="nav-item"><a class="nav-link" href="javascript:void(0)" id="SCHZ">三材汇总</a></li>
-                          <li class="nav-item"><a class="nav-link" href="javascript:void(0)" id="ZYCL">主要材料</a></li>-->
                     </ul>
                 </div>
-                <div class="main-data-top left" id="project_glj_sheet"></div>
-            </div>
-            <div class="resize-y" id="projectGljResize"></div>
+            <div class="main-data-top left" id="project_glj_sheet"></div>
+         </div>
+         <div class="resize-y" id="projectGljResize"></div>
             <div class="bottom-content" id="projectGljBottom">
                 <ul class="nav nav-tabs d-flex" role="tablist">
                     <li class="nav-item">

+ 181 - 0
web/building_saas/main/html/divide.html

@@ -0,0 +1,181 @@
+<div class="toolsbar d-flex px-1 justify-content-between" id="divideToolsBar">
+  <div class="form-inline py-1">
+      <a class="btn btn-sm ml-1" href="#" id ="exec_divide_btn" >执行分摊</a>
+      <a class="btn btn-sm ml-1" href="#" id="cancel_divide_btn" > 取消分摊</a></label>
+      <a class="btn btn-sm ml-1" href="#" id="cancel_all_divide_btn" > 取消所有分摊</a></label>
+  </div>
+  <div class="divide_side-tabs form-inline">
+    <ul class="nav nav-tabs" role="tablist">
+      <li class="nav-item" id="li_divide_stdRationTab">
+        <a class="nav-link px-1 divide-nav-link" style="height: 110%;" href="javascript:void(0)" id="divide_stdRationTab"
+           relaPanel="#divide_de">定额库</a>
+    </li>
+    </ul>
+  </div>
+</div>
+
+<div class="container-fluid">
+  <div class="row" id="divideRow">
+      <div class="main-content col p-0 " id="divide_main" style="overflow: hidden">
+       <div class="top-content row"  id="divide_top" style="overflow: hidden;margin-left: 0px;margin-right: 0px;">
+          <div class="main-data-top ovf-hidden left " id="divide_main_sheet" style="padding: 0px;width: 59%;" > </div>
+          <div class="main-data-top left  full-h" id="divide_bills_div"  style="padding: 0px;width: 41% " >
+            <div class="resize-x ovf-hidden left full-h" id="divideMiddleResize" style="width: 5px;"></div>
+            <div class="ovf-hidden left full-h" id="divide_bills_sheet"></div>
+          </div>
+       </div>
+          <div class="bottom-content" id="divideBottom">
+            <div class="resize-y" id="divideResize"></div>
+              <ul class="nav nav-tabs d-flex" role="tablist">
+                  <li class="nav-item">
+                      <a class="nav-link active show" id="divide_glj_nav" data-toggle="tab" href="#divide_subItems" role="tab" aria-selected="true">工料机</a>
+                  </li>
+                  <li class="nav-item">
+                      <a class="nav-link " id="divede_calc_nav" data-toggle="tab" href="#divide_subItems" role="tab" aria-selected="false">计算程序</a>
+                  </li>
+              </ul>
+              <!-- Tab panes -->
+              <div class="tab-content"> 
+                  <div class="tab-pane active" id="divide_subItems" role="tabpanel">
+                      <div class="main-data-bottom" id="divide_subSpread" style="overflow:hidden;float: left;width: 100%;"></div>
+                      <div class="main-data-bottom ovf-hidden  col-auto p-0" id="divide_itemTextDiv" style="display: none">
+                        <div class="resize-x  ovf-hidden full-h" id="divide_rgResize" style="display: none"></div>
+                        <div class="item_spread  ovf-hidden " id="divide_gljSubDiv" style="width: 99%;">
+                            <div class="tab-content full-h">
+                                <div class="tab-pane full-h" id="divide_rnc-zm">
+                                    <div class=" ovf-hidden full-h" id = "divide_coeSpread">
+                                    </div>
+                                </div>
+                                <div class="tab-pane full-h" id="divide_rnc-cus">
+                                    <div class=" ovf-hidden full-h" id = "divide_cusSpread">
+                                    </div>
+                                </div>
+                                <div class="tab-pane full-h" id="divide_rnc-stable">
+                                    <div class=" ovf-hidden full-h" id="divide_stableSpread"></div>
+                                </div>
+                            </div>
+                        </div>
+                        <div class=" main-data-bottom ovf-hidden col-auto p-0" id="divide_gljItemTab" style="width: 30px">
+                            <div class="rn-nav d-flex align-items-start flex-column divide_gljSubTab">
+                                <div id="divide_zmhs_toogle">
+                                    <div class="d-flex align-items-start flex-column" data-toggle="tooltip" data-placement="left" title="" data-original-title="打开定额调整">
+                                        <span class="mt-3 ml-2 text-primary">定额调整</span>
+                                        <i class="fa fa-arrow-left mt-auto mb-3 text-primary ml-2"></i>
+                                    </div>
+                                </div>
+                                <div id="divide_zmhs_nav" style="display: none">
+                                    <ul class="nav nav-tabs">
+                                        <li class="nav-item" data-toggle="tooltip" data-placement="left" title="收起">
+                                            <a data-toggle="tab" href="#divide_rnc-close" role="tab" class="zmhs-link nav-link">收起<!--<i class="fa fa-arrow-right"></i>--></a>
+                                        </li>
+                                       
+                                        <li class="nav-item" data-toggle="tooltip" data-placement="left" title="附注条件"><a data-toggle="tab"  id="divide_hs-nav" href="#divide_rnc-zm" role="tab"class="divide_zmhs-link nav-link">换算</a></li>
+                                        <li class="nav-item" data-toggle="tooltip" data-placement="left" title="自定义系数"><a data-toggle="tab" href="#divide_rnc-cus" role="tab"class="divide_zmhs-link nav-link">系数</a></li>
+                                        <li class="nav-item" data-toggle="tooltip" data-placement="left" title="定额稳定土"><a data-toggle="tab" href="#divide_rnc-stable" role="tab" class="divide_zmhs-link nav-link">稳定土</a></li>
+                                    </ul>
+                                </div>
+                            </div>
+                        </div>
+                    </div>
+                  </div>
+              </div>
+          </div>
+      </div>
+      <div class="divide_side" style="display: inline-block" id="divide_side">
+      
+        <div class="tab-content" style="width: 100%; height: 100%; float: left">
+          <div class="resize-x" id="divideSideResize"></div>
+          <!--定额库-->
+          <div class="tab-pane" style=" float:left;" id="divide_de">
+            <div class="tools-bar-height-d container-fluid" id="divide_deToolsBar">
+                <div class="p-1 row">
+                    <select class="form-control form-control-sm col-6" id="divide_stdRationLibSelect">
+                    </select>
+                    <div class="input-group col-6">
+                        <input type="text" class="form-control form-control-sm" placeholder="搜索定额" value="" id="divide_rationSearchKeyword">
+                        <div class="input-group-append">
+                            <button class="btn btn-secondary btn-sm" type="button" id="divide_rationSearch"><i class="fa fa-search" aria-hidden="true"></i></button>
+                        </div>
+                    </div>
+                    <!--搜索结果窗体-->
+                    <div class="side-search-box col-12 p-0" id="divide_rationSearchResult" style="display: none;">
+                        <div class="d-flex justify-content-between">
+                            <div class="my-1">
+                                <span id="divide_rationSearchCount"></span>
+                                <button id="divide_curRationLib" type="button" class="btn btn-sm btn-secondary" style="margin-left: 15px;">本定额</button>
+                                <button id="divide_allRationLibs" type="button" class="btn btn-sm btn-light">全部定额</button>
+                            </div>
+                            <a title="关闭搜索" class="btn btn-link btn-sm" href="javascript:void(0)"><i class="fa fa-remove" aria-hidden="true"></i></a>
+                        </div>
+                        <div class="w-100 main-data-side-search"></div>
+                    </div>
+               
+                </div>
+            </div>
+            <div class="" id="divide_deTopDiv" style="overflow: hidden">
+                <div class="" id="divide_stdRationChapter"></div>
+            </div>
+            <div class="resize-y" id="divide_deResize" style="background: #F1F1F1"></div>
+            <div class="bottom-content" id="divide_deBottomDiv">
+                <div class="main-data-bottom" id="divide_stdSectionRations"></div>
+            </div>
+        </div>
+        </div>
+  </div>
+</div>
+
+<!--弹出 执行分摊-->
+<div class="modal fade" id="exec_divide_div" data-backdrop="static">
+  <div class="modal-dialog modal-lg" style="max-width: 1100px" role="document">
+      <div class="modal-content" style="width: 1100px">
+          <div class="modal-header">
+              <h5 class="modal-title">执行分摊</h5>
+              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
+                  <span aria-hidden="true">&times;</span>
+              </button>
+          </div>
+          <div class="modal-body">
+            <label id="exec_divide_label">混凝土拌合站建设费<br>分摊到:</label>
+              <div class="row" style="height:400px;border-top: 1px solid #ccc;"><!--sjs id设置在这个div-->
+                  <div style="overflow: hidden; width: 100%;" id="billSelectedSheet" > </div>
+              </div>
+              <div class="row" style="height:250px"><!--sjs id设置在这个div-->
+                  <div style="overflow: hidden; width: 100%" id="execBillSheet"></div>
+              </div>
+          </div>
+          <div class="modal-footer" style="justify-content: left;">
+            <div class=" col-10" style="overflow: hidden" id="install_setting">
+              <div >
+                  <!--<div class="setting_title">整个项目统一计取</div>-->
+                  <fieldset class="form-group"  style="border:1px solid #b3b3b3;padding: 15px">
+                      <legend class="legend" >分摊方式:</legend>
+                      <div class=" row" style="margin-left: 10px;">
+                        <div class=" col-6">
+                          <label class="form-check-label">
+                            <input class="form-check-input divide_type" name="divide_type" id="divide_by_bills" value="0" type="radio">
+                            按清单金额分摊
+                        </label>
+                        </div>
+                         <div class=" col-6">
+                          <label class="form-check-label">
+                              <input class="form-check-input divide_type" name="divide_type" id="divide_by_concrete" value="1" type="radio">
+                              按混凝土用量分摊
+                          </label>
+                        </div>
+                        <div class=" col-6">
+                          <label class="form-check-label">
+                            <input class="form-check-input divide_type" name="divide_type" id="divide_by_customer" value="2" type="radio">
+                            自定义分摊比例
+                        </label>
+                        </div>
+                      </div>
+                  </fieldset>
+              </div>
+          </div>
+              <button  class="btn btn-primary" id="divide_confirm" data-dismiss="modal">确定</button>
+              <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
+          </div>
+      </div>
+  </div>
+</div>
+</div>

+ 9 - 4
web/building_saas/main/html/main.html

@@ -65,6 +65,7 @@
                 <li class="nav-item"><a class="active" data-toggle="tab" href="#zaojiashu" id="tab_zaojiashu" role="tab">造价书</a></li>
                 <li class="nav-item"><a data-toggle="tab" href="#project_glj" id="tab_project_glj" data-name="tab_project_glj" role="tab">工料机汇总</a></li>
                 <li class="nav-item"><a data-toggle="tab" href="#fee_rates" id="tab_fee_rate" role="tab" >费率</a></li>
+                <li class="nav-item"><a data-toggle="tab" href="#divide" id="tab_divide" role="tab" style="display: none;">分摊</a></li>
                 <li class="nav-item"><a data-toggle="tab" href="#calc_program_manage" id="tab_calc_program_manage" role="tab" style="display:none">总计算程序</a></li>
                <!-- <li class="nav-item"><a data-toggle="tab" href="#tender_price" id="tab_tender_price" role="tab">调价</a></li>-->
                 <li class="nav-item"><a data-toggle="tab" href="#reports" role="tab" id="tab_report" onclick="rptTplObj.iniPage();">报表</a></li>
@@ -663,9 +664,12 @@
             <div class="tab-pane" id="fee_rates" role="tabpanel">
                 <%include ../../fee_rates/fee_rate.html %>
             </div>
-              <div class="tab-pane" id="tender_price" role="tabpanel">
-                  <%include tender_price.html %>
-              </div>
+            <div class="tab-pane" id="divide" role="tabpanel">
+              <%include divide.html %>
+            </div>
+            <div class="tab-pane" id="tender_price" role="tabpanel">
+                <%include tender_price.html %>
+            </div>
             <div class="tab-pane" id="calc_program_manage" role="tabpanel">
                 <%include calc_program_manage.html %>
             </div>
@@ -1903,7 +1907,7 @@
     <img src="/web/dest/css/img/engineering.png" id="eng_pic" style="display: none">
     <img src="/web/dest/css/img/tender.png" id="tender_pic" style="display: none">
 
-    <img src="/web/dest/css/img/blockLib.png" id="blockLib_pic" style="display: none">
+    <img src="/web/dest/css/img/blocklib.png" id="blockLib_pic" style="display: none">
     <img src="/web/dest/css/img/folder_open.png" id="folder_pic" style="display: none">
     <img src="/web/dest/css/img/tender.png" id="block_pic" style="display: none">
 
@@ -2048,6 +2052,7 @@
     <script type="text/javascript" src="/web/building_saas/complementary_ration_lib/js/main.js"></script>
     <script type="text/javascript" src="/web/building_saas/main/js/views/material_calc_view.js"></script>
     <script type="text/javascript" src="/web/building_saas/main/js/views/electrovalence_view.js"></script>
+    <script type="text/javascript" src="/web/building_saas/main/js/views/divide_view.js"></script>
     <script type="text/javascript" src="/public/web/storageUtil.js"></script>
     <script type="text/javascript" src="/web/building_saas/report/js/rpt_jspdf.js"></script>
 

+ 1 - 1
web/building_saas/main/js/main.js

@@ -17,13 +17,13 @@ $(function () {
         $(e.relatedTarget.hash).removeClass('active');
         $("#subItems").addClass('active');
         $(gljOprObj.activeTab).addClass('active');
+        subObj.initGljSubTab();
         autoFlashHeight();
         projectObj.refreshMainSpread();
         billsGuidance.refreshWorkBook();
         billsLibObj.refreshBillsSpread();
         billsLibObj.refreshBillsRelaSpread();
         rationLibObj.refreshSpread();
-        subObj.initGljSubTab();
         //autoFlashHeight 里已经包含了 refreshSubSpread();
     });
 

+ 16 - 0
web/building_saas/main/js/models/bills.js

@@ -550,6 +550,14 @@ var Bills = {
                 return false;
             }
         };
+        bills.prototype.isConstructionInstall = function (node) {//判读是否属于第一部分建筑安装工程费CONSTRUCTION_INSTALL_FEE
+          let rootNode = this.getRootNode(node);
+           if(this.flagEquals(rootNode,fixedFlag.CONSTRUCTION_INSTALL_FEE)){
+               return true;
+           }else {
+               return false;
+           }
+       };
         bills.prototype.isFXorBX=function (node) {//是分项或者补项
             if(node.sourceType == projectObj.project.Bills.getSourceType()){
                 return   node.data.type == billType.FX || node.data.type == billType.BX;
@@ -610,6 +618,14 @@ var Bills = {
                 return false;
             }
         };
+        bills.prototype.isBelongOneToSeven = function (node) {//判读是否属于措施项目部分
+          let rootNode = this.getRootNode(node);
+          if(isFlag(rootNode.data)&&rootNode.data.flagsIndex.fixed.flag==fixedFlag.ONE_SEVEN_BILLS){
+              return true;
+          }else {
+              return false;
+          }
+        };
         bills.prototype.hasFlags = function (node) {
             return isFlag(node.data);
         };

+ 210 - 182
web/building_saas/main/js/models/calc_program.js

@@ -1625,32 +1625,35 @@ class CalcProgram {
         };
     };
 
+    /*删掉多余的费用。例如:从其它计算方式(有很多费)切换到公式计算方式(只需要common费),多出来的费要删除。
+    reserveArr 值取自:情况①遍历treeNode的计算规则,取有绑定的字段名。这些字段名以外的fee是因旧计算多出来的,需要删除。没有绑定的
+    费用类别,不要同步到清单,也需要删除。*/
+    deleteUselessFees(treeNode, reserveArr){
+        treeNode.data.fees = _.filter(treeNode.data.fees, function (item) {
+            if(!reserveArr.includes(item.fieldName)){
+                delete treeNode.data.feesIndex[item.fieldName];
+                treeNode.changed = true;
+                return false;
+            }
+            return true;
+        });
+    };
+
+    // 不能直接删除该属性,否则无法冲掉库中已存储的值。下同。
+    deleteProperties (treeNode, propNamesArr){
+        for (let pn of propNamesArr){
+            if (treeNode.data[pn]){
+                treeNode.data[pn] = null;
+                treeNode.changed = true;
+            }
+        };
+    };
+
     // 只计算treeNode自身。changedArr: 外部传来的一个数组,专门存储发生变动的节点。
     innerCalc(treeNode, changedArr, tender){
         if (treeNode.sourceType === ModuleNames.ration_glj) return;             // 仅用作树节点显示的工料机不能参与计算。
 
-        // 不能直接删除该属性,否则无法冲掉库中已存储的值。下同。
-        function deleteProperties (treeNode, propNamesArr){
-            for (let pn of propNamesArr){
-                if (treeNode.data[pn]){
-                    treeNode.data[pn] = null;
-                    treeNode.changed = true;
-                }
-            };
-        };
-        /*删掉多余的费用。例如:从其它计算方式(有很多费)切换到公式计算方式(只需要common费),多出来的费要删除。
-        reserveArr 值取自:情况①遍历treeNode的计算规则,取有绑定的字段名。这些字段名以外的fee是因旧计算多出来的,需要删除。没有绑定的
-        费用类别,不要同步到清单,也需要删除。*/
-        function deleteUselessFees(treeNode, reserveArr){
-            treeNode.data.fees = _.filter(treeNode.data.fees, function (item) {
-                if(!reserveArr.includes(item.fieldName)){
-                    delete treeNode.data.feesIndex[item.fieldName];
-                    treeNode.changed = true;
-                    return false;
-                }
-                return true;
-            });
-        };
+
 
         let me = this;
         //设置定额工料机映射表
@@ -1662,85 +1665,17 @@ class CalcProgram {
         let nTQ = calcTools.uiNodeTenderQty(treeNode);
         treeNode.calcType = calcTools.getCalcType(treeNode);
 
-        // 父清单汇总子清单的费用类别、叶子清单汇总定额的费用类别
-        if (treeNode.calcType == treeNodeCalcType.ctGatherBillsFees || treeNode.calcType == treeNodeCalcType.ctGatherRationsFees){
-            treeNode.data.programID = null;
-            calcTools.initFees(treeNode);
-
-            let nodes = [];
-            if (treeNode.calcType == treeNodeCalcType.ctGatherRationsFees){
-                calcTools.getGLJList(treeNode, true);
-                nodes = me.project.Ration.getRationNodes(treeNode);
-            }
-            else nodes = treeNode.children;
-
-            let rst = [];
-            for (let ft of cpFeeTypes) {
-                let ftObj = {};
-                ftObj.fieldName = ft.type;
-                ftObj.name = ft.name;
-                let buf = 0, btf = 0, btuf = 0, bttf = 0;
-                let bq = nQ ? nQ : 1;
-                let btq = nTQ ? nTQ : 1;
-
-                if (treeNode.calcType == treeNodeCalcType.ctGatherBillsFees){
-                    for (let node of nodes) {
-                        if (node.data.feesIndex && node.data.feesIndex[ft.type]) {
-                            btf = (btf + parseFloatPlus(node.data.feesIndex[ft.type].totalFee)).toDecimal(decimalObj.process);
-                            bttf = (bttf + parseFloatPlus(node.data.feesIndex[ft.type].tenderTotalFee)).toDecimal(decimalObj.process);
-
-                            if (calcTools.isBudgetProject()){
-                                buf = (btf / bq).toDecimal(decimalObj.process);
-                                btuf = (bttf / bq).toDecimal(decimalObj.process);
-                            }
-                        };
-                    };
-                }
-                else if (treeNode.calcType == treeNodeCalcType.ctGatherRationsFees){
-                    let sum_rtf = 0, sum_rttf = 0;
-                    for (let node of nodes) {
-                        let ruf = 0, rtuf = 0, rtf = 0, rttf = 0;
-                        if (node.data.feesIndex && node.data.feesIndex[ft.type]) {
-                            ruf = parseFloatPlus(node.data.feesIndex[ft.type].unitFee).toDecimal(decimalObj.bills.unitPrice);
-                            rtuf = parseFloatPlus(node.data.feesIndex[ft.type].tenderUnitFee).toDecimal(decimalObj.bills.unitPrice);
-                            rtf = parseFloatPlus(node.data.feesIndex[ft.type].totalFee).toDecimal(decimalObj.bills.totalPrice);
-                            rttf = parseFloatPlus(node.data.feesIndex[ft.type].tenderTotalFee).toDecimal(decimalObj.bills.totalPrice);
-                        };
-
-                        sum_rtf = (sum_rtf + rtf).toDecimal(decimalObj.process);
-                        sum_rttf = (sum_rttf + rttf).toDecimal(decimalObj.process);
-                    };
-
-                    buf = (sum_rtf / bq).toDecimal(decimalObj.process);
-                    btuf = (sum_rttf / btq).toDecimal(decimalObj.process);
-                    btf = sum_rtf;
-                    bttf = sum_rttf;
-
-                    if (calcTools.isBillProject() && (ft.type == 'common' || ft.type == 'rationCommon')) {  // 招投标项目, 还要反算
-                        buf = buf.toDecimal(decimalObj.bills.unitPrice);
-                        btuf = btuf.toDecimal(decimalObj.bills.unitPrice);
-                        btf = (buf * nQ).toDecimal(decimalObj.bills.totalPrice);
-                        bttf = (btuf * nQ).toDecimal(decimalObj.bills.totalPrice);
-                    };
-                };
-
-                ftObj.unitFee = buf.toDecimal(decimalObj.bills.unitPrice);
-                ftObj.tenderUnitFee = btuf.toDecimal(decimalObj.bills.unitPrice);
-                ftObj.totalFee = btf.toDecimal(decimalObj.bills.totalPrice);
-                ftObj.tenderTotalFee = bttf.toDecimal(decimalObj.bills.totalPrice);
-
-
-                calcTools.checkFeeField(treeNode, ftObj);
-
-                rst.push(ftObj);
-            };
-            treeNode.data.calcTemplate = {"calcItems": rst};
-        }
+        // 父清单汇总子清单的费用类别
+        if (treeNode.calcType == treeNodeCalcType.ctGatherBillsFees)
+            me.innerCalcBill(treeNode, 2)
+        // 叶子清单汇总定额的费用类别
+        else if (treeNode.calcType == treeNodeCalcType.ctGatherRationsFees)
+            me.innerCalcBill(treeNode, 1)
         // 叶子清单:公式计算
         else if (treeNode.calcType == treeNodeCalcType.ctCalcBaseValue){
             delete treeNode.data.gljList;
-            deleteProperties(treeNode, ['programID']);
-            deleteUselessFees(treeNode, ['common', 'rationCommon']);
+            me.deleteProperties(treeNode, ['programID']);
+            me.deleteUselessFees(treeNode, ['common', 'rationCommon']);
             let tf = treeNode.data.calcBaseValue ? treeNode.data.calcBaseValue : 0;
             let ttf = treeNode.data.tenderCalcBaseValue ? treeNode.data.tenderCalcBaseValue : 0;
             let q = nQ ? nQ : 1;
@@ -1766,107 +1701,197 @@ class CalcProgram {
             // }
             treeNode.data.calcTemplate = {"calcItems": []};
         }
-        // 叶子清单:无定额、无公式计算(什么都没有时),手工修改单价或金额。
-        else if (treeNode.calcType == treeNodeCalcType.ctNull){
-            delete treeNode.data.gljList;
-            deleteProperties(treeNode, ['calcBase', 'calcBaseValue', 'tenderCalcBaseValue', 'programID']);
-            deleteUselessFees(treeNode, ['common', 'rationCommon']);
+        // 叶子清单:手工修改单价或金额。(无定额、无公式计算,什么都没有时)。
+        else if (treeNode.calcType == treeNodeCalcType.ctNull)
+            me.innerCalcBillCustom(treeNode)
+        // 定额:计算程序
+        else
+            me.innerCalcRation(treeNode, tender);
 
-            if (treeNode.data.feesIndex && treeNode.data.feesIndex.common){
-                let uf, tf;
-                let ftObj = {fieldName: 'common'};
+        // if (!calcTools.isTotalCostBill(treeNode))  // 已在上面的分支中计算过
+        //     calcTools.estimateFee(treeNode);
+        if (treeNode.changed && !changedArr.includes(treeNode)) changedArr.push(treeNode);
+    };
 
-                if (treeNode.data.calcFlag == treeNodeCalcFlag.customUnitPrice){    // 修改了清单单价:以单价为准,算金额
-                    uf = parseFloatPlus(treeNode.data.feesIndex.common.unitFee);
-                    tf = (uf * nQ).toDecimal(decimalObj.bills.totalPrice);
-                }
-                else if (treeNode.data.calcFlag == treeNodeCalcFlag.customTotalPrice){  // 修改了清单金额:以金额为准,算单价。修改了清单数量也一样
-                    tf = parseFloatPlus(treeNode.data.feesIndex.common.totalFee);
-                    uf = nQ ? (tf / nQ) : tf;        // 如果工程量为0或空,综合单价直接等于综合合价
-                    uf = uf.toDecimal(decimalObj.bills.unitPrice);
-                    if (calcTools.isBillProject()) {  // 招投标项目, 还要反算
-                        tf = (uf * nQ).toDecimal(decimalObj.bills.totalPrice);
-                    };
+    // 定额部分抽取出来,供分摊定额公用。
+    innerCalcRation(treeNode, tender = tenderTypes.ttCalc){
+        let me = this;
+        let fnArr = [];
+        calcTools.getGLJList(treeNode, true);
+
+        if (treeNode.calcType == treeNodeCalcType.ctRationCalcProgram) {
+            // 量价、工料机类型的定额要求"市场合价"
+            if (treeNode.data.type == rationType.volumePrice || treeNode.data.type == rationType.gljRation){
+                let u = treeNode.data.marketUnitFee ? treeNode.data.marketUnitFee : 0;
+                let q = calcTools.uiNodeQty(treeNode);
+                let t = (u * q).toDecimal(decimalObj.ration.totalPrice);
+                if (treeNode.data.marketTotalFee != t){
+                    treeNode.data.marketTotalFee = t;
+                    treeNode.changed = true;
+                } ;
+            };
+        };
+
+        let template = me.compiledTemplates[treeNode.data.programID];
+        treeNode.data.calcTemplate = template;
+
+        if (treeNode && template && template.hasCompiled) {//2018-08-27 空行的时候,取费专业为空,template也为空,加入template非空判断
+            let $CE = executeObj;
+            $CE.treeNode = treeNode;
+            $CE.template = template;
+
+            calcTools.initFees(treeNode);
+
+            for (let idx of template.compiledSeq) {
+                let calcItem = template.calcItems[idx];
+                $CE.tempCalcItem = calcItem;
+                let feeRate = 100;  // 100%
+                if (calcItem.feeRate != undefined)
+                    feeRate = parseFloat(calcItem.feeRate).toDecimal(decimalObj.feeRate);
+
+                let tf = (eval(calcItem.compiledExpr) * feeRate * 0.01).toDecimal(decimalObj.process);
+                calcItem.totalFee = tf.toDecimal(decimalObj.decimal('totalPrice', treeNode));
+                let nodeQ = calcTools.uiNodeQty(treeNode) ? calcTools.uiNodeQty(treeNode) : 1;
+                calcItem.unitFee = (tf / nodeQ).toDecimal(decimalObj.decimal('unitPrice', treeNode));
+
+                if (tender == tenderTypes.ttCalc) {
+                    let tExpr = analyzer.getCompiledTenderExpr(calcItem.compiledExpr);
+                    calcItem.tenderUnitFee = (eval(tExpr) * feeRate * 0.01).toDecimal(decimalObj.decimal('unitPrice', treeNode));
+                    calcItem.tenderTotalFee = (calcItem.tenderUnitFee * treeNode.data.tenderQuantity).toDecimal(decimalObj.decimal('totalPrice', treeNode));
+                };
+
+                if (calcItem.fieldName) {
+                    fnArr.push(calcItem.fieldName);
+                    calcTools.checkFeeField(treeNode, calcItem);
                 };
+            };
 
-                ftObj.unitFee = uf;
-                ftObj.totalFee = tf;
-                calcTools.checkFeeField(treeNode, ftObj);
+            if (tender == tenderTypes.ttReverseRation || tender == tenderTypes.ttReverseGLJ)
+                this.calcTenderReverse(treeNode, tender);
+            me.deleteUselessFees(treeNode, fnArr);
+        };
+    };
 
-                // 数量、金额时,同步定额建安费
-                if (calcTools.isInheritFrom(treeNode, 1)){
-                    let ftObj2 = {
-                        fieldName: 'rationCommon',
-                        unitFee: uf,
-                        totalFee: tf
+    // 清单部分抽取出来,供分摊清单公用。commonCalcType:1 叶子清单汇总定额的费用类别; 2 父清单汇总子清单的费用类别。3: 分摊:叶子清单汇总定额的费用类别。
+    innerCalcBill(treeNode, commonCalcType, tender = tenderTypes.ttCalc){
+        let me = this;
+        treeNode.data.programID = null;
+        calcTools.initFees(treeNode);
+        let nodes = [];
+
+        if (commonCalcType == 1){
+            calcTools.getGLJList(treeNode, true);
+            nodes = me.project.Ration.getRationNodes(treeNode);
+        }
+        else if (commonCalcType == 2)
+            nodes = treeNode.children
+        else if (commonCalcType == 3)
+            nodes = treeNode.children;
+
+        let rst = [];
+        for (let ft of cpFeeTypes) {
+            let ftObj = {};
+            ftObj.fieldName = ft.type;
+            ftObj.name = ft.name;
+            let buf = 0, btf = 0, btuf = 0, bttf = 0;
+
+            let nQ = calcTools.uiNodeQty(treeNode);
+            let nTQ = calcTools.uiNodeTenderQty(treeNode);
+            let bq = nQ ? nQ : 1;
+            let btq = nTQ ? nTQ : 1;
+
+            if (commonCalcType == 2){
+                for (let node of nodes) {
+                    if (node.data.feesIndex && node.data.feesIndex[ft.type]) {
+                        btf = (btf + parseFloatPlus(node.data.feesIndex[ft.type].totalFee)).toDecimal(decimalObj.process);
+                        bttf = (bttf + parseFloatPlus(node.data.feesIndex[ft.type].tenderTotalFee)).toDecimal(decimalObj.process);
+
+                        if (calcTools.isBudgetProject()){
+                            buf = (btf / bq).toDecimal(decimalObj.process);
+                            btuf = (bttf / bq).toDecimal(decimalObj.process);
+                        }
                     };
-                    calcTools.checkFeeField(treeNode, ftObj2);
                 };
             }
+            else if ((commonCalcType == 1) || (commonCalcType == 3)){
+                let sum_rtf = 0, sum_rttf = 0;
+                for (let node of nodes) {
+                    let ruf = 0, rtuf = 0, rtf = 0, rttf = 0;
+                    if (node.data.feesIndex && node.data.feesIndex[ft.type]) {
+                        ruf = parseFloatPlus(node.data.feesIndex[ft.type].unitFee).toDecimal(decimalObj.bills.unitPrice);
+                        rtuf = parseFloatPlus(node.data.feesIndex[ft.type].tenderUnitFee).toDecimal(decimalObj.bills.unitPrice);
+                        rtf = parseFloatPlus(node.data.feesIndex[ft.type].totalFee).toDecimal(decimalObj.bills.totalPrice);
+                        rttf = parseFloatPlus(node.data.feesIndex[ft.type].tenderTotalFee).toDecimal(decimalObj.bills.totalPrice);
+                    };
 
-            treeNode.data.calcTemplate = {"calcItems": []};
-        }
-        // 定额:计算程序
-        else{
-            let fnArr = [];
-            calcTools.getGLJList(treeNode, true);
+                    sum_rtf = (sum_rtf + rtf).toDecimal(decimalObj.process);
+                    sum_rttf = (sum_rttf + rttf).toDecimal(decimalObj.process);
+                };
 
-            if (treeNode.calcType == treeNodeCalcType.ctRationCalcProgram) {
-                // 量价、工料机类型的定额要求市场合价
-                if (treeNode.data.type == rationType.volumePrice || treeNode.data.type == rationType.gljRation){
-                    let muf = treeNode.data.marketUnitFee ? treeNode.data.marketUnitFee : 0;
-                    let mtf = (muf * nQ).toDecimal(decimalObj.ration.totalPrice);
-                    if (treeNode.data.marketTotalFee != mtf){
-                        treeNode.data.marketTotalFee = mtf;
-                        treeNode.changed = true;
-                    } ;
+                buf = (sum_rtf / bq).toDecimal(decimalObj.process);
+                btuf = (sum_rttf / btq).toDecimal(decimalObj.process);
+                btf = sum_rtf;
+                bttf = sum_rttf;
+
+                if (calcTools.isBillProject() && (ft.type == 'common' || ft.type == 'rationCommon')) {  // 招投标项目, 还要反算
+                    buf = buf.toDecimal(decimalObj.bills.unitPrice);
+                    btuf = btuf.toDecimal(decimalObj.bills.unitPrice);
+                    btf = (buf * nQ).toDecimal(decimalObj.bills.totalPrice);
+                    bttf = (btuf * nQ).toDecimal(decimalObj.bills.totalPrice);
                 };
             };
-            // 2018-08-27   zhang  插入空定额的时候,取费专业也为空
-           // if (treeNode.data.programID == undefined) treeNode.data.programID = projectObj.project.projectInfo.property.engineering;
-            let template = me.compiledTemplates[treeNode.data.programID];
-            treeNode.data.calcTemplate = template;
-
-            if (treeNode && template && template.hasCompiled) {//2018-08-27 空行的时候,取费专业为空,template也为空,加入template非空判断
-                let $CE = executeObj;
-                $CE.treeNode = treeNode;
-                $CE.template = template;
-
-                calcTools.initFees(treeNode);
-
-                for (let idx of template.compiledSeq) {
-                    let calcItem = template.calcItems[idx];
-                    $CE.tempCalcItem = calcItem;
-                    let feeRate = 100;  // 100%
-                    if (calcItem.feeRate != undefined)
-                        feeRate = parseFloat(calcItem.feeRate).toDecimal(decimalObj.feeRate);
-                    // console.log(`[${calcItem.ID}]: ${calcItem.compiledExpr}`);   // for test.
-                    let tf = (eval(calcItem.compiledExpr) * feeRate * 0.01).toDecimal(decimalObj.process);
-                    calcItem.totalFee = tf.toDecimal(decimalObj.decimal('totalPrice', treeNode));
-                    let nodeQ = calcTools.uiNodeQty(treeNode) ? calcTools.uiNodeQty(treeNode) : 1;
-                    calcItem.unitFee = (tf / nodeQ).toDecimal(decimalObj.decimal('unitPrice', treeNode));
-
-                    if (tender == tenderTypes.ttCalc) {
-                        let tExpr = analyzer.getCompiledTenderExpr(calcItem.compiledExpr);
-                        calcItem.tenderUnitFee = (eval(tExpr) * feeRate * 0.01).toDecimal(decimalObj.decimal('unitPrice', treeNode));
-                        calcItem.tenderTotalFee = (calcItem.tenderUnitFee * treeNode.data.tenderQuantity).toDecimal(decimalObj.decimal('totalPrice', treeNode));
-                    };
 
-                    if (calcItem.fieldName) {
-                        fnArr.push(calcItem.fieldName);
-                        calcTools.checkFeeField(treeNode, calcItem);
-                    };
+            ftObj.unitFee = buf.toDecimal(decimalObj.bills.unitPrice);
+            ftObj.tenderUnitFee = btuf.toDecimal(decimalObj.bills.unitPrice);
+            ftObj.totalFee = btf.toDecimal(decimalObj.bills.totalPrice);
+            ftObj.tenderTotalFee = bttf.toDecimal(decimalObj.bills.totalPrice);
+
+            calcTools.checkFeeField(treeNode, ftObj);
+
+            rst.push(ftObj);
+        };
+        treeNode.data.calcTemplate = {"calcItems": rst};
+    };
+
+    innerCalcBillCustom(treeNode){
+        let me = this;
+        delete treeNode.data.gljList;
+        me.deleteProperties(treeNode, ['calcBase', 'calcBaseValue', 'tenderCalcBaseValue', 'programID']);
+        me.deleteUselessFees(treeNode, ['common', 'rationCommon']);
+
+        if (treeNode.data.feesIndex && treeNode.data.feesIndex.common){
+            let uf, tf;
+            let ftObj = {fieldName: 'common'};
+            let nQ = calcTools.uiNodeQty(treeNode);
+            if (treeNode.data.calcFlag == treeNodeCalcFlag.customUnitPrice){    // 修改了清单单价:以单价为准,算金额
+                uf = parseFloatPlus(treeNode.data.feesIndex.common.unitFee);
+                tf = (uf * nQ).toDecimal(decimalObj.bills.totalPrice);
+            }
+            else if (treeNode.data.calcFlag == treeNodeCalcFlag.customTotalPrice){  // 修改了清单金额:以金额为准,算单价。修改了清单数量也一样
+                tf = parseFloatPlus(treeNode.data.feesIndex.common.totalFee);
+                uf = nQ ? (tf / nQ) : tf;        // 如果工程量为0或空,综合单价直接等于综合合价
+                uf = uf.toDecimal(decimalObj.bills.unitPrice);
+                if (calcTools.isBillProject()) {  // 招投标项目, 还要反算
+                    tf = (uf * nQ).toDecimal(decimalObj.bills.totalPrice);
                 };
+            };
+
+            ftObj.unitFee = uf;
+            ftObj.totalFee = tf;
+            calcTools.checkFeeField(treeNode, ftObj);
 
-                if (tender == tenderTypes.ttReverseRation || tender == tenderTypes.ttReverseGLJ)
-                    this.calcTenderReverse(treeNode, tender);
-                deleteUselessFees(treeNode, fnArr);
+            // 数量、金额时,同步定额建安费
+            if (calcTools.isInheritFrom(treeNode, 1)){
+                let ftObj2 = {
+                    fieldName: 'rationCommon',
+                    unitFee: uf,
+                    totalFee: tf
+                };
+                calcTools.checkFeeField(treeNode, ftObj2);
             };
-        };
+        }
 
-        // if (!calcTools.isTotalCostBill(treeNode))  // 已在上面的分支中计算过
-        //     calcTools.estimateFee(treeNode);
-        if (treeNode.changed && !changedArr.includes(treeNode)) changedArr.push(treeNode);
+        treeNode.data.calcTemplate = {"calcItems": []};
     };
 
     // 存储、刷新零散的多个结点。
@@ -2180,6 +2205,9 @@ class CalcProgram {
         }
     };
     getGljArrByRation(ration){
+        if(ration.itemType=="定额"){//分摊定额
+            return divideObj.getRationGLJDatas(ration);
+        }
         if (ration.type == rationType.gljRation){
             let glj = JSON.parse(JSON.stringify(ration));
             glj.type = glj.subType;

+ 2 - 1
web/building_saas/main/js/models/main_consts.js

@@ -17,7 +17,8 @@ const ModuleNames = {
     labour_coe: 'labour_coe',
     calc_program: 'calc_program',
     installation_fee:'installation_fee',
-    projectInfo: 'project_info'
+    projectInfo: 'project_info',
+    divide_setting:'divide_setting'
 };
 
 let gljType = gljUtil.gljType;

+ 102 - 23
web/building_saas/main/js/models/project.js

@@ -99,6 +99,7 @@ var PROJECT = {
             this.labourCoe = new LabourCoe(this);
             this.calcProgram = new CalcProgram(this);
             this.calcBase = calcBase;
+            this.divide_setting = new DivideSetting(this);
 
             // this.masterField = {ration: 'billsItemID', volumePrice: 'billsItemID'};
             this.masterField = {ration: 'billsItemID'};
@@ -403,30 +404,108 @@ var PROJECT = {
                 }
             })
         };
-
+        project.prototype.syncUpdateNodesAndRefresh =async function (datas) {
+          let me = this;
+          return new Promise(function (resolve, reject) {
+              me.updateNodes(datas,function (result) {
+                  let nodes = me.updateNodesCache(result);
+                  projectObj.mainController.refreshTreeNode(nodes);
+                  resolve(nodes);
+              });
+          });
+      };
         project.prototype.updateNodesCache =function (datas) {
-            let refreshNode = [];
-            for(let d of datas){
-                let temObj = null;
-                if(d.type == ModuleNames.bills || d.type == ModuleNames.ration){//如果是树节点类型,直接取树节点更新
-                    let temNode = this.mainTree.getNodeByID(d.data.ID);
-                    if(temNode){
-                        temObj = temNode.data;
-                        refreshNode.push(temNode);
-                    }
-                }else {//其它类型,更新datas
-                    temObj = _.find(this[d.type].datas,{"ID":d.data.ID});
-                }
-                if(temObj){
-                    for(let key in d.data){
-                        if(key == 'ID' || key == 'id'){
-                            continue;
-                        }
-                        this.setValue(temObj,key,d.data[key])
-                    }
-                }
-            }
-            return refreshNode;
+          let refreshNode = [];
+          let reclacQuantity = false;
+          let deleteNode=[],addNodeDatas=[];
+          for(let d of datas){
+              let temObj = null;
+              if(d.type == ModuleNames.bills || d.type == ModuleNames.ration){//如果是树节点类型,直接取树节点更新
+                  if(d.action =="add"){
+                      if(d.type == ModuleNames.ration) this.Ration.datas.push(d.data);
+                      reclacQuantity = true;
+                      addNodeDatas.push(d);
+                  }else {
+                      let temNode = this.mainTree.getNodeByID(d.data.ID);
+                      if(temNode){
+                          if(d.action =="delete"){
+                              if(d.type == ModuleNames.ration){
+                                  _.remove(this.Ration.datas,{'ID':d.data.ID});
+                                  this.Ration.deleteSubListOfRation({ID:d.data.ID});
+                                  reclacQuantity = true;
+                              }
+                              deleteNode.push(temNode);//对于删除节点,统一不加入refreshNode中,由外部加入,避免重复
+                          }else {
+                              temObj = temNode.data;
+                              if(gljUtil.isDef(d.data.quantity))reclacQuantity = true;
+                              refreshNode.push(temNode);
+                          }
+                      }
+                  }
+              }else if(d.type == ModuleNames.project){
+                  temObj = this;
+              }else if (d.type == ModuleNames.ration_glj && d.action == "add"){
+                  this[d.type].datas.push(d.data);
+                  if(d.projectGLJ) this.projectGLJ.loadNewProjectGLJToCache(d.projectGLJ);
+              } else {//其它类型,更新datas
+                  temObj = _.find(this[d.type].datas,{"ID":d.data.ID});
+              }
+              if(temObj){
+                  for(let key in d.data){
+                      if(key == 'ID' || key == 'id'){
+                          continue;
+                      }
+                      this.setValue(temObj,key,d.data[key])
+                  }
+              }
+          }
+
+          //对树节点的操作并删除、添加清单、删除添加定额、删除对应的定额工料机缓存
+          TREE_SHEET_HELPER.massOperationSheet(projectObj.mainController.sheet, function () {
+              deleteTreeNodes(deleteNode);
+              addNewNodes(addNodeDatas,refreshNode);
+          });
+
+
+          if(reclacQuantity) this.projectGLJ.calcQuantity();
+          return refreshNode;
+
+
+
+
+          function deleteTreeNodes(deleteNodes) {
+              let controller = projectObj.mainController, project = projectObj.project;
+              let Bill = project.Bills, Ration = project.Ration;
+              for(let rd of deleteNodes){
+                  controller.sheet.deleteRows(rd.serialNo(),1);
+                  controller.tree.delete(rd);
+                  if(rd.sourceType == Bill.getSourceType()) Bill.tree.delete(rd.source);
+              }
+          }
+          function addNewNodes(newDatas,refreshNode) {
+              let controller = projectObj.mainController;
+              let Bill = projectObj.project.Bills;
+              let newAddNode = [];
+              for(let nr of newDatas){
+                  let nextID = -1;
+                  let preNode = projectObj.project.mainTree.getNodeByID(nr.preSiblingID);
+                  if(preNode) nextID = preNode.getNextSiblingID();
+                  let newNode = projectObj.project.mainTree.insert(nr.parentID, nextID, nr.data.ID);
+                  if(nr.type == ModuleNames.bills){
+                      let newSource = Bill.tree.insertByData(nr.data, nr.ParentID, nextID, true);
+                      newNode.source = newSource;
+                  }else {
+                      newNode.source = nr.data;
+                  }
+                  newNode.sourceType = nr.type;
+                  newNode.data = nr.data;
+                  controller.sheet.addRows(newNode.serialNo(), 1);
+                  controller.sheet.showRow(newNode.serialNo(), GC.Spread.Sheets.VerticalPosition.center);
+                  newAddNode.push(newNode);
+                  refreshNode.push(newNode);
+              }
+              TREE_SHEET_HELPER.refreshTreeNodeData(controller.setting, controller.sheet, newAddNode, false);
+          }
         };
         project.prototype.setValue=function (obj,key,value) {
             let keyArray = key.split('.');

+ 15 - 3
web/building_saas/main/js/models/project_glj.js

@@ -956,7 +956,7 @@ ProjectGLJ.prototype.calcEachFreightOrPrice = function (temp,type,priceMap,needU
           let exp = expList.length == 0?`${temp.otherFee}x${temp.weightCoe}`:`((${expList.join("+")})+${temp.otherFee})x${temp.weightCoe}`
           let ndoc = {};
           if(temp.unitFreight != sum) ndoc['unitFreight'] = sum;
-          if(temp.exp != exp) ndoc['exp'] = exp;
+          ndoc['exp'] = exp;
           if(temp.heightFee != heightFee) ndoc['heightFee'] = heightFee;
           if(!_.isEmpty(ndoc)) return {ID:temp.ID,doc:ndoc};
         }
@@ -980,7 +980,7 @@ ProjectGLJ.prototype.calcEachFreightOrPrice = function (temp,type,priceMap,needU
             let rationQuantity = scMathUtil.roundForObj(ration.quantity,getDecimal("ration.quantity"));
             for(let g of gljs){
                 gljOprObj.setGLJPrice(g,pMap[gljUtil.getIndex(g)]);
-                if(priceMap && priceMap[g.projectGLJID]) g.marketPrice = scMathUtil.roundForObj(priceMap[g.projectGLJID]);
+                if(priceMap && priceMap[g.projectGLJID]) g.marketPrice = scMathUtil.roundForObj(priceMap[g.projectGLJID],getDecimal("glj.unitPrice"));
                 let quantity = scMathUtil.roundForObj(g.quantity,getDecimal("glj.quantity"));
                 let t = scMathUtil.roundForObj(quantity * g.marketPrice * rationQuantity,processDecimal);//市场价
                 let r_price = gljUtil.getAssUsedPrice(g);//浙江定额时特殊处理,这里取市场价
@@ -1151,6 +1151,7 @@ ProjectGLJ.prototype.updatePrice = function (recode, updateField, newval,from,cb
             let nodes = me.getImpactRationNodes(gljs);//取到因为改变工料机价格而受影响的定额
             projectObj.project.calcProgram.calcNodesAndSave(nodes);//触发计算程序
             if(materialGljList.length==0)projectGljObject.onUnitFileChange(result);
+            divideObj.calcDivideAfterGLJUpdate(gljs);
             if(cb){
                 cb(gljs);
             }
@@ -1759,4 +1760,15 @@ ProjectGLJ.prototype.loadNewProjectGLJToCache = function (data,tIDMap) {//把新
     this.datas.gljList.push(data);
     IDMap[data.id] = data;
     return data;
-};
+};
+
+class DivideSetting {
+  constructor (project) {
+      this.project = project;
+      this.datas = [];
+      project.registerModule(ModuleNames.divide_setting, this);
+  };
+  loadData (datas) {
+      this.datas = datas;
+  };
+}

+ 10 - 1
web/building_saas/main/js/models/ration_coe.js

@@ -140,7 +140,13 @@ var ration_coe = {
                 delete:[],
                 replace:[]
             };
-            let gljList = project.ration_glj.getGLJListByRationID(record.rationID);
+            let gljList = [];
+            if($('#divide_subSpread').is(':visible')){
+              gljList = divideObj.getGLJListByRationID(record.rationID);
+            }else{
+              gljList = project.ration_glj.getGLJListByRationID(record.rationID);
+            }
+            
             if(gljUtil.isDef(record.option_codes)&&record.option_codes!=""){ //说明编辑的是下拉选择编号的类型
                 //勾选而不是下拉的情况下,默认选择下拉框中的第一个
                 if(newval == 1 && (!gljUtil.isDef(doc.select_code)||doc.select_code == '')){
@@ -193,6 +199,9 @@ var ration_coe = {
                         updateData.replace.push(r_tem);
                     }
                 }
+                if($('#divide_subSpread').is(':visible')){
+                  return divideObj.updateCoeAdjust(updateData);
+                }
                 $.bootstrapLoading.start();
                 CommonAjax.post("/ration/updateCoeAdjust",updateData,function (result) {
                     $.bootstrapLoading.end();

文件差异内容过多而无法显示
+ 1614 - 0
web/building_saas/main/js/views/divide_view.js


+ 0 - 2
web/building_saas/main/js/views/electrovalence_view.js

@@ -43,8 +43,6 @@ let electrovalenceObj = {
         this.sheet.bind(GC.Spread.Sheets.Events.SelectionChanged,this.onElectrovalenceSelectionChange);
         this.sheet.bind(GC.Spread.Sheets.Events.ValueChanged, this.onElectrovalenceValueChange);
         this.sheet.bind(GC.Spread.Sheets.Events.EditStarting,this.onElectrovalenceEditStarting);
-    /*
-        ;*/
         this.sheet.name('electrovalence_sheet');
         if(projectReadOnly){
             disableSpread(this.spread);

+ 4 - 4
web/building_saas/main/js/views/glj_col.js

@@ -8,9 +8,9 @@ let gljCol = {
             {headerName: "名称", headerWidth: 160, dataCode: "name", dataType: "String",cellType:'tipsCell'},
             {headerName: "规格", headerWidth: 120, dataCode: "specs", dataType: "String", hAlign: "left",cellType:'tipsCell'},
             {headerName: "单位", headerWidth: 45, dataCode: "unit", dataType: "String", hAlign: "center"},
-            {headerName: "预算价", headerWidth: 65, dataCode: "marketPrice", dataType: "Number", hAlign: "right"},//, decimalField: "glj.unitPrice"
-            {headerName: "调整价", headerWidth: 65, dataCode: "adjustPrice", dataType: "Number", hAlign: "right"},//, decimalField: "glj.unitPrice"1
-            {headerName: "自定消耗", headerWidth: 65, dataCode: "customQuantity", dataType: "Number", hAlign: "right", decimalField: "glj.quantity"},
+            {headerName: "预算价", headerWidth: 65, dataCode: "marketPrice", dataType: "Number", validator:"number",hAlign: "right"},//, decimalField: "glj.unitPrice"
+            {headerName: "调整价", headerWidth: 65, dataCode: "adjustPrice", dataType: "Number",validator:"number", hAlign: "right"},//, decimalField: "glj.unitPrice"1
+            {headerName: "自定消耗", headerWidth: 65, dataCode: "customQuantity", dataType: "Number",validator:"number", hAlign: "right", decimalField: "glj.quantity"},
             {headerName: "消耗量", headerWidth: 65, dataCode: "quantity", dataType: "Number", hAlign: "right", decimalField: "glj.quantity"},
             {headerName: "定额价", headerWidth: 65, dataCode: "basePrice", dataType: "Number", hAlign: "right"},//, decimalField: "glj.unitPrice"
             {headerName: "定额消耗", headerWidth: 65, dataCode: "rationItemQuantity", dataType: "Number", hAlign: "right", decimalField: "glj.quantity"},   // dataType: "Number", formatter: "0.00"
@@ -18,7 +18,7 @@ let gljCol = {
             //{headerName: "暂估", headerWidth: 45, dataCode: "isEstimate", dataType: "String", hAlign: "center", vAlign: "center", cellType: "checkBox"}
         ],
         view: {
-            lockColumns: [ "adjustPrice", "rationItemQuantity", "quantity", "totalQuantity", "isEstimate"],//这里以后改成dataCode好一点
+            lockColumns: [ "adjustPrice", "rationItemQuantity", "quantity", "totalQuantity", "isEstimate"],
             rowHeaderWidth:25
         },
         getStyle:function (data) {

+ 5 - 2
web/building_saas/main/js/views/glj_view.js

@@ -632,6 +632,8 @@ var gljOprObj = {
         return codeMap;
     },
     initRationTree: function (init,codeMap) {
+        this.sheet.suspendPaint();
+        this.sheet.suspendEvent();
         this.sheet.setRowCount(this.sheetData.length >30?this.sheetData.length:30);
         for (var i = 0; i < this.sheetData.length; i++) {
             let options = this.getCodeOptions(this.sheetData[i],codeMap);
@@ -643,6 +645,8 @@ var gljOprObj = {
                 }
             }
         }
+        this.sheet.resumeEvent();
+        this.sheet.resumePaint(); 
     },
     getCodeOptions:function (recode,codeMap) {
         let options = [];
@@ -944,8 +948,7 @@ var gljOprObj = {
                 var decimal = getDecimal("glj.unitPrice");
                 newval = number_util.checkNumberValue(value, decimal);
             }
-        }
-        else {
+        }else {
             if (value != null) {
                 projectObj.project.projectGLJ.updatePropertyFromMainSpread(node, fieldName, value,editingText);
                 return;

+ 3 - 2
web/building_saas/main/js/views/material_calc_view.js

@@ -56,7 +56,7 @@ materialCalcObj = {
         },
          getText:{
           forExp:function (item) {
-             return _.isEmpty(item.exp)?materialCalcObj.getFreightEXP(item):item.exp;
+             return item.exp&&item.exp!=""?item.exp:materialCalcObj.getFreightEXP(item);
           }
       }
 
@@ -366,6 +366,7 @@ materialCalcObj = {
                     if(freigth.conveyance == "自办运输") args.cancel = true;
                 }
                 if(dataCode == "unitFreight"){
+                    if(freigth.conveyance == "自办运输") args.cancel = true;
                     if(freigth.rations && freigth.rations.length > 0) args.cancel = true;
                     if(gljUtil.isDef(freigth.materialType) && freigth.materialType != "") args.cancel = true;//当材料类型有值时,说明是内蒙古计算,运费是通过运距算出来的,不能编辑
                 }
@@ -466,7 +467,7 @@ materialCalcObj = {
       //(单位运价×(1+运距增加率%)+装卸费单价×装卸次数+其它费用)×单位毛重×加权系数
       if(item.conveyance == "自办运输"){
         let t = projectObj.project.projectGLJ.calcEachFreightOrPrice(item,"freight",{},needUpdate);
-        return t.doc.exp;
+        if(t) return t.doc.exp;
       }
 
       //(单位运价×km运距×(1+运距增加率%)+装卸费单价×装卸次数+其它费用)×单位毛重×加权系数

+ 22 - 17
web/building_saas/main/js/views/project_glj_view.js

@@ -662,6 +662,7 @@ projectGljObject={
 
     },
     showProjectGljData:function () {
+        let me = this;
         this.projectGljSpread.setActiveSheetIndex(0);
         let sel = this.projectGljSheet.getSelections()[0];
         let oldData = sel.row<this.projectGljSheetData.length?this.projectGljSheetData[sel.row]:"";
@@ -674,10 +675,12 @@ projectGljObject={
         }
         this.projectGljSheetData = projectGljSheetData;
         this.projectGljSheet.setRowCount(this.projectGljSheetData.length);
-        sheetCommonObj.showData(this.projectGljSheet, this.projectGljSetting,this.projectGljSheetData);
-        //this.projectGljSheet.setRowCount(this.projectGljSheetData.length);
-        sel.row = oldData?_.findIndex(this.projectGljSheetData,{'id':oldData.id}):0;
-        this.projectGljSheet.setSelection(sel.row==-1?0:sel.row,sel.col,sel.rowCount,sel.colCount);
+        sheetCommonObj.showData(this.projectGljSheet, this.projectGljSetting,this.projectGljSheetData,null,function(){
+          //this.projectGljSheet.setRowCount(this.projectGljSheetData.length);
+          sel.row = oldData?_.findIndex(me.projectGljSheetData,{'id':oldData.id}):0;
+          me.projectGljSheet.setSelection(sel.row==-1?0:sel.row,sel.col,sel.rowCount,sel.colCount);
+        });
+        
     },
     showMaterialTreeData:function () {
         this.projectGljSpread.setActiveSheetIndex(1);
@@ -692,22 +695,24 @@ projectGljObject={
         this.materialTreeSheet.setSelection(sel.row==-1?0:sel.row,sel.col,sel.rowCount,sel.colCount);
         this.materialTreeController.setTreeSelected(this.materialTree.items[sel.row==-1?0:sel.row]);
     },
-    refreshDataSheet:function () {
+    refreshDataSheet:function (refresh) {//refresh = true 的时候不用更新表头信息
         let me = projectGljObject;
         if(!me.projectGljSpread)  return;
-        let quantityCol = _.findIndex(me.projectGljSetting.header,function (header) {
+        if(!refresh){
+          let quantityCol = _.findIndex(me.projectGljSetting.header,function (header) {
             return header.dataCode ==  'quantity'|| header.dataCode == 'techQuantity' || header.dataCode =='subdivisionQuantity';
-        });
-        if(me.displayType == filterType.FBFX){//分部分项人材机,将“总消耗量”替换显示为“分部分项总消耗量”。
-            me.projectGljSetting.header[quantityCol].dataCode = 'subdivisionQuantity';
-            if(me.projectGljSheet) me.projectGljSheet.setValue(0, quantityCol, "分部分项总消耗量", GC.Spread.Sheets.SheetArea.colHeader);
-        }else if(me.displayType == filterType.TECH) {//措施项目人材机,将“总消耗量”替换显示为“措施项目总消耗量”。
-            me.projectGljSetting.header[quantityCol].dataCode = 'techQuantity';
-            if(me.projectGljSheet) me.projectGljSheet.setValue(0, quantityCol, "措施项目总消耗量", GC.Spread.Sheets.SheetArea.colHeader);
-        }else {
-            me.projectGljSetting.header[quantityCol].dataCode = 'quantity';
-            if(me.projectGljSheet) me.projectGljSheet.setValue(0, quantityCol, "总消耗量", GC.Spread.Sheets.SheetArea.colHeader);
-        }
+          });
+          if(me.displayType == filterType.FBFX){//分部分项人材机,将“总消耗量”替换显示为“分部分项总消耗量”。
+              me.projectGljSetting.header[quantityCol].dataCode = 'subdivisionQuantity';
+              if(me.projectGljSheet) me.projectGljSheet.setValue(0, quantityCol, "分部分项总消耗量", GC.Spread.Sheets.SheetArea.colHeader);
+          }else if(me.displayType == filterType.TECH) {//措施项目人材机,将“总消耗量”替换显示为“措施项目总消耗量”。
+              me.projectGljSetting.header[quantityCol].dataCode = 'techQuantity';
+              if(me.projectGljSheet) me.projectGljSheet.setValue(0, quantityCol, "措施项目总消耗量", GC.Spread.Sheets.SheetArea.colHeader);
+          }else {
+              me.projectGljSetting.header[quantityCol].dataCode = 'quantity';
+              if(me.projectGljSheet) me.projectGljSheet.setValue(0, quantityCol, "总消耗量", GC.Spread.Sheets.SheetArea.colHeader);
+          }
+        } 
         if(me.displayType == filterType.SCHZ){//三材汇总树节点
             me.showMaterialTreeData();
         }else {

+ 2 - 1
web/building_saas/main/js/views/project_info.js

@@ -67,9 +67,10 @@ var projectInfoObj = {
     },
     showProjectInfo: function (data) {
         if (data) {
-            //如果是工程量清单项目,则显示导入功能
+            //如果是工程量清单项目,则显示导入、分摊功能
             if (data.property.valuationType === 'ration') {
                 $('#importSpan').show();
+                $('#tab_divide').show();
             }
 
             //打开预算项目时,右侧“清单规则”显示为“项目表”,打开工程量清单项目时,右侧“清单规则”显示为“清单范本”。

+ 1 - 0
web/building_saas/main/js/views/project_view.js

@@ -442,6 +442,7 @@ var projectObj = {
             project.ration_glj.updateFromMainSpread(value,node,fieldName);
         }
         else if(calcTools.isGljRation(node)){
+            if(fieldName === 'feesIndex.common.unitFee') fieldName = 'marketUnitFee';
             gljOprObj.updateRationTypeGLJ(value,node,fieldName,editingText);
         }
         else if(fieldName === 'remark'){

+ 5 - 0
web/building_saas/main/js/views/side_tools.js

@@ -9,6 +9,7 @@ $(window).resize(function() {
     billsGuidance.setColumnWidthByRate(billsGuidance.elfItem.workBook, $('#zy').width(), billsGuidance.elfItem.headers);
     billsGuidance.refreshWorkBook();
     rationLibObj.refreshSpread();
+    loadDivideHeight();
     //BillsElf.setColumnWidthByRate();
     loadSideToolsHeight();
     //刷新主界面与各库中间的拖动条宽度:始终保持为一个宽度(在小窗口打开一个库,再放大窗口后,该拖动条宽度会变大)
@@ -189,6 +190,10 @@ function loadSideToolsHeight() {
         SlideResize.loadMultiVerticalHeight(blockLibMulti.module, blockLibMulti.eles, blockLibMulti.totalHeight, function () {
             blockLibObj.refreshSpread();
         });
+    }else if($('#divide_de').is(':visible')){
+      SlideResize.loadVerticalHeight(dividRationLibResizeEles.eleObj.module, dividRationLibResizeEles.eleObj, dividRationLibResizeEles.limit, function () {
+         //rationLibObj.refreshSpread();
+      });
     }
 }
 

+ 64 - 44
web/building_saas/main/js/views/std_ration_lib.js

@@ -17,20 +17,23 @@ var rationLibObj = {
     refreshSettingForHint: function () {
         TREE_SHEET_HELPER.initSetting($('#stdSectionRations')[0], rationLibObj.sectionRationsSetting);
     },
-    checkSpread: function () {
-        if (!this.rationChapterSpread) {
-            this.rationChapterSpread = SheetDataHelper.createNewSpread($('#stdRationChapter')[0]);
-            this.rationChapterSpread.getSheet(0).options.rowHeaderVisible = false;
-            sheetCommonObj.spreadDefaultStyle(this.rationChapterSpread);
-            this.rationChapterSpread.getSheet(0).name('stdRationLib_chapter');
-            this.rationChapterSpread.bind(GC.Spread.Sheets.Events.CellDoubleClick, this.onChapterSpreadCellDoubleClick);
-        }
-        if (!this.sectionRationsSpread) {
-            this.sectionRationsSpread = SheetDataHelper.createNewSpread($('#stdSectionRations')[0]);
-            this.sectionRationsSpread.getSheet(0).setColumnWidth(0, 1, GC.Spread.Sheets.SheetArea.rowHeader);
-            sheetCommonObj.spreadDefaultStyle(this.sectionRationsSpread);
+    checkSpread: function (tfrom) {
+        let from = $('#divide_de').is(':visible')||tfrom?"divide_":"";
+        if (!this[from+'rationChapterSpread']) {
+             this[from+'rationChapterSpread'] = SheetDataHelper.createNewSpread($(`#${from}stdRationChapter`)[0]);
+             let rationChapterSpread = this[from+'rationChapterSpread'];
+            rationChapterSpread.getSheet(0).options.rowHeaderVisible = false;
+            sheetCommonObj.spreadDefaultStyle(rationChapterSpread);
+            rationChapterSpread.getSheet(0).name(from+'stdRationLib_chapter');
+            rationChapterSpread.bind(GC.Spread.Sheets.Events.CellDoubleClick, this.onChapterSpreadCellDoubleClick);
+        }
+        if (!this[from+'sectionRationsSpread']) {
+            this[from+'sectionRationsSpread'] = SheetDataHelper.createNewSpread($(`#${from}stdSectionRations`)[0]);
+            let sectionRationsSpread = this[from+'sectionRationsSpread'];
+            sectionRationsSpread.getSheet(0).setColumnWidth(0, 1, GC.Spread.Sheets.SheetArea.rowHeader);
+            sheetCommonObj.spreadDefaultStyle(sectionRationsSpread);
             if (!projectReadOnly) {
-                this.sectionRationsSpread.bind(GC.Spread.Sheets.Events.CellDoubleClick, this.onRationSpreadCellDoubleClick);
+                sectionRationsSpread.bind(GC.Spread.Sheets.Events.CellDoubleClick, this.onRationSpreadCellDoubleClick);
             }
             this.refreshSettingForHint();
         }
@@ -47,15 +50,19 @@ var rationLibObj = {
         }
     },
     loadStdRationLibs: function () {
-        let select = $('#stdRationLibSelect');
+        let from = $('#divide_de').is(':visible')?"divide_":"";
+        let select = $(`#${from}stdRationLibSelect`);
         select.empty();
         let ration_lib = projectObj.project.projectInfo.engineeringInfo.ration_lib;
-        ration_lib.push({
+        if(rationLibObj.inited != true){
+          ration_lib.push({
             isDefault: false,
             id: rationLibObj.compleRationLibId,
             name: '我的补充定额'
-        });
-        let selectedRationLib = sessionStorage.getItem('stdRationLib');
+          });
+        }
+     
+        let selectedRationLib = sessionStorage.getItem(`${from}stdRationLib`);
         ration_lib.forEach(function (data) {
             let option = $('<option>').val(data.id).text(data.name);
             if(selectedRationLib){
@@ -74,13 +81,14 @@ var rationLibObj = {
             rationLibObj.loadStdRation(select.val());
         }
     },
-    initQuestionModal: function(row) {
-        let node = rationLibObj.tree.items[row];
+    initQuestionModal: function(row,sheetName) {
+        let pre = $('#divide_de').is(':visible')?"divide_":"";
+        let node = rationLibObj[pre+'tree'].items[row];
         while (node && !node.data.explanation){
             node = node.parent;
         }
         let explanation = node && node.data.explanation ? node.data.explanation : '无内容';
-        node = rationLibObj.tree.items[row];
+        node = rationLibObj[pre+'tree'].items[row];
         $('#questionContent1').html(explanation);
         while (node && !node.data.ruleText){
             node = node.parent;
@@ -90,8 +98,9 @@ var rationLibObj = {
         $('#questionContent2').html(ruleText);
         $('#questionModal').modal('show');
     },
-    hasExplanationRuleText: function(row) {
-        let node = rationLibObj.tree.items[row];
+    hasExplanationRuleText: function(row) { 
+        let pre = $('#divide_de').is(':visible')?"divide_":"";
+        let node = rationLibObj[pre+'tree'].items[row];
         if (!node) {
             return false;
         }
@@ -103,20 +112,22 @@ var rationLibObj = {
         }
         return false;
     },
-    loadStdRation: function (rationLibID) {
+    loadStdRation: function (rationLibID){
+        let from = $('#divide_de').is(':visible')?"divide_":"";
         $.bootstrapLoading.start();
         rationLibObj.curLibType = rationLibID === rationLibObj.compleRationLibId ? rationLibObj.libType.complementary : rationLibObj.libType.std;
         var that = this;
+        let rationChapterSpread = this[from+'rationChapterSpread'];
         var showRationChapterTree = function (datas) {
             var rationChapterTree = idTree.createNew({id: 'ID', pid: 'ParentID', nid: 'NextSiblingID', rootId: -1, autoUpdate: false});
-            that.tree = rationChapterTree;
-            var rationChapterTreeController = TREE_SHEET_CONTROLLER.createNew(rationChapterTree, that.rationChapterSpread.getActiveSheet(), that.rationChapterTreeSetting);
-            sheetCommonObj.setColumnWidthByRate($('#stdRationChapter').width() - 40, that.rationChapterSpread, that.rationChapterTreeSetting.cols);
+            that[from+'tree'] = rationChapterTree;
+            var rationChapterTreeController = TREE_SHEET_CONTROLLER.createNew(rationChapterTree, rationChapterSpread.getActiveSheet(), that.rationChapterTreeSetting);
+            sheetCommonObj.setColumnWidthByRate($(`#${from}stdRationChapter`).width() - 40, rationChapterSpread, that.rationChapterTreeSetting.cols);
             rationChapterTree.loadDatas(datas);
             //读取展开收起状态
-            let currentExpState = sessionStorage.getItem('stdRationLibExpState');
+            let currentExpState = sessionStorage.getItem(from+'stdRationLibExpState');
             if(currentExpState){
-                that.tree.setExpandedByState(that.tree.items, currentExpState);
+                that[from+'tree'].setExpandedByState(that[from+'tree'].items, currentExpState);
             }
             else {
                 //展开至第一层
@@ -124,18 +135,19 @@ var rationLibObj = {
                     root.setExpanded(false);
                     that.tree.setRootExpanded(root.children, false);
                 } */
-                that.tree.setRootExpanded(that.tree.roots, false);
+                that[from+'tree'].setRootExpanded(that[from+'tree'].roots, false);
             }
             rationChapterTreeController.showTreeData();
-            rationLibObj.rationChapterSpread.getSheet(0).options.rowHeaderVisible = true;
+            rationChapterSpread.getSheet(0).options.rowHeaderVisible = true;
             rationChapterTreeController.bind(TREE_SHEET_CONTROLLER.eventName.treeSelectedChanged, function (node) {
-                rationLibObj.loadSectionRations(node && node.children.length === 0 ? node.getID() : null);
+              rationLibObj.loadSectionRations(node && node.children.length === 0 ? node.getID() : null);
             });
-
+            
+          
             if (rationChapterTree.firstNode() && rationChapterTree.firstNode().length === 0) {
                 rationLibObj.loadSectionRations(rationChapterTree.firstNode().getID());
             } else {
-                rationLibObj.loadSectionRations();
+                rationLibObj.loadSectionRations(null);
             };
         };
         //type: 0-补充库 1-标准库
@@ -152,16 +164,17 @@ var rationLibObj = {
     },
     //双击隐藏显示
     onChapterSpreadCellDoubleClick: function (sender, args) {
+        let from = $('#divide_de').is(':visible')?"divide_":"";
         let me = rationLibObj;
-        let node = me.tree.items[args.row];
+        let node = me[from+'tree'].items[args.row];
         if (!node || node.children.length === 0)
             return;
         node.setExpanded(!node.expanded);
-        sessionStorage.setItem('stdRationLibExpState', me.tree.getExpState(me.tree.items));
+        sessionStorage.setItem(from+'stdRationLibExpState', me[from+'tree'].getExpState(me[from+'tree'].items));
         TREE_SHEET_HELPER.massOperationSheet(args.sheet, function () {
             let iCount = node.posterityCount(), i, child;
             for (i = 0; i < iCount; i++) {
-                child = me.tree.items[args.row + i + 1];
+                child = me[from+'tree'].items[args.row + i + 1];
                 args.sheet.setRowVisible(args.row + i + 1, child.visible, args.sheetArea);
             }
             args.sheet.invalidateLayout();
@@ -182,13 +195,14 @@ var rationLibObj = {
     },
     loadSectionRations: function (sectionID) {
         let me = this;
+        let from = $('#divide_de').is(':visible')?"divide_":"";
         var showDatas = function (datas, setting) {
-            let rationSheet = rationLibObj.sectionRationsSpread.getActiveSheet();
+            let rationSheet = rationLibObj[from+"sectionRationsSpread"].getActiveSheet();
             /*TREE_SHEET_HELPER.massOperationSheet(rationSheet, function () {
                 rationSheet.setColumnWidth(0, 25, GC.Spread.Sheets.SheetArea.rowHeader);
             });*/
-            SheetDataHelper.loadSheetHeader(setting, rationLibObj.sectionRationsSpread.getActiveSheet());
-            SheetDataHelper.loadSheetData(setting, rationLibObj.sectionRationsSpread.getActiveSheet(), datas);
+            SheetDataHelper.loadSheetHeader(setting, rationLibObj[from+"sectionRationsSpread"].getActiveSheet());
+            SheetDataHelper.loadSheetData(setting, rationLibObj[from+"sectionRationsSpread"].getActiveSheet(), datas);
             rationLibObj.setTagForHint(rationSheet, datas);
         };
         //定额名称的处理:
@@ -233,7 +247,7 @@ var rationLibObj = {
         }
         if (sectionID) {
             CommonAjax.post('/complementaryRation/api/getRationGljItemsBySection', {user_Id: userID, sectionId: sectionID, type: me.curLibType}, function (datas) {
-                let chapterSheet = me.rationChapterSpread.getActiveSheet();
+                let chapterSheet = me[from+'rationChapterSpread'].getActiveSheet();
                 let sectionName = chapterSheet.getText(chapterSheet.getActiveRowIndex(), chapterSheet.getActiveColumnIndex());
                 simplifyName(sectionName, datas);
                 showDatas(datas, rationLibObj.sectionRationsSetting);
@@ -249,16 +263,21 @@ var rationLibObj = {
         }
     },
     onRationSpreadCellDoubleClick: function (sender, args) {
-        var select = $('#stdRationLibSelect'), rationCode = args.sheet.getText(args.row, 0);
+        let pre = $('#divide_de').is(':visible')?"divide_":"";
+        var select = $(`#${pre}stdRationLibSelect`), rationCode = args.sheet.getText(args.row, 0);
         if (rationCode !== '') {
             let query = {userID: userID, rationRepId: select.val(), code: rationCode};
             //搜索结果全部定额中双击添加定额、有可能同名不同库,更新查询的库ID
             if (rationLibObj.resultCache && rationLibObj.resultCache[args.row]) {
                 query.rationRepId = rationLibObj.resultCache[args.row].type === 'std' ? rationLibObj.resultCache[args.row].rationRepId : rationLibObj.compleRationLibId;
             }
-            projectObj.project.Ration.addNewRation(query,rationType.ration, function () {
+            if(pre =="divide_"){
+              divideObj.addDivideRation(select.val(),rationCode);
+            }else{
+              projectObj.project.Ration.addNewRation(query,rationType.ration, function () {
                 projectObj.setActiveCell('quantity', true);
             });
+            }
         }
     },
     //滚动条到底部加载
@@ -499,8 +518,9 @@ var rationLibObj = {
             alert('当前项目无定额库,请添加定额库。');
             return null;
         }
-        if($('#stdRationLibSelect').val()){
-            return parseInt($('#stdRationLibSelect').val());
+        let pre = $('#divide_de').is(':visible')?"divide_":"";
+        if($(`#${pre}stdRationLibSelect`).val()){
+            return parseInt($(`#${pre}stdRationLibSelect`).val());
         }else {
             return projectObj.project.projectInfo.engineeringInfo.ration_lib[0].id;
         }

+ 148 - 105
web/building_saas/main/js/views/zmhs_view.js

@@ -90,33 +90,37 @@ let zmhs_obj = {
         this.initAssSpread();
     },
     initCoeSpread:function () {
-        if(zmhs_obj.coeSpread == null){
-            this.coeSpread = SheetDataHelper.createNewSpread($("#coeSpread")[0]);
-            sheetCommonObj.spreadDefaultStyle(this.coeSpread);
-            this.coeSheet = this.coeSpread.getSheet(0);
-            sheetCommonObj.initSheet(this.coeSheet, this.coeSetting, 30);
-            this.coeSheet.name('ration_coe');
-            //this.coeSheet.bind(GC.Spread.Sheets.Events.CellClick, this.onCoeCellClick);  配合自定义系数使用,现在自定义系数不在这显示了
-            this.coeSpread.bind(GC.Spread.Sheets.Events.ButtonClicked, this.onButtonClick);
-            this.coeSheet.bind(GC.Spread.Sheets.Events.ValueChanged,this.onCoeValueChange);
-            this.coeSheet.bind(GC.Spread.Sheets.Events.RangeChanged, this.onCoeRangeChanged);
-            this.coeSheet.bind(GC.Spread.Sheets.Events.SelectionChanged, function (e,args) {
-                args.sheet.repaint();
-            });
-            SheetDataHelper.protectdSheet(this.coeSheet);
-        }
+      let pre = $('#divide_subSpread').is(':visible')?"divide_":"";
+      if(zmhs_obj[pre+"coeSpread"] == null){
+          this[pre+"coeSpread"] = SheetDataHelper.createNewSpread($("#"+pre+"coeSpread")[0]);
+          sheetCommonObj.spreadDefaultStyle(this[pre+"coeSpread"]);
+          this[pre+"coeSheet"] = this[pre+"coeSpread"].getSheet(0);
+          sheetCommonObj.initSheet(this[pre+"coeSheet"], this.coeSetting, 30);
+          this[pre+"coeSheet"].name(pre+'ration_coe');
+          //this.coeSheet.bind(GC.Spread.Sheets.Events.CellClick, this.onCoeCellClick);  配合自定义系数使用,现在自定义系数不在这显示了
+          this[pre+"coeSpread"].bind(GC.Spread.Sheets.Events.ButtonClicked, this.onButtonClick);
+          this[pre+"coeSheet"].bind(GC.Spread.Sheets.Events.ValueChanged,this.onCoeValueChange);
+          this[pre+"coeSheet"].bind(GC.Spread.Sheets.Events.RangeChanged, this.onCoeRangeChanged);
+          this[pre+"coeSheet"].bind(GC.Spread.Sheets.Events.SelectionChanged, function (e,args) {
+              args.sheet.repaint();
+          });
+          SheetDataHelper.protectdSheet(this[pre+"coeSheet"]);
+      }else{
+        zmhs_obj[pre+"coeSpread"].refresh();
+      }
     },
     initCusSpread:function () {
-        if(zmhs_obj.cusSpread == null){
-            this.cusSpread = SheetDataHelper.createNewSpread($("#cusSpread")[0]);
-            sheetCommonObj.spreadDefaultStyle(this.cusSpread);
-            this.cusSheet = this.cusSpread.getSheet(0);
-            sheetCommonObj.initSheet(this.cusSheet, this.cusSetting, 30);
-            this.cusSheet.name('ration_cus');
-            this.cusSheet.bind(GC.Spread.Sheets.Events.ValueChanged,this.onCusValueChange);
-            this.cusSheet.bind(GC.Spread.Sheets.Events.RangeChanged, this.onCusRangeChanged);
-            SheetDataHelper.protectdSheet(this.cusSheet);
-        }
+      let pre = $('#divide_subSpread').is(':visible')?"divide_":"";
+      if(zmhs_obj[pre+'cusSpread'] == null){
+          this[pre+'cusSpread'] = SheetDataHelper.createNewSpread($("#"+pre+"cusSpread")[0]);
+          sheetCommonObj.spreadDefaultStyle(this[pre+'cusSpread']);
+          this[pre+"cusSheet"] = this[pre+'cusSpread'].getSheet(0);
+          sheetCommonObj.initSheet(this[pre+"cusSheet"], this.cusSetting, 30);
+          this[pre+"cusSheet"].name(pre+'ration_cus');
+          this[pre+"cusSheet"].bind(GC.Spread.Sheets.Events.ValueChanged,this.onCusValueChange);
+          this[pre+"cusSheet"].bind(GC.Spread.Sheets.Events.RangeChanged, this.onCusRangeChanged);
+          SheetDataHelper.protectdSheet(this[pre+"cusSheet"]);
+      }
     },
     initAssSpread:function () {
         if(zmhs_obj.assSheet == null){
@@ -131,94 +135,110 @@ let zmhs_obj = {
         }
     },
     initStableSpread:function () {
-        if(zmhs_obj.stableSpread == null){
-            this.stableSpread = SheetDataHelper.createNewSpread($("#stableSpread")[0]);
-            sheetCommonObj.spreadDefaultStyle(this.stableSpread);
-            this.stableSheet = this.stableSpread.getSheet(0);
-            sheetCommonObj.initSheet(this.stableSheet, this.stableSetting, 30);
-            this.stableSheet.name('ration_stable');
-            this.stableSheet.bind(GC.Spread.Sheets.Events.ValueChanged,this.onStableValueChange);
-            this.stableSheet.bind(GC.Spread.Sheets.Events.RangeChanged, this.onStableRangeChanged);
-            SheetDataHelper.protectdSheet(this.stableSheet);
-        }
+      let pre = $('#divide_subSpread').is(':visible')?"divide_":"";
+      if(zmhs_obj[pre+'stableSpread'] == null){
+          this[pre+'stableSpread'] = SheetDataHelper.createNewSpread($("#"+pre+"stableSpread")[0]);
+          sheetCommonObj.spreadDefaultStyle(this[pre+'stableSpread'] );
+          this[pre+"stableSheet"] = this[pre+'stableSpread'].getSheet(0);
+          sheetCommonObj.initSheet(this[pre+"stableSheet"], this.stableSetting, 30);
+          this[pre+"stableSheet"].name(pre+'ration_stable');
+          this[pre+"stableSheet"].bind(GC.Spread.Sheets.Events.ValueChanged,this.onStableValueChange);
+          this[pre+"stableSheet"].bind(GC.Spread.Sheets.Events.RangeChanged, this.onStableRangeChanged);
+          SheetDataHelper.protectdSheet(this[pre+"stableSheet"]);
+      }
     },
     showCoeData:function (node) {
-        let preSelections = this.coeSheet.getSelections();
-        let selected = node?node:projectObj.project.mainTree.selected;
+        let pre = $('#divide_subSpread').is(':visible')?"divide_":"";
+        let preSelections = this[pre+'coeSheet'].getSelections();
         let ration_coe = projectObj.project.ration_coe;
         let coeList = [];
-        this.coeSheet.suspendPaint();
-        this.coeSheet.suspendEvent();
-        if(selected&&selected.sourceType == "ration"){
-            let ration = selected.data;
-            let assList = this.getAssList(node); //2019-01-23 新需求,将辅助定额合并到一个表显示  -- 20191206
-            // this.assFirstIndex = coeList.length;//没改前这里要记录辅助定额的起始下标,现在调整顺序后,默认就是0
-            coeList = ration_coe.getCoeByRationID(ration.ID);
-            _.remove(coeList,{"coeID":-1})//2018-12-24 新需求,把自定义乘系数分离出来,这里排除自定义乘系数行
-            coeList = assList.concat(coeList)
-        }
-        this.coeSheet.setRowCount(0);
-        sheetCommonObj.showData(this.coeSheet, this.coeSetting,coeList);
+        let coeSheet = this[pre+'coeSheet'];
+        coeSheet.suspendPaint();
+        coeSheet.suspendEvent();
+        if(pre == "divide_"){//来自分摊
+          coeList = divideObj.getCoeList();
+        }else{
+          let selected = node?node:projectObj.project.mainTree.selected;
+          if(selected&&selected.sourceType == "ration"){
+              let ration = selected.data;
+              let assList = this.getAssList(node); //2019-01-23 新需求,将辅助定额合并到一个表显示  -- 20191206
+              // this.assFirstIndex = coeList.length;//没改前这里要记录辅助定额的起始下标,现在调整顺序后,默认就是0
+              coeList = ration_coe.getCoeByRationID(ration.ID);
+              _.remove(coeList,{"coeID":-1})//2018-12-24 新需求,把自定义乘系数分离出来,这里排除自定义乘系数行
+              coeList = assList.concat(coeList)
+          }
+        }
+    
+        coeSheet.setRowCount(0);
+        sheetCommonObj.showData(coeSheet, this.coeSetting,coeList);
         if (coeList.length > 0) {
             for(let i =0;i<coeList.length;i++ ){
                 if(gljUtil.isDef(coeList[i].option_codes)&&coeList[i].option_codes!=""){
                     this.getComboBoxForCodes(coeList[i],i);//设置可选类型的下拉框
                     //  sheet.setValue(row, col, val, ch);
                 } else if(coeList[i].assistCode && coeList[i].assistCode !=''){//是辅助定额列
-                    this.coeSheet.getCell(i, 2, GC.Spread.Sheets.SheetArea.viewport).locked(false);
+                    coeSheet.getCell(i, 2, GC.Spread.Sheets.SheetArea.viewport).locked(false);
                 } else if(coeList[i].coeID == -1){ //自定义系数列
-                    this.coeSheet.getCell(i, 1, GC.Spread.Sheets.SheetArea.viewport).locked(false);
-                    this.coeSheet.setCellType(i, 1, sheetCommonObj.getCustomerCoeCellType(this.generateHtmlString,this.bindCusEditorValue,this.updateCusCoeAfterEditor), GC.Spread.Sheets.SheetArea.viewport);
+                    coeSheet.getCell(i, 1, GC.Spread.Sheets.SheetArea.viewport).locked(false);
+                    coeSheet.setCellType(i, 1, sheetCommonObj.getCustomerCoeCellType(this.generateHtmlString,this.bindCusEditorValue,this.updateCusCoeAfterEditor), GC.Spread.Sheets.SheetArea.viewport);
                 }
             }
         }
-        this.coeSheetData = coeList;
+        this[pre+'coeSheetData'] = coeList;
         if(projectReadOnly){
             disableSpread(zmhs_obj.coeSpread);
         }
         if(preSelections){//定位光标到之前的位置
-            this.coeSheet.setSelection(preSelections[0].row,preSelections[0].col,preSelections[0].rowCount,preSelections[0].colCount);
+            coeSheet.setSelection(preSelections[0].row,preSelections[0].col,preSelections[0].rowCount,preSelections[0].colCount);
         }
-        this.coeSheet.resumeEvent();
-        this.coeSheet.resumePaint();
+        coeSheet.resumeEvent();
+        coeSheet.resumePaint();
     },
     showCusData:function (node) {
-        let selected = node?node:projectObj.project.mainTree.selected;
+        let pre = $('#divide_subSpread').is(':visible')?"divide_":"";
         let ration_coe = projectObj.project.ration_coe;
         let cusList = [];
-        if(selected&&selected.sourceType == "ration"){
-            let ration = selected.data;
-            let coeList = ration_coe.getCoeByRationID(ration.ID);
-            this.cusSheetData = _.find(coeList,{"coeID":-1});
-            if(this.cusSheetData) cusList = this.cusSheetData.coes;
-        }
-        sheetCommonObj.showData(this.cusSheet, this.cusSetting,cusList);
-        this.cusSheet.getRange(cusList.length,-1,this.cusSheet.getRowCount()-cusList.length, -1, GC.Spread.Sheets.SheetArea.viewport).locked(true);
+        if(pre == "divide_"){
+          cusList = divideObj.getCusList();
+        }else{
+          let selected = node?node:projectObj.project.mainTree.selected;
+          if(selected&&selected.sourceType == "ration"){
+              let ration = selected.data;
+              let coeList = ration_coe.getCoeByRationID(ration.ID);
+              this.cusSheetData = _.find(coeList,{"coeID":-1});
+              if(this.cusSheetData) cusList = this.cusSheetData.coes;
+          }
+        }
+        this[pre+'cusSheet'].setRowCount(0);
+        sheetCommonObj.showData(this[pre+'cusSheet'], this.cusSetting,cusList);
+        this[pre+'cusSheet'].getRange(cusList.length,-1,this[pre+'cusSheet'].getRowCount()-cusList.length, -1, GC.Spread.Sheets.SheetArea.viewport).locked(true);
         if(projectReadOnly){
-            disableSpread(zmhs_obj.cusSpread);
+            disableSpread(zmhs_obj[pre+'cusSpread']);
         }
     },
     showStableData: function (node) {
         // 过滤出定额配合比不为0的数据
-        const stableList = gljOprObj.sheetData.filter(glj => !glj.isMixRatio && glj.rationProportion);
-        this.stableSheetData = stableList;
-        sheetCommonObj.showData(this.stableSheet, this.stableSetting, stableList);
+        let pre = $('#divide_subSpread').is(':visible')?"divide_":"";
+        const stableList = pre == 'divide_' ?divideObj.getStableList():gljOprObj.sheetData.filter(glj => !glj.isMixRatio && glj.rationProportion);
+        this[pre+'stableSheetData'] = stableList;
+        sheetCommonObj.showData(this[pre+"stableSheet"], this.stableSetting, stableList);
         const proportionCol = this.stableSetting.header.findIndex(item => item.dataCode === 'adjustProportion');
-        this.stableSheet.getRange(0, proportionCol, stableList.length, 1, GC.Spread.Sheets.SheetArea.viewport).locked(false);
-        this.stableSheet.getRange(stableList.length, -1, this.stableSheet.getRowCount() - stableList.length, -1, GC.Spread.Sheets.SheetArea.viewport).locked(true);
+        this[pre+"stableSheet"].getRange(0, proportionCol, stableList.length, 1, GC.Spread.Sheets.SheetArea.viewport).locked(false);
+        this[pre+"stableSheet"].getRange(stableList.length, -1, this[pre+"stableSheet"].getRowCount() - stableList.length, -1, GC.Spread.Sheets.SheetArea.viewport).locked(true);
         if(projectReadOnly){
-            disableSpread(zmhs_obj.cusSpread);
+            disableSpread(zmhs_obj[pre+'stableSpread']);
         }
     },
     getComboBoxForCodes:function (coe,i) {
-        this.coeSheet.getCell(i, 1, GC.Spread.Sheets.SheetArea.viewport).locked(false);
+        let pre = $('#divide_subSpread').is(':visible')?"divide_":"";
+        this[pre+'coeSheet'].getCell(i, 1, GC.Spread.Sheets.SheetArea.viewport).locked(false);
         let options = coe.option_list; //coe.option_codes.split("|");
         let combo =  new GC.Spread.Sheets.CellTypes.ComboBox();//sheetCommonObj.getDynamicCombo(true);  2019-4-1 这里用普通的下拉框,一直显示
-        let buttonRow =  this.coeSheet.getViewportBottomRow(1);
+        let buttonRow =  this[pre+'coeSheet'].getViewportBottomRow(1);
         combo.editorValueType(GC.Spread.Sheets.CellTypes.EditorValueType.value);
         combo.items(options).maxDropDownItems(buttonRow - i -1 < 3 ?3:buttonRow - i -1 );//itemHeight(options.length).
-        this.coeSheet.setCellType(i, 1, combo, GC.Spread.Sheets.SheetArea.viewport);
-        this.coeSheet.setValue(i, 1, coe.select_code);
+        this[pre+'coeSheet'].setCellType(i, 1, combo, GC.Spread.Sheets.SheetArea.viewport);
+        this[pre+'coeSheet'].setValue(i, 1, coe.select_code);
 
     },
     showAssData:function (node) {
@@ -292,21 +312,21 @@ let zmhs_obj = {
         }
         return calcInstall;
     },
-
-
     refresh:function () {
-        $('#coeSpread').is(':visible')&&this.coeSpread?this.coeSpread.refresh():'';
-        $('#coeSpread').is(':visible')&&this.coeSpread?this.showDatas():'';//这里combobox下拉框要重新加载一下
-        $('#cusSpread').is(':visible')&&this.cusSpread?this.cusSpread.refresh():'';
-        $('#assSpread').is(':visible')&&this.assSpread?this.assSpread.refresh():'';
-        $('#stableSpread').is(':visible')&&this.stableSpread?this.stableSpread.refresh():'';
+        zmhs_obj.initSpread();
+        let pre = $('#divide_subSpread').is(':visible')?"divide_":"";
+        $('#'+pre+'coeSpread').is(':visible')&&this[pre+'coeSpread']?this[pre+'coeSpread'].refresh():'';
+        $('#'+pre+'coeSpread').is(':visible')&&this[pre+'coeSpread']?this.showDatas():'';//这里combobox下拉框要重新加载一下
+        $('#'+pre+'cusSpread').is(':visible')&&this[pre+'cusSpread']?this[pre+'cusSpread'].refresh():'';
+        $('#'+pre+'assSpread').is(':visible')&&this[pre+'assSpread']?this[pre+'assSpread'].refresh():'';
+        $('#'+pre+'stableSpread').is(':visible')&&this[pre+'stableSpread']?this[pre+'stableSpread'].refresh():'';
     },
     showDatas:function () {
         if($('#itemCharacterText').is(':visible'))MaterialController.showItemCharacterText()
-        if($('#coeSpread').is(':visible')) this.showCoeData();
-        if($('#cusSpread').is(':visible')) this.showCusData();
+        if($('#coeSpread').is(':visible')||$('#divide_coeSpread').is(':visible')) this.showCoeData();
+        if($('#cusSpread').is(':visible')||$('#divide_cusSpread').is(':visible')) this.showCusData();
         if($('#assSpread').is(':visible')) this.showAssData();
-        if($('#stableSpread').is(':visible')) this.showStableData();
+        if($('#stableSpread').is(':visible')||$('#divide_stableSpread').is(':visible')) this.showStableData();
     },
     refreshStableDataIfNeeded: function () {
         if ($('#stableSpread').is(':visible')) {
@@ -330,14 +350,15 @@ let zmhs_obj = {
         let me = zmhs_obj;
         let sheet = args.sheet, row = args.row, col = args.col;
         let cellType = sheet.getCellType(row, col);
-        if (args.sheetName == 'ration_coe' && cellType instanceof GC.Spread.Sheets.CellTypes.CheckBox) {
+        if ((args.sheetName == 'divide_ration_coe'||args.sheetName == 'ration_coe')&& cellType instanceof GC.Spread.Sheets.CellTypes.CheckBox) {
             me.onCoeCheckBoxClick(sender, args)
         }
     },
     bindCusEditorValue:function(context){
         let me = zmhs_obj;
-        if(me.coeSheetData[context.row]){
-            let data = me.coeSheetData[context.row];
+        let pre = $('#divide_subSpread').is(':visible')?"divide_":"";
+        if(me[pre+'coeSheetData'][context.row]){
+            let data = me[pre+'coeSheetData'][context.row];
             for(let c of data.coes){
                 $("#"+ c.coeType).val(c.amount);
             }
@@ -352,8 +373,10 @@ let zmhs_obj = {
     updateCusCoeAfterEditor:function(){
         let me = zmhs_obj;
         let result = me.checkIfNeedUpdate();
+        let pre = $('#divide_subSpread').is(':visible')?"divide_":"";
         if (result.isNeed) {
-            projectObj.project.ration_coe.updateCustomerCoe(result);
+          if(pre == "")  projectObj.project.ration_coe.updateCustomerCoe(result);
+          if(pre == "divide_") divideObj.updateCustomerCoe(result);
         }
     },
     onInputChange(id, name){
@@ -421,6 +444,7 @@ let zmhs_obj = {
     },
     onCoeCheckBoxClick:function (sender, args) {
         let me = zmhs_obj;
+        let pre = $('#divide_subSpread').is(':visible')?"divide_":"";
         let checkboxValue = args.sheet.getCell(args.row, args.col).value();
         let newval = 0;
         if (checkboxValue) {
@@ -430,15 +454,16 @@ let zmhs_obj = {
             newval = 1;
             args.sheet.getCell(args.row, args.col).value(newval);
         }
-        let recode = me.coeSheetData[args.row];
+        let recode = me[pre+"coeSheetData"][args.row];
         recode.assistCode && recode.assistCode != "" ? me.adjustAssClick(args,newval) : projectObj.project.ration_coe.adjustCoeClick(recode, newval);
     },
     generateHtmlString: function (context,cellRect,$editor) {//这里要改成动态的了,根据自定义系数内容生成对应的输入框
         let me = zmhs_obj;
+        let pre = $('#divide_subSpread').is(':visible')?"divide_":"";
         let height = cellRect.height;
         let offect = 0;
         let newString = "<form style='margin-top:1px' ><table  width='100%'  cellpadding='0'  border='1px' bordercolor='#CCCCCC' cellspacing='0px' style='border-collapse:collapse;'>";
-        let cus_coe =  me.coeSheetData[context.row];
+        let cus_coe =  me[pre+'coeSheetData'][context.row];
         if(cus_coe){
             for(let i =0;i< cus_coe.coes.length;i++){
                 newString += me.getOneRow(cus_coe.coes[i].coeType, i, cus_coe.coes[i].coeType,height);
@@ -473,19 +498,22 @@ let zmhs_obj = {
     },
     onCoeValueChange:function (e,args) {
         let fieldID =  zmhs_obj.coeSetting.header[args.col].dataCode;
-        let recode = zmhs_obj.coeSheetData[args.row];
+        let pre = $('#divide_subSpread').is(':visible')?"divide_":"";
+        let recode = zmhs_obj[pre+"coeSheetData"][args.row];   
         if(gljUtil.isDef(recode.option_codes)&&recode.option_codes!=""&& fieldID == 'name'){//说明是选择了下拉框
-            projectObj.project.ration_coe.adjustCoeClick(recode, 1,{'select_code':args.newValue});
+          projectObj.project.ration_coe.adjustCoeClick(recode, 1,{'select_code':args.newValue});
         }else if(recode.assistCode &&recode.assistCode!=""){//编辑的是辅助定额
             zmhs_obj.updateRationAss({editingText:args.newValue,row:args.row - zmhs_obj.assFirstIndex})//转换一下
         }
+        
     },
     onCusValueChange:function (e,args) {
       zmhs_obj.changeCusValue([{row:args.row,col:args.col,value:args.newValue}]);
     },
     changeCusValue:function (datas) {//[{row:,col,value}]
-        if(this.cusSheetData){
-            let tem_coes = _.cloneDeep(this.cusSheetData.coes);
+        let pre = $('#divide_subSpread').is(':visible')?"divide_":"";
+        if(this[pre+"cusSheetData"]){
+            let tem_coes = _.cloneDeep(this[pre+"cusSheetData"].coes);
             for(let d of datas){
                 if(d.value&&!sheetCommonObj.checkData(d.col,this.cusSetting,d.value)){
                     this.showDatas();
@@ -503,7 +531,7 @@ let zmhs_obj = {
                 }
             }
             let doc = {'coes':tem_coes,'content':this.generationContent(tem_coes)};
-            projectObj.project.ration_coe.adjustCoeClick(this.cusSheetData, 1,doc);
+            projectObj.project.ration_coe.adjustCoeClick(this[pre+"cusSheetData"], 1,doc);
         }
     },
     generationContent:function (coes) {
@@ -552,13 +580,18 @@ let zmhs_obj = {
     },
     adjustAssClick:function (args,newval) {
         let me = zmhs_obj, row = args.row - me.assFirstIndex;
-        projectObj.project.ration_ass.updateActualValue(me.assSheetData, row,null,newval);
+        if($('#divide_subSpread').is(':visible')){
+          divideObj.updateActualValue(me.divide_assSheetData, args.row, null,newval);
+        }else{
+          projectObj.project.ration_ass.updateActualValue(me.assSheetData, row,null,newval);
+        }
     },
     updateRationAss: function (args) {
         var me = zmhs_obj;
         var newval;
+        let pre = $('#divide_subSpread').is(':visible')?"divide_":"";
         newval = me.numberValueChecking(args.editingText);
-        var recode = me.assSheetData[args.row];
+        var recode = me[pre+"assSheetData"][args.row];
         if (args.editingText === null) {
             newval = parseFloat(recode.stdValue);
         }
@@ -568,7 +601,11 @@ let zmhs_obj = {
         }
         if (isValidate) {
             newval = scMathUtil.roundTo(newval, -2);
-            projectObj.project.ration_ass.updateActualValue(me.assSheetData, args.row, newval);
+            if($('#divide_subSpread').is(':visible')){
+              divideObj.updateActualValue(me.divide_assSheetData, args.row, newval);
+            }else{
+              projectObj.project.ration_ass.updateActualValue(me.assSheetData, args.row, newval);
+            }
         } else {
             me.showDatas();
         }
@@ -623,9 +660,13 @@ let zmhs_obj = {
         // 获取需要更新的数据
         const rationGLJ = projectObj.project.ration_glj;
         const updateProportionList = this.getStablePostData(sheetData);
-        const projectID = projectObj.project.ID();
-        const rationID = projectObj.project.mainTree.selected.data.ID;
-        rationGLJ.updateProportion(updateProportionList, projectID, rationID);
+        if($('#divide_subSpread').is(':visible')){
+          divideObj.updateProportion(updateProportionList);
+        }else{
+          const projectID = projectObj.project.ID();
+          const rationID = projectObj.project.mainTree.selected.data.ID;
+          rationGLJ.updateProportion(updateProportionList, projectID, rationID);
+        }
     },
     // 将值进行四舍五入处理
     handleDataWithPrecision: function (data, precision) {
@@ -635,10 +676,11 @@ let zmhs_obj = {
     },
     // 获取经过自动处理后的表格数据
     getAutoStableSheetData: function (changedData, precision) {
+        let pre = $('#divide_subSpread').is(':visible')?"divide_":"";
         const expectedValue = 100;
         const unchangedData = [];
         const col = this.stableSetting.header.findIndex(item => item.dataCode === 'adjustProportion');
-        this.stableSheetData.forEach((item, index) => {
+        this[pre+"stableSheetData"].forEach((item, index) => {
             const matchData = changedData.find(dItem => dItem.row === index);
             if (!matchData) {
                 unchangedData.push({ row: index, col: col, value: item.adjustProportion});
@@ -674,9 +716,10 @@ let zmhs_obj = {
         }
     },
     getStablePostData: function (sheetData) {
+        let pre = $('#divide_subSpread').is(':visible')?"divide_":"";
         const postData = [];
         sheetData.forEach(cell => {
-            const originItem = this.stableSheetData[cell.row];
+            const originItem = this[pre+"stableSheetData"][cell.row];
             if (cell.value !== originItem.adjustProportion) {
                 postData.push({ ID: originItem.ID, adjustProportion: cell.value});
             }

+ 1 - 1
web/building_saas/unit_price_file/index.html

@@ -174,7 +174,7 @@
     <img src="/web/dest/css/img/engineering.png" id="eng_pic" style="display: none">
     <img src="/web/dest/css/img/tender.png" id="tender_pic" style="display: none">
 
-    <img src="/web/dest/css/img/blockLib.png" id="blockLib_pic" style="display: none">
+    <img src="/web/dest/css/img/blocklib.png" id="blockLib_pic" style="display: none">
     <img src="/web/dest/css/img/folder_open.png" id="folder_pic" style="display: none">
     <img src="/web/dest/css/img/tender.png" id="block_pic" style="display: none">
 

+ 28 - 1
web/over_write/js/hunan_2020.js

@@ -408,9 +408,36 @@ if (typeof projectObj !== 'undefined') {
     projectObj.isInsertEquipmentVisable = function (selected) {
         return true;   //湖南不管是预算或者工程量清单,都显示   
     }
+    projectObj.isInsertEquipmentVisable = function (selected) {
+        if (projectObj.project.property.valuationType == 'bill') {//预算项目中,右键“插入设备”,仅在第一部分中显示。
+            return projectObj.project.Bills.isConstructionInstall(selected);
+        }
+        return true;   //湖南不管是预算或者工程量清单,都显示   
+    }
+}
+
+//湖南工地转移费率值修改特殊处理
+if (typeof feeRateObject !== 'undefined') {
+    feeRateObject.feeRateSpecialHandle = function (subRate, value) {
+        let result = {};
+        if (subRate.name == "工地转移(km)" && value && value < 50) {//工地转移50km以内按50km算
+            result.valueKey = "50";
+            result.value = scMathUtil.roundForObj(value, getDecimal("feeRate"));//设置显示的节点值
+        }
+        return result;
+    }
+}
+
+if (typeof electrovalenceObj !== 'undefined') {
+    electrovalenceObj.options = [
+        { code: "3005003", name: "电网电", specs: "", unit: "kW·h", type: "201" },
+        { code: "8017001", name: "15kW以内柴油发电机组", specs: "12GF1", unit: "台班", type: "301" },
+        { code: "8017002", name: "30kW以内柴油发电机组", specs: "30GFY-2", unit: "台班", type: "301" },
+        { code: "8017003", name: "50kW以内柴油发电机组", specs: "50GFY-2", unit: "台班", type: "301" }
+    ]
 }
 
-// 安徽养护在新建分段的时候需要隐藏养护类别和费用标准
+// 在新建分段的时候需要隐藏养护类别和费用标准
 if (typeof $ !== 'undefined') { // 后端也有引用这个文件,后端引用时$没有定义会报错
     $(document).ready(function () {
         $('#tender-engineering-group').hide();