Преглед изворни кода

Merge branch 'master' of http://smartcost.f3322.net:3000/SmartCost/ConstructionCost

zhongzewei пре 7 година
родитељ
комит
d3c80f3fd0

+ 4 - 1
modules/glj/controllers/glj_controller.js

@@ -13,6 +13,7 @@ import MixRatioModel from "../models/mix_ratio_model";
 import UnitPriceFileModel from "../models/unit_price_file_model";
 let logger = require("../../../logs/log_helper").logger;
 let consts = require('../../main/models/project_consts');
+let glj_type_util = require('../../../public/cache/std_glj_type_util');
 
 const ProjectModel = require('../../pm/models/project_model').project;
 class GLJController extends BaseController {
@@ -595,12 +596,14 @@ async function getGLJListByProjectID(projectId){
         responseData.data.mixRatioConnectData = mixRatioConnectData;
         responseData.data.mixRatioMap = mixRationMap;
         responseData.data.usedTenderList = usedTenderList;
+        let gljTypeMap = glj_type_util.getStdGljTypeCacheObj().innerGljTypeObj;
         responseData.data.constData = {
             materialIdList: gljListModel.materialIdList,
             ownCompositionTypes: gljListModel.ownCompositionTypes,
             roomId: unitPriceFileId,
             GLJTypeConst: JSON.stringify(GLJTypeConst),
-            usedUnitPriceInfo: usedUnitPriceInfo
+            usedUnitPriceInfo: usedUnitPriceInfo,
+            gljTypeMap:gljTypeMap
         };
     } catch (error) {
         console.log(error);

+ 3 - 3
modules/main/controllers/labour_coe_controller.js

@@ -44,12 +44,12 @@ async function getStdLabourCoe(req, res) {
 function save(req, res) {
     let result = {error: 0, message: '', data: null};
 
-    labourCoeFacade.save(req.body.data, function (err, message, data) {
-        if (err == 0){
+    labourCoeFacade.save(req.body.data, function (err, data) {
+        if (err == ''){
             result.data = data;
         }else{
             result.error = 1;
-            result.message = message;
+            result.message = err;
         }
     });
 

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

@@ -2,6 +2,8 @@
  * Created by jimiz on 2017/4/9.
  */
 var rationData = require('../models/ration');
+var ration_glj_facade = require('../../ration_glj/facade/ration_glj_facade');
+let logger = require("../../../logs/log_helper").logger;
 
 //统一回调函数
 var callback = function(req, res, err, message, data){
@@ -39,6 +41,25 @@ module.exports = {
                 callback(req, res, err, message, null);
             }
         });
+    },
+    insertGLJAsRation:insertGLJAsRation
+};
+
+async function insertGLJAsRation(req, res){
+    let result={
+        error:0
     }
+    try {
+        let data = req.body.data;
+        data = JSON.parse(data);
+        let datas= await ration_glj_facade.insertGLJAsRation(data);
+        result.data=datas;
+    }catch (err){
+        logger.err(err);
+        result.error=1;
+        result.message = err.message;
+    }
+    res.json(result);
+
 
-};
+}

+ 4 - 3
modules/main/facade/labour_coe_facade.js

@@ -112,9 +112,10 @@ function save (data, callback) {
     projectLabourCoesModel.bulkWrite(updateArr)
         .then(function(){
             logger.info(`Project LabourCoe saved successful : ${data.projectID}`);
-            callback(0, '', null);
+            callback('', null);
         })
         .catch(function (err) {
-            logger.err(err);
-            callback(1, err, null)});
+            logger.err('labourCoe save error: ' + err);
+            callback(err, null)
+        });
 }

+ 12 - 2
modules/main/models/ration.js

@@ -37,6 +37,7 @@ let rationSchema = new Schema({
     name: String,
     unit: String,
     quantity: String,
+    contain:String,//含量
     programID: Number,
     marketUnitFee: String,
     marketTotalFee: String,
@@ -51,13 +52,22 @@ let rationSchema = new Schema({
     caption: String,
     isFromDetail:{type: Number,default:0},       // 1 true 2 false
     adjustState: String,
-    content: String,
     rationProjName: String,
     comments: String,                           // 说明
     flags: [subSchema.flagsSchema],             // 标记字段
     rationAssList: [rationAssItemSchema],
     content: String,                            // 工作内容
-    ruleText: String                            // 计算规则
+    ruleText: String,                            // 计算规则
+
+    //工料机特有属性
+    projectGLJID:Number,  //项目工料机ID
+    GLJID:Number,//工料机库ID
+    original_code:String, //原始编码
+    specs:String,//规格型号
+    shortName:String,//缩写
+    customQuantity:String,//自定义消耗
+    from:{type: String,default:'std'}//std, cpt  来自标准工料机库、补充工料机库
+
 });
 
 let ration = db.model("ration", rationSchema, "ration");

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

@@ -6,10 +6,11 @@ let express = require('express');
 module.exports = function (app) {
     let rationRouter = express.Router();
     let rationController = require('../controllers/ration_controller');
-
     rationRouter.post('/getData', rationController.getData);
     rationRouter.post('/getItemTemplate', rationController.getItemTemplate);
     rationRouter.post('/allocIDs', rationController.allocIDs);
+    rationRouter.post('/insertGLJAsRation', rationController.insertGLJAsRation);
+
 
     app.use('/ration', rationRouter);
 };

+ 27 - 11
modules/pm/controllers/pm_controller.js

@@ -12,6 +12,7 @@ let fee_rate_facade = require("../../fee_rates/facade/fee_rates_facade");
 let billsModel = require('../../main/models/bills').model;
 let rationsModel = require('../../main/models/ration').model;
 let projectModel = require("../models/project_schema");
+let asyncTool = require('async');
 
 //统一回调函数
 let callback = function(req, res, err, message, data){
@@ -64,40 +65,55 @@ module.exports = {
     },
     // CSL, 2017-12-14 该方法用于项目属性:提交保存混合型数据,这些数据来自不同的表,包括projects.property、ration、bills、labour_coes.
     updateMixDatas: function(req, res){
-        let callBackInner = function (err, message, data) {
-            if (err === 0) {
-                res.json({error: err, message: message, data: data});
-            } else {
-                res.json({error: err, message: message, data: null});
+        let datas = JSON.parse(req.body.data).mixDataArr;
+        let functions = [];
+
+        function updateFunc(model, cod, doc) {
+            return function (cb) {
+                model.update(cod, doc, cb);
             }
         };
 
-        let datas = JSON.parse(req.body.data).mixDataArr;
+        function updateLC(){
+            return function (cb) {
+                datas.labourCoes.updateData.projectID = datas.projectID;
+                labourCoe.save(datas.labourCoes.updateData, cb);
+            }
+        };
 
         // 项目属性
         if (Object.keys(datas.properties).length > 0){
-            projectModel.update({ID: datas.projectID}, datas.properties, callBackInner);
+            functions.push(updateFunc(projectModel, {ID: datas.projectID}, datas.properties));
         };
 
         // 人工系数
         if (datas.labourCoes.updateData){
-            datas.labourCoes.updateData.projectID = datas.projectID;
-            labourCoe.save(datas.labourCoes.updateData, callBackInner);
+            functions.push(updateLC());
         };
 
         // 清单:每文档doc只存储一条清单,每条清单都必须定位一次文档,无法合并处理
         if (datas.bills.length > 0){
             for (let bill of datas.bills){
-                billsModel.update({projectID: datas.projectID, ID: bill.ID, deleteInfo: null}, bill, callBackInner);
+                functions.push(updateFunc(billsModel, {projectID: datas.projectID, ID: bill.ID, deleteInfo: null}, bill));
             };
         };
 
         // 定额:每文档doc只存储一条定额,每条定额都必须定位一次文档,无法合并处理
         if (datas.rations.length > 0){
             for (let ration of datas.rations){
-                rationsModel.update({projectID: datas.projectID, ID: ration.ID, deleteInfo: null}, ration, callBackInner);
+                functions.push(updateFunc(rationsModel, {projectID: datas.projectID, ID: ration.ID, deleteInfo: null}, ration));
             };
         };
+
+        asyncTool.parallel(functions, function(err, result){
+            {
+                if (!err) {
+                    res.json({error: 0, message: err, data: result});
+                } else {
+                    res.json({error: 1, message: err, data: null});
+                }
+            }
+        });
     },
     updateFiles: async function(req, res){
         let data = JSON.parse(req.body.data);

+ 37 - 4
modules/ration_glj/facade/ration_glj_facade.js

@@ -22,6 +22,8 @@ import stdgljutil  from "../../../public/cache/std_glj_type_util";
 import EngineeringLibModel from "../../users/models/engineering_lib_model";
 import GljDao from "../../complementary_glj_lib/models/gljModel";
 import {complementaryGljModel, stdGljModel, gljClassModel} from "../../complementary_glj_lib/models/schemas";
+import  projCounter from '../../main/models/proj_counter_model';
+
 
 
 module.exports={
@@ -35,7 +37,8 @@ module.exports={
     replaceGLJ:replaceGLJ,
     mReplaceGLJ:mReplaceGLJ,
     updateRationGLJByEdit:updateRationGLJByEdit,
-    getGLJClass:getGLJClass
+    getGLJClass:getGLJClass,
+    insertGLJAsRation:insertGLJAsRation
 }
 
 let operationMap={
@@ -551,8 +554,8 @@ function getGLJSearchInfo(ration_glj) {
         shortName:ration_glj.shortName,
         specs: ration_glj.specs,
         unit: ration_glj.unit,
-        type: ration_glj.type,
-        type_of_work: ration_glj.type,
+        type:ration_glj.subType?ration_glj.subType:ration_glj.type,//如果有subType,则是通过插入定额级的工料机进来的
+        type_of_work: ration_glj.subType?ration_glj.subType:ration_glj.type,
         base_price: ration_glj.basePrice,
         market_price: ration_glj.basePrice,
         repositoryId:ration_glj.repositoryId,
@@ -574,7 +577,7 @@ async function addGLJ(rgList) {
        g.marketPrice=result.unit_price.market_price;
        g.adjustPrice=result.unit_price.base_price;
        g.basePrice=result.unit_price.base_price;
-       g.isAdd=result.unit_price.is_add,
+       g.isAdd=result.unit_price.is_add;
        g.projectGLJID=result.id;
        g.isEstimate=result.is_evaluate;
        g.ID=uuidV1();
@@ -710,6 +713,36 @@ async function getGLJClass(info,data) {
    return result;
 }
 
+async function insertGLJAsRation(data) {
+    let gljList = data.gljList;
+    //先更新counter
+    let counter = await projCounter.model.findOneAndUpdate({projectID:data.projectID},{ration:data.rationCount},{new:true});
+    console.log(counter);
+    if(data.hasOwnProperty("selectedSerialNo")){ //如果需要,更新序列号。
+        let query={
+            projectID:data.projectID,
+            billsItemID:data.billsItemID,
+            serialNo:{$gt: data.selectedSerialNo}
+        }
+        await ration.update(query,{$inc:{serialNo:gljList.length}},{multi: true});
+    }
+
+    for(let glj of gljList){
+        let p_glj = getGLJSearchInfo(glj);
+        let projectGljModel = new GLJListModel();
+        let result = await projectGljModel.addList(p_glj);//逐条添加到项目工料机
+        glj.marketPrice=result.unit_price.market_price;
+        glj.adjustPrice=result.unit_price.base_price;
+        glj.basePrice=result.unit_price.base_price;
+        glj.isAdd=result.unit_price.is_add;
+        glj.projectGLJID=result.id;
+        glj.isEstimate=result.is_evaluate;
+    }
+    await ration.insertMany(gljList);
+    console.log(gljList);
+    return gljList;
+}
+
 async function changAdjustState(data,rationList) {
     let stateList=[];
     for(let r of rationList){

+ 31 - 14
modules/ration_glj/models/ration_glj_temp.js

@@ -40,30 +40,47 @@ var rationAssItemSchema = mongoose.Schema({
 
 
 let rationSchema = new Schema({
+    // 公用属性部分
     ID: Number,
     projectID: Number,
     billsItemID: Number,
     serialNo: Number,
-    libID: Number,
     code: String,
     name: String,
-    maskName: String,
-    caption: String,
     unit: String,
-    quantity: String, // Decimal
-    isFromDetail:{type: Number,default:0},//1 true 2 false
+    quantity: String,
+    contain:String,//含量
     programID: Number,
-    adjustState: String,
-    content: String,
-    rationProjName: String,
-    comments: String,
-    // 费用字段
+    marketUnitFee: String,
+    marketTotalFee: String,
     fees: [subSchema.feesSchema],
-    // 标记字段
-    flags: [subSchema.flagsSchema],
     deleteInfo: deleteSchema,
-    rationAssList: [rationAssItemSchema]
-});
+    type: Number,                               // 1 定额、2 量价、3 工料机定额
+    subType: Number,                            // 子类型:1人工、201材料、301机械、4主材、5设备
+
+    // 定额特有属性:
+    libID: Number,
+    maskName: String,
+    caption: String,
+    isFromDetail:{type: Number,default:0},       // 1 true 2 false
+    adjustState: String,
+    rationProjName: String,
+    comments: String,                           // 说明
+    flags: [subSchema.flagsSchema],             // 标记字段
+    rationAssList: [rationAssItemSchema],
+    content: String,                            // 工作内容
+    ruleText: String,                            // 计算规则
+
+    //工料机特有属性
+    projectGLJID:Number,  //项目工料机ID
+    GLJID:Number,//工料机库ID
+    original_code:String, //原始编码
+    specs:String,//规格型号
+    shortName:String,//缩写
+    customQuantity:String,//自定义消耗
+    from:{type: String,default:'std'}//std, cpt  来自标准工料机库、补充工料机库
+
+},{versionKey:false});
 
 mongoose.model("ration", rationSchema, "ration");
 

+ 32 - 0
modules/reports/util/rpt_construct_data_util.js

@@ -601,6 +601,7 @@ function setupFunc(obj, prop, ownRawObj) {
     obj[prop].getFee = ext_getFee;
     obj[prop].getPropertyByForeignId = ext_getPropertyByForeignId;
     obj[prop].getArrayItemByKey = ext_getArrayItemByKey;
+    obj[prop].getPropertyByFlag = ext_getPropertyByFlag;
     if (prop === projectConst.CALC_PROGRAM) obj[prop].getCalcProperty = ext_getCalcProperty;
     if (prop === projectConst.FEERATE) obj[prop].getFeeRate = ext_getFeeRate;
 }
@@ -859,7 +860,38 @@ function ext_getArrayItemByKey(arrayKey, itemKey, itemKeyValue, itemRstKey){
             private_getItemValue(arr, itemKeyValue);
         }
     }
+}
 
+function ext_getPropertyByFlag(flagVal, rstKey, dftValIfEmpty) {
+    let rst = [], parentObj = this;
+    let dtObj = parentObj["myOwnRawDataObj"];
+    if (flagVal && rstKey && dtObj) {
+        let isArr = (flagVal instanceof Array);
+        for (let dItem of dtObj.data) {
+            let doc = (dItem._doc === null || dItem._doc === undefined)?dItem:dItem._doc;
+            if (doc.hasOwnProperty("flags")) {
+                let bFlag = false;
+                for (let flagItem of doc.flags) {
+                    if (isArr) {
+                        bFlag = (flagVal.indexOf(flagItem.flag) >= 0);
+                    } else {
+                        if (flagItem.flag === flagVal) {
+                            bFlag = true;
+                        }
+                    }
+                    if (bFlag) break;
+                }
+                if (bFlag) {
+                    rst.push(doc[rstKey]);
+                    break;
+                }
+            }
+        }
+    }
+    if (rst.length === 0 && dftValIfEmpty) {
+        rst.push(dftValIfEmpty);
+    }
+    return rst;
 }
 
 function ext_getPropertyByForeignId(foreignIdVal, adHocIdKey, propKey, dftValIfNotFound) {

+ 55 - 27
public/stringUtil.js

@@ -145,36 +145,64 @@ module.exports = {
     rightTrim: function(rst) {
         return str.replace(/(\s*$)/g,"");
     },
-    convertNumToChinese : function(num, isCurrency) {
-        if (!/^\d*(\.\d*)?$/.test(num)) { return "Number is wrong!"; }
-        let AA, BB;
-        if (isCurrency) {
-            AA = ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"];
-            BB = ["", "拾", "佰", "仟", "萬", "億", "点", ""];
-        } else {
-            AA = ['零','一','二','三','四','五','六','七','八','九'];
-            BB = ["", "十", "百", "千", "万", "亿", "点", ""];
-        }
-        //let AA = new Array("零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖");
-        //let BB = new Array("", "拾", "佰", "仟", "萬", "億", "点", "");
-        let a = ("" + num).replace(/(^0*)/g, "").split("."), k = 0, re = "";
-        for (let i = a[0].length - 1; i >= 0; i--) {
-            switch (k) {
-                case 0: re = BB[7] + re; break;
-                case 4: if (!new RegExp("0{4}\\d{" + (a[0].length - i - 1) + "}$").test(a[0]))
-                    re = BB[4] + re; break;
-                case 8: re = BB[5] + re; BB[7] = BB[5]; k = 0; break;
+    replaceAll: function (targetStr, FindText, RepText) {
+        let regExp = new RegExp(FindText, "gm");
+        return targetStr.replace(regExp, RepText);
+    },
+    convertToCaptionNum: function(num, isCurrency, isTraditionalCap) {
+        let me = this, rst = "";
+        if (/^\d*(\.\d*)?$/.test(num)) {
+            let capChars, unitChars;
+            if (isTraditionalCap) {
+                capChars = ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"];
+                unitChars = ["" , "拾", "佰", "仟", "萬", "拾", "佰", "仟", "億", "拾", "佰", "仟", "萬"];
+            } else {
+                capChars = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"];
+                unitChars = ["" , "十", "百", "千", "万", "十", "百", "千", "亿", "十", "百", "千", "万"];
             }
-            if (k % 4 === 2 && a[0].charAt(i + 2) !== 0 && a[0].charAt(i + 1) === 0) re = AA[0] + re;
-            if (a[0].charAt(i) !== 0) re = AA[a[0].charAt(i)] + BB[k % 4] + re; k++;
-        }
 
-        if (a.length > 1) //加上小数部分(如果有小数部分)
-        {
-            re += BB[6];
-            for (let i = 0; i < a[1].length; i++) re += AA[a[1].charAt(i)];
+            let numSplitArr = ("" + num).replace(/(^0*)/g, "").split(".");
+            if (numSplitArr[0] === "") numSplitArr[0] = "0";
+            let len = numSplitArr[0].length;
+            let intPartArr = [];
+            if (len <= 13) {
+                for (let idx = 0; idx < len; idx++) {
+                    intPartArr.push(capChars[ parseInt(numSplitArr[0].charAt(idx) )] + unitChars[len - idx - 1]);
+                }
+                rst = intPartArr.join('');
+                rst = me.replaceAll(rst, capChars[0] + unitChars[3], capChars[0]); //零千 -> 零
+                rst = me.replaceAll(rst, capChars[0] + unitChars[2], capChars[0]); //零百 -> 零
+                rst = me.replaceAll(rst, capChars[0] + unitChars[1], capChars[0]); //零十 -> 零
+                //
+                rst = me.replaceAll(me.replaceAll(rst, "零零", "零"), "零零", "零");
+                rst = me.replaceAll(rst, capChars[0] + unitChars[8], unitChars[8]); //零亿 -> 亿
+                rst = me.replaceAll(rst, capChars[0] + unitChars[4], unitChars[4]); //零万 -> 万
+                //
+                rst = me.replaceAll(rst, unitChars[8] + unitChars[4], unitChars[8] + capChars[0]); //亿万 -> 亿零
+                if (num === 0) {
+                    rst = "零";
+                } else if (rst.length > 1 && rst.charAt(rst.length - 1) === '零') {
+                    rst = rst.slice(0, rst.length - 1);
+                }
+                //小数部分处理
+                if (numSplitArr.length > 1) {
+                    len = numSplitArr[1].length;
+                    if (isCurrency && len > 2) len = 2;
+                    let fractionStr = [];
+                    for (let idx = 0; idx < len; idx++) {
+                        fractionStr.push(capChars[ parseInt(numSplitArr[1].charAt(idx))]+ (isCurrency?((idx === 0)?"角":"分"):""));
+                    }
+                    rst = rst + (isCurrency?"元":"点") + fractionStr.join("");
+                } else {
+                    rst = rst + (isCurrency?"元整":"");
+                }
+            } else {
+                rst = "Number is too big!";
+            }
+        } else {
+            rst = "Number is wrong!";
         }
-        return re;
+        return rst;
     },
     convertStrToBoolean: function(str) {
         let rst = false, me = this;

+ 10 - 0
web/building_saas/main/js/models/calc_program.js

@@ -917,6 +917,12 @@ class CalcProgram {
                     feeRate: node.data.feeRate,
                     feeRateID: node.data.feeRateID
                 };
+                if(node.sourceType==ModuleNames.ration&&node.data.type==rationType.gljRation){//定额类型的工料机做特殊处理
+                    data.code=node.data.code;
+                    data.projectGLJID = node.data.projectGLJID;
+                    delete data.marketUnitFee;
+                }
+
                 let newData = {'updateType': 'ut_update', 'updateData': data};
                 me.project.push(node.sourceType, [newData]);
             }
@@ -971,4 +977,8 @@ class CalcProgram {
             me.saveNodes(needSaveNodes);
         };
     };
+    calcRationsAndSave(nodes){//计算批量替换工料机后受影响的定额,同时将结果打包保存
+
+    };
+
 }

+ 0 - 6
web/building_saas/main/js/models/main_consts.js

@@ -108,12 +108,6 @@ const volumePriceMaps = {
     5: "量设"
 };
 
-const gljTypeMap = {
-   201:'材',
-   4:'主',
-   5:'设'
-}
-
 
 const rationType = {
     ration: 1,

+ 7 - 2
web/building_saas/main/js/models/project_glj.js

@@ -172,7 +172,8 @@ ProjectGLJ.prototype.updateBasePriceFromRG=function(recode,updateField,newval){
             me.refreshRationGLJPrice(glj);
             gljOprObj.showRationGLJSheetData();
             me.refreshTreeNodePriceIfNeed(glj);
-            
+            //触发计算
+            projectObj.project.ration_glj.reCalcWhenGLJChange(recode);
             $.bootstrapLoading.end();
         }
         $.bootstrapLoading.start();
@@ -258,5 +259,9 @@ ProjectGLJ.prototype.getAdjustPrice = function (glj) {
     }else {
         return glj.unit_price.base_price
     }
+}
 
-}
+ProjectGLJ.prototype.getShortNameByID = function (ID) {
+    let gljTypeMap = this.datas.constData.gljTypeMap;
+    return gljTypeMap["typeId"+ID].shortName;
+}

+ 112 - 6
web/building_saas/main/js/models/ration_glj.js

@@ -194,7 +194,7 @@ var ration_glj = {
             projectObj.mainController.refreshTreeNode([rationNode]);
             for(let o of oldData){
                 if(this.needShowToTree(o)){
-                    let node = me.findTreeNodeByID(o.ID);  //找到对应的树节点
+                    let node = me.findGLJNodeByID(o.ID);  //找到对应的树节点
                     projectObj.mainController.deleteNode(node,next);
                 }
             }
@@ -353,6 +353,7 @@ var ration_glj = {
                 if(initShow==false){//不需要初始化,只需耍新当前显示就可以了
                     gljOprObj.showRationGLJSheetData();
                 }
+                me.reCalcWhenGLJChange(recode);//触发计算定额以及父节点
                 projectObj.project.projectGLJ.loadData(function () {//等项目工料机加载完成后再给用户编辑
                     if(initShow==true){
                         gljOprObj.refreshView();
@@ -372,7 +373,7 @@ var ration_glj = {
             var doc = {};
             doc[updateField]=newval;
             if(updateField=="type"){
-                doc.shortName = gljTypeMap[newval];
+                doc.shortName =  projectObj.project.projectGLJ.getShortNameByID[newval];
             }
             CommonAjax.post("/rationGlj/updateRationGLJByEdit",{query:query,doc:doc,priceInfo:priceInfo},callback,function (err) {
                 $.bootstrapLoading.end();
@@ -404,6 +405,100 @@ var ration_glj = {
                 cb(data);
             })
         };
+        ration_glj.prototype.insertGLJAsRation = function (GLJSelection,selected,callback) {
+            let gljList = [];
+            let allGLJ=gljOprObj.AllRecode;
+            let billsItemID = null;
+            let serialNo=0;
+            let selectedSerialNo=null;
+            let nextNodeID=null;
+            let parentNodeID=null;
+            let children = [];
+            if(selected.sourceType === project.Bills.getSourceType()){
+                billsItemID = selected.data.ID;
+                parentNodeID = selected.getID();
+                nextNodeID = selected.tree.rootID();
+            }else {
+                billsItemID = selected.data.billsItemID;
+                serialNo = selected.data.serialNo;
+                selectedSerialNo=selected.data.serialNo;
+                nextNodeID= selected.getNextSiblingID();
+                parentNodeID=selected.getParentID();
+            }
+            children = project.Ration.getBillsSortRation(billsItemID);
+            serialNo==0?serialNo=children.length:"";
+            for(let con_key of GLJSelection){
+                var glj=_.find(allGLJ,function (item) {
+                    let i_key = gljOprObj.getIndex(item,['code','name','specs','unit','gljType']);
+                    return i_key ==con_key;
+                });
+                if(glj){
+                    serialNo+=1;
+                    let new_glj = {
+                        ID:project.Ration.getNewRationID(),
+                        projectID:parseInt(project.ID()),
+                        billsItemID:billsItemID,
+                        type:rationType.gljRation,
+                        code : glj.code,
+                        name :glj.name,
+                        quantity:0,
+                        unit:glj.unit,
+                        specs:glj.specs,
+                        subType:glj.gljType,
+                        basePrice:glj.basePrice,
+                        original_code:glj.code,
+                        shortName:glj.shortName,
+                        serialNo:serialNo,
+                        GLJID:glj.ID,
+                        adjCoe:glj.adjCoe,
+                        repositoryId:glj.repositoryId
+                    }
+                    if(glj.hasOwnProperty("compilationId")){
+                        new_glj.from="cpt";
+                        if(glj.code.indexOf('-')!=-1){//这条工料机是用户通过修改名称、规格、型号等保存到补充工料机库的
+                            new_glj.original_code = glj.code.split('-')[0];//取-前的编号作为原始编号
+                        }
+                    }
+                    gljList.push(new_glj);
+                }
+            }
+            if(gljList.length==0){
+                return;
+            }
+            let postData = {
+                gljList:gljList,
+                projectID:parseInt(project.ID()),
+                billsItemID:billsItemID,
+                rationCount:project.Ration.maxRationID()
+            }
+            selectedSerialNo==null?"":postData.selectedSerialNo = selectedSerialNo;
+            $.bootstrapLoading.start();
+            CommonAjax.post("/ration/insertGLJAsRation",postData,function (data) {
+                console.log(data);
+                 // 更新兄弟节点的序列号
+                if(selectedSerialNo!=null&&selectedSerialNo<children.length){
+                    for(let i = selectedSerialNo;i<children.length;i++){
+                        children[i].serialNo+=gljList.length;
+                    }
+                }
+                for(let r_glj of data){
+                    r_glj.marketUnitFee = r_glj.marketPrice;
+                    r_glj.quantity =r_glj.quantity+"";
+                    project.Ration.datas.push(r_glj);
+                    let newNode = project.mainTree.insert(parentNodeID,nextNodeID);
+                    newNode.source = r_glj;
+                    newNode.sourceType = project.Ration.getSourceType();
+                    newNode.data = r_glj;
+                    ProjectController.syncDisplayNewNode(projectObj.mainController, newNode);
+                }
+                callback();
+                $.bootstrapLoading.end();
+            },function () {
+                $.bootstrapLoading.end();
+            });
+
+
+        };
         ration_glj.prototype.addGLJByLib=function (GLJSelection,ration,callback) {
           var gljList=[];
           var allGLJ=gljOprObj.AllRecode;
@@ -546,8 +641,6 @@ var ration_glj = {
             data.marketUnitFee = data.marketPrice;
         };
         ration_glj.prototype.updateFromMainSpread=function (value,node,fieldName) {
-            console.log(fieldName);
-            console.log(value);
             if(node.data[fieldName]===value){
                 return;
             }
@@ -584,12 +677,25 @@ var ration_glj = {
             }
             return false
         };
-        ration_glj.prototype.findTreeNodeByID = function (ID) {
+        ration_glj.prototype.findGLJNodeByID = function (ID) {
             let node = _.find(projectObj.project.mainTree.items,function (n) {//找到对应的树节点
                 return n.sourceType==ModuleNames.ration_glj &&n.data.ID==ID;
             });
             return node;
-        }
+        };
+        ration_glj.prototype.findRationNodeByID = function (ID) {
+            let node = _.find(projectObj.project.mainTree.items,function (n) {//找到对应定额的树节点
+                return n.sourceType==ModuleNames.ration &&n.data.ID==ID;
+            });
+            return node;
+        };
+        ration_glj.prototype.reCalcWhenGLJChange = function (ration_glj) {//当改变定额工料机时,重新计算定额以及期父节点
+            let node = this.findRationNodeByID(ration_glj.rationID);
+            if(node){
+                project.calcProgram.calculate(node);
+                project.calcProgram.saveNode(node);
+            }
+        };
         return new ration_glj(project);
     }
 };

+ 19 - 4
web/building_saas/main/js/views/glj_view.js

@@ -953,7 +953,14 @@ var gljOprObj = {
     doInsertGLJ:function () {
         var selected = projectObj.project.mainTree.selected;
         var project= projectObj.project;
-        console.log(gljOprObj.GLJSelection);
+        if(gljOprObj.GLJSelection.length<=0){
+            return;
+        }
+       $("#glj_tree_div").modal('hide');
+        project.ration_glj.insertGLJAsRation(gljOprObj.GLJSelection,selected,function (result) {
+            project.projectGLJ.loadData();
+            gljOprObj.showRationGLJSheetData();
+        })
     },
     doAddGLJ:function () {
         var selected = projectObj.project.mainTree.selected;
@@ -976,6 +983,8 @@ var gljOprObj = {
                     gljOprObj.showRationGLJSheetData();
                     project.ration_glj.addToMainTree(result.showData);
                     project.projectGLJ.loadData();
+                    project.calcProgram.calculate(selected);
+                    project.calcProgram.saveNode(selected);
                     projectObj.mainController.refreshTreeNode([selected]);
                     $.bootstrapLoading.end();
                 }
@@ -1001,7 +1010,7 @@ var gljOprObj = {
                 gljOprObj.sheetData[index]=data;
                 gljOprObj.showRationGLJSheetData();
                 if(project.ration_glj.needShowToTree(data)){//当替换的是主材或设备时,刷新对应的树节点
-                    var  node =  project.ration_glj.findTreeNodeByID(data.ID);
+                    var  node =  project.ration_glj.findGLJNodeByID(data.ID);
                     if(node){
                         project.ration_glj.transferToNodeData(data);
                         node.source = data;
@@ -1013,6 +1022,8 @@ var gljOprObj = {
                 project.projectGLJ.loadData();
                 selected.data.adjustState=result.adjustState;
                 projectObj.mainController.refreshTreeNode(nodes);
+                project.calcProgram.calculate(selected);
+                project.calcProgram.saveNode(selected);
             }
             $.bootstrapLoading.end();
         })
@@ -1034,14 +1045,15 @@ var gljOprObj = {
                     me.updateProperty(t,data.doc);
                     if(project.ration_glj.needShowToTree(t)){//如果是造价书中的树节点,则也须刷新
                         project.ration_glj.transferToNodeData(t);
-                        var node = project.ration_glj.findTreeNodeByID(t.ID);
+                        var node = project.ration_glj.findGLJNodeByID(t.ID);
                         nodes.push(node);
                     }
                 }
             })
             me.showRationGLJSheetData();
             project.projectGLJ.loadData();
-            me.refreshStateAfterMreplace(stateList,nodes);
+            var rationNodes= me.refreshStateAfterMreplace(stateList,nodes);
+            project.calcProgram.calcRationsAndSave(rationNodes);
             $.bootstrapLoading.end();
         })
     },
@@ -1052,6 +1064,7 @@ var gljOprObj = {
     },
     refreshStateAfterMreplace:function (stateList,gljNodes) {
         var nodes=[];
+        var rationNodes=[];
         _.forEach(stateList,function (s) {
           var node = _.find(projectObj.project.mainTree.items,function (n) {
               return n.sourceType==ModuleNames.ration&&n.data.ID==s.rationID;
@@ -1059,10 +1072,12 @@ var gljOprObj = {
           if(node){
               node.data.adjustState=s.adjustState;
               nodes.push(node);
+              rationNode.push(node);
           }
         });
         gljNodes.length>0?nodes = nodes.concat(gljNodes):"";
         projectObj.mainController.refreshTreeNode(nodes);
+        return rationNodes;
     },
     refreshView:function () {
         this.showRationGLJData();

+ 11 - 6
web/building_saas/main/js/views/main_tree_col.js

@@ -15,10 +15,10 @@ let MainTreeCol = {
                     return volumePriceMaps[node.data.subType];
                 }
                 else if (node.data.type == 3){    // 工料机定额
-                    return '工料机';     // 这里明细值等张伟城确定
+                    return  projectObj.project.projectGLJ.getShortNameByID(node.data.subType);//工料机名字缩写
                 }
             } else if (node.sourceType === projectObj.project.ration_glj.getSourceType()) {
-                return gljTypeMap[node.data.subType];
+                return projectObj.project.projectGLJ.getShortNameByID(node.data.subType);//工料机名字缩写
             }
         },
 
@@ -32,7 +32,7 @@ let MainTreeCol = {
     readOnly: {
         // CSL, 2017-11-28
         subType: function (node){
-            return (node.data.type != 2 && node.data.type != 3&&!MainTreeCol.readOnly.glj(node));
+            return (node.data.type != 2 && node.data.type != 3&&!MainTreeCol.readOnly.glj(node))||(node.data.type==rationType.gljRation&&MainTreeCol.readOnly.non_editSubType(node));
         },
         calcProgramName: function (node) {
             if (
@@ -41,7 +41,9 @@ let MainTreeCol = {
             ) return false
             else return true;
         },
-
+        non_editSubType:function (node) {
+           return node.data.subType!=201&&node.data.subType!=4&&node.data.subType!=5
+        },
         commonUnitFee: function(node){
             return !projectObj.project.calcProgram.isNullBill(node);
         },
@@ -162,8 +164,11 @@ let MainTreeCol = {
                 if (node.data.type == rationType.volumePrice)
                     VPType.itemHeight(5).items(["人工","材料","机械","主材","设备"])
                 else if (node.data.type == rationType.gljRation||node.sourceType === projectObj.project.ration_glj.getSourceType())
-                    VPType.itemHeight(3).items(["材料","主材","设备"]);
-
+                    if(!MainTreeCol.readOnly.non_editSubType(node)){
+                        VPType.itemHeight(3).items(["材料","主材","设备"]);
+                    }else {
+                        return null;
+                    }
                 return VPType;
             };
         },

+ 8 - 6
web/building_saas/main/js/views/project_view.js

@@ -268,7 +268,9 @@ var projectObj = {
         let project = projectObj.project, fieldName = colSetting.data.field;
         if(node.sourceType==project.ration_glj.getSourceType()){
             project.ration_glj.updateFromMainSpread(value,node,fieldName);
-        }else if (value !== calcFees.getFee(node.data, fieldName)) {
+        }if(node.sourceType==ModuleNames.ration&&node.data.type==rationType.gljRation){
+            console.log("hehe");
+        } else if (value !== calcFees.getFee(node.data, fieldName)) {
             if (fieldName === 'code') {
                 projectObj.updateCode(node, value);
             }
@@ -442,11 +444,11 @@ var projectObj = {
 
                     // for test digit. CSLAAAAA
                     if (col.data.field.hasSubStr("totalFee"))
-                       col.data.formatter = MainTreeCol.getNumberFormatter(decimalObj.ration.totalPrice, true)
+                       col.data.formatter = MainTreeCol.getNumberFormatter(decimalObj.ration.totalPrice, false)
                     else if (col.data.field.hasSubStr("unitFee"))
-                        col.data.formatter = MainTreeCol.getNumberFormatter(decimalObj.ration.unitPrice, true)
+                        col.data.formatter = MainTreeCol.getNumberFormatter(decimalObj.ration.unitPrice, false)
                     else if (col.data.field == "quantity")
-                        col.data.formatter = MainTreeCol.getNumberFormatter(decimalObj.ration.quantity, true);
+                        col.data.formatter = MainTreeCol.getNumberFormatter(decimalObj.ration.quantity, false);
                 });
 
                 that.mainController = TREE_SHEET_CONTROLLER.createNew(that.project.mainTree, that.mainSpread.getActiveSheet(), that.project.projSetting.mainGridSetting);
@@ -528,7 +530,7 @@ var projectObj = {
                     disabled: function () {
                         var selected = project.mainTree.selected;
                         var readOnly = MainTreeCol.readOnly;
-                        return readOnly.billsParent(selected)||(readOnly.bills(selected)&&!readOnly.calcBaseType(selected));
+                        return readOnly.billsParent(selected)||(readOnly.bills(selected)&&!readOnly.forCalcBase(selected))||readOnly.glj(selected);
                     },
                     callback: function (key, opt) {
                         getGLJData('insert');// ProjectController.addRation(project, controller, rationType.volumePrice);
@@ -816,7 +818,7 @@ $('#property_ok').click(function () {
                 for (let node of changedNodes){delete node.changed};
             };
             if (mixDatas.labourCoes.updateData) labourCoeView.refresh(mixDatas.labourCoes.updateData);*/
-            // window.location.href = '/main?project=' + projectID;
+            window.location.href = '/main?project=' + projectID;
         });
     }
 });