zhongzewei 6 anni fa
parent
commit
599c1b3844
45 ha cambiato i file con 3177 aggiunte e 815 eliminazioni
  1. 1 0
      config/gulpConfig.js
  2. 16 8
      modules/all_models/compleRation_coe.js
  3. 30 0
      modules/all_models/compleRation_installFeeItem.js
  4. 43 0
      modules/all_models/compleRation_installSection.js
  5. 1 1
      modules/all_models/compleRation_ration.js
  6. 11 6
      modules/all_models/compleRation_section.js
  7. 9 0
      modules/all_models/user.js
  8. 94 27
      modules/complementary_ration_lib/controllers/compleRationController.js
  9. 1 1
      modules/complementary_ration_lib/controllers/compleSectionTreeController.js
  10. 43 16
      modules/complementary_ration_lib/controllers/compleViewController.js
  11. 2 2
      modules/complementary_ration_lib/controllers/searchController.js
  12. 99 0
      modules/complementary_ration_lib/facades/compleCoeFacade.js
  13. 91 0
      modules/complementary_ration_lib/facades/compleInstallFacade.js
  14. 106 82
      modules/complementary_ration_lib/models/compleRationModel.js
  15. 35 16
      modules/complementary_ration_lib/models/searchModel.js
  16. 49 2
      modules/complementary_ration_lib/models/sectionTreeModel.js
  17. 4 0
      modules/complementary_ration_lib/routes/routes.js
  18. 1 1
      modules/main/controllers/ration_controller.js
  19. 19 10
      modules/main/facade/ration_facade.js
  20. 15 1
      modules/pm/controllers/pm_controller.js
  21. 2 0
      modules/ration_glj/facade/ration_coe_facade.js
  22. 11 0
      modules/ration_repository/models/coe.js
  23. 12 1
      public/counter/counter.js
  24. 20 0
      public/web/id_tree.js
  25. 20 0
      public/web/tree_sheet/tree_sheet_controller.js
  26. 20 1
      web/building_saas/complementary_ration_lib/html/anzhuang.html
  27. 60 10
      web/building_saas/complementary_ration_lib/html/dinge.html
  28. 3 0
      web/building_saas/complementary_ration_lib/html/fuzhu.html
  29. 3 0
      web/building_saas/complementary_ration_lib/html/gongliao.html
  30. 476 42
      web/building_saas/complementary_ration_lib/js/coe.js
  31. 1 0
      web/building_saas/complementary_ration_lib/js/gljSelect.js
  32. 61 13
      web/building_saas/complementary_ration_lib/js/global.js
  33. 1007 39
      web/building_saas/complementary_ration_lib/js/installation.js
  34. 145 152
      web/building_saas/complementary_ration_lib/js/ration.js
  35. 6 15
      web/building_saas/complementary_ration_lib/js/ration_assist.js
  36. 314 223
      web/building_saas/complementary_ration_lib/js/ration_coe.js
  37. 62 5
      web/building_saas/complementary_ration_lib/js/ration_glj.js
  38. 4 19
      web/building_saas/complementary_ration_lib/js/ration_installation.js
  39. 8 19
      web/building_saas/complementary_ration_lib/js/repository_glj.js
  40. 238 92
      web/building_saas/complementary_ration_lib/js/section_tree.js
  41. 1 0
      web/building_saas/main/js/controllers/project_controller.js
  42. 2 0
      web/building_saas/main/js/models/ration_coe.js
  43. 10 6
      web/building_saas/main/js/views/project_view.js
  44. 19 4
      web/building_saas/main/js/views/std_ration_lib.js
  45. 2 1
      web/common/html/header.html

+ 1 - 0
config/gulpConfig.js

@@ -185,6 +185,7 @@ module.exports = {
         'lib/jquery-contextmenu/jquery.contextMenu.css',
     ],
     compleRation_ration_jspaths:[
+        '/public/web/uuid.js',
         'lib/jquery-contextmenu/jquery.contextMenu.min.js',
         'lib/jquery-contextmenu/jquery.ui.position.js',
         'lib/ztree/jquery.ztree.core.js',

+ 16 - 8
modules/all_models/compleRation_coe.js

@@ -8,24 +8,32 @@
  * @version
  */
 
-/*import mongoose from 'mongoose';
+/*
+* 补充定额库用户新增子目换算
+* 用户ID与费用定额ID绑定子目换算
+* */
+
+import mongoose from 'mongoose';
+const deleteSchema = require('../all_schemas/delete_schema');
 const Schema = mongoose.Schema;
 const coeSchema = new Schema({
-    coeType: String,                // 系数类型,指作用范围:
-                                    // 单个(如:111量0.001)、人工类、材料类、机械类、全部(如:定额×0.925)。
-    gljID: Number,                  // 要调整的工料机ID(当coeType=0时有效)
+    coeType: String,                // 系数类型
+    gljCode: String,                //要调整的人材机编码
+    gljName: String,
     operator: String,               // 运算符(*、+、-、=)
     amount: String,                 // 调整的量
     _id: false
 });
 
 const coeListSchema = new Schema({
-    libID: Number,                      // 所属定额定ID
-    ID: Number,                         // 系数ID(流水号ID)
+    userId: String,
+    compilationId: String,
+    ID: Number,
     serialNo: Number,                  //编号
     name: String,                       // 名称
     content: String,                    // 说明
-    coes: [coeSchema]
+    coes: [coeSchema],
+    deleteInfo: deleteSchema
 }, {versionKey: false});
 
-mongoose.model('std_ration_lib_coe_list', coeListSchema, 'std_ration_lib_coe_list');*/
+mongoose.model('complementary_ration_coe_list', coeListSchema, 'complementary_ration_coe_list');

+ 30 - 0
modules/all_models/compleRation_installFeeItem.js

@@ -0,0 +1,30 @@
+'use strict';
+
+/**
+ *
+ *
+ * @author Zhong
+ * @date 2018/10/23
+ * @version
+ */
+
+/*
+* 补充定额库用户新增安装增加费费用项
+*
+* */
+const mongoose = require('mongoose');
+const Schema = mongoose.Schema;
+const deleteSchema = require('../all_schemas/delete_schema');
+//补充安装增加费-费用项
+const installFeeItemSchema = new Schema({
+    userId: String,
+    compilationId: String,
+    ID: String,
+    feeItem: String, //费用项
+    feeType: String, //费用类型
+    position: String, //记取位置
+    section: [],
+    deleteInfo: deleteSchema
+}, {versionKey: false});
+
+mongoose.model('complementary_ration_installation', installFeeItemSchema, 'complementary_ration_installation');

+ 43 - 0
modules/all_models/compleRation_installSection.js

@@ -0,0 +1,43 @@
+'use strict';
+
+/**
+ *
+ *
+ * @author Zhong
+ * @date 2018/10/23
+ * @version
+ */
+
+/*
+* 补充定额库用户新增安装增加费分册章节
+*
+*
+* */
+
+const mongoose = require('mongoose');
+const Schema = mongoose.Schema;
+const deleteSchema = require('../all_schemas/delete_schema');
+//安装增加费-费用规则
+const feeRuleSchema = new Schema({
+    ID: String,
+    code: String,
+    rule: String,
+    base: String,
+    feeRate: Number,
+    labour: Number,
+    material: Number,
+    machine: Number
+});
+
+//补充安装增加费-分册章节
+const installSectionSchema = new Schema({
+    userId: String,
+    compilationId: String,
+    ID: String,
+    feeItemId: String,
+    name: String,
+    feeRule: [feeRuleSchema],
+    deleteInfo: deleteSchema
+}, {versionKey: false});
+
+mongoose.model('complementary_ration_installationSection', installSectionSchema, 'complementary_ration_installationSection');

+ 1 - 1
modules/all_models/compleRation_ration.js

@@ -46,7 +46,7 @@ const compleRationSchema = new Schema({
     materialPrice: String,
     machinePrice: String,
     basePrice: String,
-    sectionId: Number,
+    sectionId: String,
     caption: String,
     feeType: Number,
     jobContent: String,

+ 11 - 6
modules/all_models/compleRation_section.js

@@ -12,15 +12,20 @@ const compleRationSectionTreeSchema = new Schema({
     //编办
     compilationId: String,
     //标准定额库
-    rationRepId: Number,
+    //rationRepId: Number,
     //名称
     name: String,
     //是否是同层第一个节点
-    isFirst: Boolean,
-    ID: Number,
-    NextSiblingID: Number,
-    ParentID: Number,
-    deleteInfo: deleteSchema
+   // isFirst: Boolean,
+    ID: String,
+    NextSiblingID: String,
+    ParentID: String,
+    deleteInfo: deleteSchema,
+    //以下预留数据,以后开放可用
+    explanation: String,//说明
+    ruleText: String,//计算规则,
+    jobContentSituation: String,//工作内容适用情况,ALL适用本项全部定额,PARTIAL适用本项部分定额
+    annotationSituation: String,//附注适用情况,ALL适用本项全部定额,PARTIAL适用本项部分定额
 }, {versionKey: false});
 
 mongoose.model('complementary_ration_section_tree', compleRationSectionTreeSchema, 'complementary_ration_section_tree');

+ 9 - 0
modules/all_models/user.js

@@ -32,6 +32,10 @@ let upgrade = mongoose.Schema({
     remark:String//描述:广东办刘飞 2018-06-17 启用/关闭
 }, { _id: false })
 
+const userdList = mongoose.Schema({
+    compilationId: String
+}, {_id: false});
+
 // 表结构
 let schema = {
     ssoId: Number,
@@ -74,6 +78,11 @@ let schema = {
     user_type:{
         type:String,
         default:'normal'//  normal : 普通用户,test:测试用户
+    },
+    //使用过的费用定额,主要目的拷贝用户在该费用定额下的一些数据模板 eg:用户第一次进入该费用定额的补充定额库时,拷贝补充定额的章节树
+    used_list: {
+        type: [userdList],
+        default: []
     }
 };
 mongoose.model(collectionName, new Schema(schema, {versionKey: false}));

+ 94 - 27
modules/complementary_ration_lib/controllers/compleRationController.js

@@ -7,14 +7,21 @@ import CompleRationDao from '../models/compleRationModel';
 
 let compleRationDao = new CompleRationDao();
 let coeListDAO = require('../../ration_repository/models/coe');
+const coeFacade = require('../facades/compleCoeFacade');
+const installFacade = require('../facades/compleInstallFacade');
 let callback = function (req, res, err, msg, data) {
     res.json({error: err, message: msg, data: data})
-}
+};
+const libType = {
+    complementary: 0,
+    std: 1
+};
+
 
 class CompleRationController extends BaseController{
     getRationItems(req, res){
         let data = JSON.parse(req.body.data);
-        compleRationDao.getRationItems(req.session.sessionUser.id, data.rationRepId, data.sectionId, function (err, data) {
+        compleRationDao.getRationItems(data.sectionId, function (err, data) {
             callback(req, res, err, '', data);
         });
     }
@@ -78,39 +85,99 @@ class CompleRationController extends BaseController{
         });
     }
 
-    getRationGljItemsBySection(req, res){
-        let data = JSON.parse(req.body.data);
-        compleRationDao.getRationGljItemsBySection(req.session.sessionUser.id, data.sectionId, function (err, data) {
-            callback(req, res, err, '', data);
-        });
+    async getRationGljItemsBySection(req, res){
+        let data = JSON.parse(req.body.data),
+            rations = [];
+        try {
+            if (data.type === libType.complementary) {
+                rations = await compleRationDao.getCompleRationBySection(req.session.sessionUser.id, data.sectionId);
+            }  else {
+                rations = await compleRationDao.getRationGljItemsBySection(data.sectionId);
+            }
+            callback(req, res, 0, 'success', rations);
+        } catch (err) {
+            callback(req, res, 1, err, rations);
+        }
     }
 
-    getCoeList(req, res){
-        let data = JSON.parse(req.body.data);
-        coeListDAO.getCoesByLibID(data.libID, function (err, data) {
-            callback(req, res, err, '', data);
-        });
+    async getCoeList(req, res){
+        try{
+            let coeList = await coeFacade.getComplementaryCoes(req.session.sessionUser.id, req.session.sessionCompilation._id);
+            callback(req, res, 0, 'success', coeList);
+        } catch (err) {
+            callback(req, res, 1, err, null);
+        }
     }
 
-    getCoeItemsByIDs(req, res){
-        let data = JSON.parse(req.body.data);
-        coeListDAO.getCoeItemsByIDs(data, function (err, data) {
-            callback(req, res, err, '', data);
-        });
+    async saveCoeList(req, res){
+        try {
+            let data = JSON.parse(req.body.data);
+            let newDatas = await coeFacade.saveToCoeList(req.session.sessionUser.id, req.session.sessionCompilation._id, data);
+            callback(req, res, 0, 'success', newDatas);
+        } catch (err) {
+            console.log(err);
+            callback(req, res, 1, err, null);
+        }
     }
 
-    getCoeItemsByNos(req, res){
-        let data = JSON.parse(req.body.data);
-        coeListDAO.getCoeItemsByNos(data, function (err, data) {
-            callback(req, res, err, '', data);
-        });
+    async getCoeItemsByIDs(req, res){
+        try{
+            let data = JSON.parse(req.body.data);
+            let coeList = await coeFacade.getCoeItemsByIDs(data.coeIDs);
+            callback(req, res, 0, 'success', coeList);
+        } catch (err) {
+            callback(req, res, 1, err, null);
+        }
     }
 
-    getInstallation(req, res){
-        let data = JSON.parse(req.body.data);
-        compleRationDao.getInstallation(data.rationRepId, function (err, data) {
-            callback(req, res, err, '', data);
-        });
+    async getCoeItemsByNos(req, res){
+        try{
+            let data = JSON.parse(req.body.data);
+            let coeList = await coeFacade.getCoeItemsByNos(req.session.sessionUser.id, req.session.sessionCompilation._id, data.coeNos);
+            callback(req, res, 0, 'success', coeList);
+        } catch (err) {
+            console.log(err);
+            callback(req, res, 1, err, null);
+        }
+    }
+
+    async getInstallation(req, res){
+        try {
+            let installData = await installFacade.getInstallation(req.session.sessionUser.id, req.session.sessionCompilation._id);
+            callback(req, res, 0, 'success', installData);
+        } catch (err) {
+            callback(req, res, 1, err, null);
+        }
+    }
+
+    async updateFeeItem(req, res){
+        try {
+            let data = JSON.parse(req.body.data);
+            await installFacade.updateFeeItem(req.session.sessionUser.id, req.session.sessionCompilation._id, data.updateData);
+            callback(req, res, 0, 'success', null);
+        } catch (err) {
+            callback(req, res, 1, err, null);
+        }
+    }
+
+    async updateInstallSection(req, res){
+        try {
+            let data = JSON.parse(req.body.data);
+            await installFacade.updateSection(req.session.sessionUser.id, req.session.sessionCompilation._id, data.updateData);
+            callback(req, res, 0, 'success', null);
+        } catch (err) {
+            callback(req, res, 1, err, null);
+        }
+    }
+
+    async batchUpdateInst(req, res){
+        try {
+            let data = JSON.parse(req.body.data);
+            await installFacade.batchUpdateInst(data.rationSection, data.inst);
+            callback(req, res, 0, 'success', null);
+        } catch (err) {
+            callback(req, res, 1, err, null);
+        }
     }
 }
 

+ 1 - 1
modules/complementary_ration_lib/controllers/compleSectionTreeController.js

@@ -20,7 +20,7 @@ class CompleSectionTreeController extends BaseController{
 
     getRationTree(req, res){
         let data = JSON.parse(req.body.data);
-        sectionTreeDao.getRationTree(req.session.sessionUser.id, data.rationRepId, function (err, data) {
+        sectionTreeDao.getRationTree(req.session.sessionUser.id, req.session.sessionCompilation._id, data.rationRepId, data.type, function (err, data) {
             callback(req, res, err, '', data);
         });
     }

+ 43 - 16
modules/complementary_ration_lib/controllers/compleViewController.js

@@ -4,6 +4,7 @@
 
 import BaseController from '../../common/base/base_controller';
 import CompleViewModel from '../models/compleViewModel';
+import EngineeringLibModel from "../../users/models/engineering_lib_model";
 let config = require("../../../config/config.js");
 
 let compleViewModel = new CompleViewModel();
@@ -11,47 +12,73 @@ let callback = function (req, res, err, msg, data) {
     res.json({error: err, message: msg, data: data});
 };
 
+async function getGljLibId(sessionCompilation) {
+    let gljLibId = null,
+        rationValuation = sessionCompilation.ration_valuation,
+        billValuation = sessionCompilation.bill_valuation,
+        engineeringLibModel = new EngineeringLibModel(),
+        valuationIDs = [] ;
+    for(let r of rationValuation){//{ "glj_lib.0": {$exists:1} }
+        if(r.id){
+            valuationIDs.push(r.id);
+        }
+    }
+    for(let b of billValuation){
+        if(b.id){
+            valuationIDs.push(b.id);
+        }
+    }
+    if(valuationIDs.length > 0){
+        let engineeringInfo = await engineeringLibModel.findDataByCondition({'valuationID': {"$in": valuationIDs},"glj_lib.0": {$exists:1}});//数组大于0
+        gljLibId = engineeringInfo.glj_lib.length > 0 && typeof engineeringInfo.glj_lib !== 'undefined' ? engineeringInfo.glj_lib[0].id : null;
+    }
+    return gljLibId;
+}
+
 class CompleViewController extends BaseController{
-    redirectRation(req, res){
-        const repId = req.query.repository;
-        const redirectGlj = `/complementaryRation/glj?repository=${repId}`;
-        const redirectCoe = `/complementaryRation/coe?repository=${repId}`;
-        const redirectInstallation = `/complementaryRation/installation?repository=${repId}`;
+    async redirectRation(req, res){
+        const gljLibId = await getGljLibId(req.session.sessionCompilation);
+        const redirectGlj = `/complementaryRation/glj`;
+        const redirectCoe = `/complementaryRation/coe`;
+        const redirectInstallation = `/complementaryRation/installation`;
         res.render('building_saas/complementary_ration_lib/html/dinge.html', {
             userID: req.session.sessionUser.id,
             redirectGlj: redirectGlj,
             redirectCoe: redirectCoe,
             redirectInstallation: redirectInstallation,
+            gljLibId: gljLibId,
             versionName: req.session.sessionCompilation.name + '免费版',
             LicenseKey:config.getLicenseKey(process.env.NODE_ENV)
         });
     }
 
-    redirectGljList(req, res){
-        const repId = req.query.repository;
-        const redirectRation = `/complementaryRation/ration?repository=${repId}`;
-        const redirectCoe = `/complementaryRation/coe?repository=${repId}`;
-        const redirectInstallation = `/complementaryRation/installation?repository=${repId}`;
+    async redirectGljList(req, res){
+        const gljLibId = await getGljLibId(req.session.sessionCompilation);
+        const redirectRation = `/complementaryRation/ration`;
+        const redirectCoe = `/complementaryRation/coe`;
+        const redirectInstallation = `/complementaryRation/installation`;
         res.render('building_saas/complementary_ration_lib/html/gongliao.html', {
             userID: req.session.sessionUser.id,
             redirectRation: redirectRation,
             redirectCoe: redirectCoe,
             redirectInstallation: redirectInstallation,
+            gljLibId: gljLibId,
             versionName: req.session.sessionCompilation.name + '免费版',
             LicenseKey:config.getLicenseKey(process.env.NODE_ENV)
         });
     }
 
-    redirectCoeList(req, res){
-        const repId = req.query.repository;
-        const redirectRation = `/complementaryRation/ration?repository=${repId}`;
-        const redirectGlj = `/complementaryRation/glj?repository=${repId}`;
-        const redirectInstallation = `/complementaryRation/installation?repository=${repId}`;
+    async redirectCoeList(req, res){
+        const gljLibId = await getGljLibId(req.session.sessionCompilation);
+        const redirectRation = `/complementaryRation/ration`;
+        const redirectGlj = `/complementaryRation/glj`;
+        const redirectInstallation = `/complementaryRation/installation`;
         res.render('building_saas/complementary_ration_lib/html/fuzhu.html', {
             userID: req.session.sessionUser.id,
             redirectRation: redirectRation,
             redirectGlj: redirectGlj,
             redirectInstallation: redirectInstallation,
+            gljLibId: gljLibId,
             versionName: req.session.sessionCompilation.name + '免费版',
             LicenseKey:config.getLicenseKey(process.env.NODE_ENV)
         });
@@ -59,7 +86,7 @@ class CompleViewController extends BaseController{
 
     redirectInstallation(req, res){
         const repId = req.query.repository;
-        const redirectRation = `/complementaryRation/ration?repository=${repId}`;
+        const redirectRation = `/complementaryRation/ration`;
         const redirectGlj = `/complementaryRation/glj?repository=${repId}`;
         const redirectCoe = `/complementaryRation/coe?repository=${repId}`;
         res.render('building_saas/complementary_ration_lib/html/anzhuang.html', {

+ 2 - 2
modules/complementary_ration_lib/controllers/searchController.js

@@ -13,14 +13,14 @@ let callback = function (req, res, err, message, data) {
 class SearchController extends BaseController{
     getRationItem(req, res){
         let data = JSON.parse(req.body.data);
-        searchDao.getRationItem(req.session.sessionUser.id, data.rationRepIds, data.code, null, function (err, data) {
+        searchDao.getRationItem(req.session.sessionUser.id, req.session.sessionCompilation._id, data.rationRepIds, data.code, null, function (err, data) {
             callback(req, res, err, '', data);
         });
     }
 
     findRation(req, res){
         let data = JSON.parse(req.body.data);
-        searchDao.findRation(req.session.sessionUser.id, data.rationRepId, data.keyword, function (err, data) {
+        searchDao.findRation(req.session.sessionUser.id, req.session.sessionCompilation._id, data.rationRepId, data.keyword, function (err, data) {
             callback(req, res, err, '', data);
         });
     }

+ 99 - 0
modules/complementary_ration_lib/facades/compleCoeFacade.js

@@ -0,0 +1,99 @@
+'use strict';
+
+/**
+ *
+ *
+ * @author Zhong
+ * @date 2018/10/25
+ * @version
+ */
+
+module.exports = {
+    getComplementaryCoes,
+    getCoeItemsByIDs,
+    getCoeItemsByNos,
+    saveToCoeList,
+};
+
+const mongoose = require("mongoose");
+const counter = require('../../../public/counter/counter');
+const compleCoeModel = mongoose.model('complementary_ration_coe_list');
+const async = require('async');
+const deleteQuery = [{deleteInfo: null}, {'deleteInfo.deleted': false}];
+
+//获取用户总的补充子目换算
+async function getComplementaryCoes(userId, compilationId) {
+    let coeData =  await compleCoeModel.find({userId: userId, compilationId: compilationId, $or: deleteQuery});
+    return coeData;
+}
+
+
+//补充子目换算增删改
+async function saveToCoeList(userId, compilationId, data, callback) {
+    let bulks = [],
+        newDatas = [];
+    if (data.addArr && data.addArr.length > 0) {
+        let insertOprs = await getInsertBulk(userId, compilationId, data.addArr);
+        bulks = bulks.concat(insertOprs.insertBulk);
+        newDatas = insertOprs.newDatas;
+    }
+    if (data.updateArr && data.updateArr.length > 0) {
+        bulks = bulks.concat(getUpdateBulk(data.updateArr));
+    }
+    if (data.deleteArr && data.deleteArr.length > 0) {
+        let deleteObj = {
+            deleted: true,
+            deleteDateTime: new Date(),
+            deleteBy: userId
+        };
+        for (let delData of data.deleteArr) {
+            delData.deleteInfo = deleteObj
+        }
+        bulks = bulks.concat(getUpdateBulk(data.deleteArr));
+    }
+    if (bulks.length > 0) {
+        await compleCoeModel.bulkWrite(bulks);
+    }
+    return newDatas;
+}
+
+async function getInsertBulk(userId, compilationId, addArr) {
+    let insertBulk = [],
+        newDatas = [];
+    let counterResult = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.complementaryCoeList, addArr.length);
+    let maxId = counterResult.sequence_value;
+    for (let insertData of addArr) {
+        insertData.userId = userId;
+        insertData.compilationId = compilationId;
+        insertData.ID = (maxId - (addArr.length - 1) + addArr.indexOf(insertData));
+        insertData.coes = [];
+        newDatas.push(insertData);
+        insertBulk.push({insertOne: {document: insertData}});
+    }
+    return {insertBulk, newDatas};
+}
+
+function getUpdateBulk(updateArr) {
+    let updateBulk = [],
+        updateFields = ['name', 'content', 'coes', 'deleteInfo'];
+    for (let updateData of updateArr) {
+        let needSet = {};
+        for (let attr in updateData){
+            if (updateFields.includes(attr)){
+                needSet[attr] = updateData[attr];
+            }
+        }
+        updateBulk.push({updateOne:{filter: {ID: updateData.ID}, update: {$set: needSet}}});
+    }
+    return updateBulk;
+}
+//根据序号获取子目换算,插入子目换算时用
+async function getCoeItemsByNos(userId, compilationId, serialNos) {
+    return await compleCoeModel.find({userId: userId, compilationId: compilationId, serialNo: {$in: serialNos}}, '-_id ID serialNo name content');
+}
+
+//根据ID获取子目换算,获取定额子目换算用
+async function getCoeItemsByIDs(coeIds) {
+    return await compleCoeModel.find({ID: {$in: coeIds}}, '-_id ID serialNo name content');
+}
+

+ 91 - 0
modules/complementary_ration_lib/facades/compleInstallFacade.js

@@ -0,0 +1,91 @@
+'use strict';
+
+/**
+ *
+ *
+ * @author Zhong
+ * @date 2018/10/25
+ * @version
+ */
+
+module.exports = {
+    getInstallation,
+    updateFeeItem,
+    updateSection,
+    batchUpdateInst,
+};
+
+const mongoose = require("mongoose");
+const counter = require('../../../public/counter/counter');
+const async = require('async');
+const deleteQuery = [{deleteInfo: null}, {'deleteInfo.deleted': false}];
+const complefeeItemModel = mongoose.model('complementary_ration_installation');
+const compleSectionModel = mongoose.model('complementary_ration_installationSection');
+const compleRationModel = mongoose.model('complementary_ration_items');
+
+async function getInstallation(userId, compilationId){
+        let feeItems = await complefeeItemModel.find({userId: userId, compilationId: compilationId, $or: deleteQuery});
+        for (let feeItem of feeItems) {
+            let sids = [];
+            for (let sec of feeItem.section) {
+                sids.push(sec.ID);
+            }
+            if (sids.length > 0) {
+                let sections = await compleSectionModel.find({ID: {$in: sids}, $or: deleteQuery});
+                feeItem._doc.section = sections;
+            }
+        }
+        return feeItems;
+}
+
+//更新费用项
+async function updateFeeItem(userId, compilationId, updateData){
+    for (let data of updateData) {
+        if (data.updateType === 'new') {
+            data.updateData.userId = userId;
+            data.updateData.compilationId = compilationId;
+            await complefeeItemModel.create(data.updateData);
+        } else if (data.updateType === 'update' && !data.updateData.deleted) {
+            await complefeeItemModel.update({ID: data.updateData.ID}, data.updateData);
+        } else {
+            let deleteInfo = {
+                deleted: true,
+                deleteDateTime: new Date(),
+                deleteBy: userId
+            };
+            data.updateData.deleteInfo = deleteInfo;
+            delete data.updateData.deleted;
+            await complefeeItemModel.remove({ID: data.updateData.ID});
+        }
+    }
+}
+
+//更新分册章节
+async function updateSection(userId, compilationId, updateData){
+    for (let data of updateData) {
+        if (data.updateType === 'new') {
+            data.updateData.userId = userId;
+            data.updateData.compilationId = compilationId;
+            await compleSectionModel.create(data.updateData);
+        } else if (data.updateType === 'update' && !data.updateData.deleted) {
+            await compleSectionModel.update({ID: data.updateData.ID}, data.updateData);
+        } else {
+            let deleteInfo = {
+                deleted: true,
+                deleteDateTime: new Date(),
+                deleteBy: userId
+            };
+            data.updateData.deleteInfo = deleteInfo;
+            delete data.updateData.deleted;
+            await compleSectionModel.remove({ID: data.updateData.ID});
+        }
+    }
+}
+
+//批量关联至定额(选择某一章节)
+async function batchUpdateInst(rationSection, inst){
+    for (let sectionId of rationSection) {
+        await compleRationModel.update({sectionId: sectionId, $or: deleteQuery},
+            {$addToSet: {rationInstList: {feeItemId: inst.feeItemId, sectionId: inst.sectionId}}}, {multi: true});
+    }
+}

+ 106 - 82
modules/complementary_ration_lib/models/compleRationModel.js

@@ -34,19 +34,10 @@ class CompleRatoinDao {
         }
     }
 
-    async getRationItems(userID, rationRepId, sectionId, callback){
+    async getRationItems(sectionId, callback){
         try{
-            let stdRations = await stdRationModel.find({rationRepId: rationRepId, sectionId: sectionId, $or: [{isDeleted: null}, {isDeleted: false}]});
-            //mark std
-            for(let i = 0, len = stdRations.length; i < len; i++){
-                stdRations[i]._doc.type = 'std';
-            }
-            let compleRations = await compleRationModel.find({userId: userID, rationRepId: rationRepId, sectionId: sectionId, deleteInfo: null});
-            //mark complementary
-            for(let i = 0, len = compleRations.length; i < len; i++){
-                compleRations[i]._doc.type = 'complementary';
-            }
-            callback(0, stdRations.concat(compleRations));
+            let compleRations = await compleRationModel.find({sectionId: sectionId, deleteInfo: null});
+            callback(0, compleRations);
         }
         catch(err){
             callback(err, null);
@@ -138,83 +129,116 @@ class CompleRatoinDao {
             callback(err, null);
         }
     }
-    //造价书定额库
-    async getRationGljItemsBySection(userId, sectionId, callback){
-        try{
-            const perHintHeight = 17.2;
-            let stdRations = await stdRationModel.find({sectionId: sectionId, $or: [{isDeleted: null}, {isDeleted: false}]});
-            for(let ration of stdRations){
-                ration._doc.type = 'std';
+
+    //根据章节树获取补充定额
+    async getCompleRationBySection(userId, sectionId) {
+        const deleteQuery = [{deleteInfo: null}, {'deleteInfo.deleted': false}];
+        let compleRations = await compleRationModel.find({sectionId: sectionId, $or: deleteQuery});
+        for(let ration of compleRations){
+            ration._doc.type = 'complementary';
+            let hintsArr = [];
+            let stdGljIds = [],
+                comGljIds = [],
+                stdGljs = [],
+                comGljs = [];
+            let gljAmtMapping = {};
+            for(let rationGlj of ration.rationGljList){
+                gljAmtMapping[rationGlj.gljId] = rationGlj.consumeAmt;
+                if(!isDef(rationGlj.type) || rationGlj.type === 'std'){
+                    stdGljIds.push(rationGlj.gljId);
+                }
+                else {
+                    comGljIds.push(rationGlj.gljId);
+                }
             }
-            let compleRations = await compleRationModel.find({userId: userId, sectionId: sectionId, deleteInfo: null});
-            for(let ration of compleRations){
-                ration._doc.type = 'complementary';
+            if(stdGljIds.length > 0) {
+                stdGljs = await stdGljModel.find({ID: {$in: stdGljIds}});
             }
-            let rations = stdRations.concat(compleRations);
-            rations.sort(function (a, b) {
-                let rst = 0;
-                if(a.code > b.code){
-                    rst = 1;
-                }
-                else if(a.code < b.code){
-                    rst = -1;
+            if(comGljIds.length > 0) {
+                comGljs = await complementaryGljModel.find({userId: userId, ID: {$in: comGljIds}});
+            }
+            let gljDatas = stdGljs.concat(comGljs);
+            gljDatas.sort(function (a, b) {
+                let aV = a.gljType + a.code,
+                    bV = b.gljType + b.code;
+                if(aV > bV) {
+                    return 1;
+                } else if (aV < bV) {
+                    return -1;
                 }
-                return rst;
+                return 0;
             });
-            for(let ration of rations){
-                let hintsArr = [];
-                let stdGljIds = [],
-                    comGljIds = [],
-                    stdGljs = [],
-                    comGljs = [];
-                let gljAmtMapping = {};
-                for(let rationGlj of ration.rationGljList){
-                    gljAmtMapping[rationGlj.gljId] = rationGlj.consumeAmt;
-                    if(!isDef(rationGlj.type) || rationGlj.type === 'std'){
-                        stdGljIds.push(rationGlj.gljId);
-                    }
-                    else {
-                        comGljIds.push(rationGlj.gljId);
-                    }
-                }
-                if(stdGljIds.length > 0) {
-                    stdGljs = await stdGljModel.find({ID: {$in: stdGljIds}});
-                }
-                if(comGljIds.length > 0) {
-                    comGljs = await complementaryGljModel.find({userId: userId, ID: {$in: comGljIds}});
-                }
-                let gljDatas = stdGljs.concat(comGljs);
-                gljDatas.sort(function (a, b) {
-                    let aV = a.gljType + a.code,
-                        bV = b.gljType + b.code;
-                    if(aV > bV) {
-                        return 1;
-                    } else if (aV < bV) {
-                        return -1;
-                    }
-                    return 0;
-                });
-                for(let glj of gljDatas){
-                    hintsArr.push(` ${glj.code} ${glj.name}${glj.specs ? '&nbsp;&nbsp;&nbsp;' + glj.specs : ''}&nbsp;&nbsp&nbsp;${glj.unit}&nbsp;&nbsp;&nbsp;${gljAmtMapping[glj.ID]}`)
-                }
-                hintsArr.push(`基价 元 ${ration.basePrice}`);
-                if(ration.jobContent && ration.jobContent.toString().trim() !== ''){
-                    hintsArr.push(`工作内容:`);
-                    hintsArr = hintsArr.concat(ration.jobContent.split('\n'));
-                }
-                if(ration.annotation && ration.annotation.toString().trim() !== ''){
-                    hintsArr.push(`附注:`);
-                    hintsArr = hintsArr.concat(ration.annotation.split('\n'));
-                }
-                ration._doc.hint = hintsArr.join('<br>');
-               // ration._doc.hintHeight = hintsArr.length * perHintHeight;//控制定额库悬浮提示位置
+            for(let glj of gljDatas){
+                hintsArr.push(` ${glj.code} ${glj.name}${glj.specs ? '&nbsp;&nbsp;&nbsp;' + glj.specs : ''}&nbsp;&nbsp&nbsp;${glj.unit}&nbsp;&nbsp;&nbsp;${gljAmtMapping[glj.ID]}`)
             }
-            callback(0, rations);
+            hintsArr.push(`基价 元 ${ration.basePrice}`);
+            if(ration.jobContent && ration.jobContent.toString().trim() !== ''){
+                hintsArr.push(`工作内容:`);
+                hintsArr = hintsArr.concat(ration.jobContent.split('\n'));
+            }
+            if(ration.annotation && ration.annotation.toString().trim() !== ''){
+                hintsArr.push(`附注:`);
+                hintsArr = hintsArr.concat(ration.annotation.split('\n'));
+            }
+            ration._doc.hint = hintsArr.join('<br>');
         }
-        catch(err){
-            console.log(err);
-            callback(err, null);
+        return compleRations;
+    }
+
+    //造价书定额库 根据章节树过去标准定额
+    async getRationGljItemsBySection(sectionId, callback){
+        let stdRations = await stdRationModel.find({sectionId: sectionId});
+        for(let ration of stdRations){
+            ration._doc.type = 'std';
+        }
+        stdRations.sort(function (a, b) {
+            let rst = 0;
+            if(a.code > b.code){
+                rst = 1;
+            }
+            else if(a.code < b.code){
+                rst = -1;
+            }
+            return rst;
+        });
+        for(let ration of stdRations){
+            let hintsArr = [];
+            let stdGljIds = [],
+                stdGljs = [];
+            let gljAmtMapping = {};
+            for(let rationGlj of ration.rationGljList){
+                gljAmtMapping[rationGlj.gljId] = rationGlj.consumeAmt;
+                stdGljIds.push(rationGlj.gljId);
+            }
+            if(stdGljIds.length > 0) {
+                stdGljs = await stdGljModel.find({ID: {$in: stdGljIds}});
+            }
+            let gljDatas = stdGljs;
+            gljDatas.sort(function (a, b) {
+                let aV = a.gljType + a.code,
+                    bV = b.gljType + b.code;
+                if(aV > bV) {
+                    return 1;
+                } else if (aV < bV) {
+                    return -1;
+                }
+                return 0;
+            });
+            for(let glj of gljDatas){
+                hintsArr.push(` ${glj.code} ${glj.name}${glj.specs ? '&nbsp;&nbsp;&nbsp;' + glj.specs : ''}&nbsp;&nbsp&nbsp;${glj.unit}&nbsp;&nbsp;&nbsp;${gljAmtMapping[glj.ID]}`)
+            }
+            hintsArr.push(`基价 元 ${ration.basePrice}`);
+            if(ration.jobContent && ration.jobContent.toString().trim() !== ''){
+                hintsArr.push(`工作内容:`);
+                hintsArr = hintsArr.concat(ration.jobContent.split('\n'));
+            }
+            if(ration.annotation && ration.annotation.toString().trim() !== ''){
+                hintsArr.push(`附注:`);
+                hintsArr = hintsArr.concat(ration.annotation.split('\n'));
+            }
+            ration._doc.hint = hintsArr.join('<br>');
         }
+        return stdRations;
     }
 
     updateRationBasePrc(userID, basePrcArr, callback){

+ 35 - 16
modules/complementary_ration_lib/models/searchModel.js

@@ -9,25 +9,28 @@ const compleRationSectionTreeModel = mongoose.model('complementary_ration_sectio
 let stdSectionTreeModel = require ('../../ration_repository/models/ration_section_tree').Model;
 let stdRationModel = require ('../../ration_repository/models/ration_item').Model;
 
+const compleRationLib = 'compleRationLib';
+
 class SearchDao{
-    async getRationItem(userId, rationRepIds, code, ID, callback){
+    async getRationItem(userId, compilationId, rationRepIds, code, ID, callback){
         let ration = null;
         try{
+            if(rationRepIds.includes(compleRationLib)) {
+                rationRepIds.splice(rationRepIds.indexOf(compleRationLib), 1);
+            }
             let stdQuery = {rationRepId: {$in: rationRepIds}, code: code, $or: [{isDeleted: null}, {isDeleted: false}]};
             if(ID){
                 stdQuery = {ID: ID, $or: [{isDeleted: null}, {isDeleted: false}]};
             }
-            //let stdRation = await stdRationModel.findOne({rationRepId: {$in: rationRepIds}, code: code, $or: [{isDeleted: null}, {isDeleted: false}]});
             let stdRation = await stdRationModel.findOne(stdQuery);
             if(isDef(stdRation)){
                 ration = stdRation._doc;
                 ration.type = 'std';
             } else{
-                let compleQuery = {userId: userId, rationRepId: {$in: rationRepIds}, code: code, deleteInfo: null};
+                let compleQuery = {userId: userId, compilationId: compilationId, code: code, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]};
                 if(ID){
-                    compleQuery = {ID: ID, deleteInfo: null};
+                    compleQuery.ID = ID;
                 }
-                //let compleRation = await compleRationModel.findOne({userId: userId, rationRepId: {$in: rationRepIds}, code: code, deleteInfo: null});
                 let compleRation = await compleRationModel.findOne(compleQuery);
                 if(isDef(compleRation)){
                     ration = compleRation._doc;
@@ -35,12 +38,13 @@ class SearchDao{
                 }
             }
             if(isDef(ration)){
-                let stdChapter = await stdSectionTreeModel.findOne({rationRepId: ration.rationRepId, ID: ration.sectionId, $or: [{isDeleted: null}, {isDeleted: false}]});
-                if(isDef(stdChapter)){
-                    ration.chapter = stdChapter._doc;
-                }
-                else{
-                    let compleChapter = await compleRationSectionTreeModel.findOne({userId: userId, ID: ration.sectionId, deleteInfo: null});
+                if (ration.type === 'std') {
+                    let stdChapter = await stdSectionTreeModel.findOne({rationRepId: ration.rationRepId, ID: ration.sectionId, $or: [{isDeleted: null}, {isDeleted: false}]});
+                    if(isDef(stdChapter)){
+                        ration.chapter = stdChapter._doc;
+                    }
+                } else {
+                    let compleChapter = await compleRationSectionTreeModel.findOne({ID: ration.sectionId, $or: [{isDeleted: null}, {isDeleted: false}]});
                     if(isDef(compleChapter)){
                         ration.chapter = compleChapter._doc;
                     }
@@ -58,8 +62,14 @@ class SearchDao{
         return ration;
     }
 
-    async findRation(userId, rationRepId, keyword, callback){
+    async findRation(userId, compilationId, rationRepId, keyword, callback){
         try{
+            //是否需要查找补充定额
+            let findCompleRtion = rationRepId.length > 0 && rationRepId.includes(compleRationLib) ? true : false;
+            //剔除补充定额库id
+            if (rationRepId.includes(compleRationLib)) {
+                rationRepId.splice(rationRepId.indexOf(compleRationLib), 1);
+            }
             let filter = {
                 'rationRepId': {$in: rationRepId},
                 '$and': [{
@@ -68,20 +78,29 @@ class SearchDao{
                     '$or': [{'isDeleted': {"$exists":false}}, {'isDeleted': null}, {'isDeleted': false}, {deleteInfo: null}]
                 }]
             };
+
             let stdGljIds = [],
                 comGljIds = [];
-            let stdRations = await stdRationModel.find(filter);
+            let stdRations = rationRepId.length === 0 ? [] : await stdRationModel.find(filter);
             for(let i = 0, len = stdRations.length; i < len; i++){
                 stdRations[i]._doc.type = 'std';
                 for(let glj of stdRations[i].rationGljList){
                     stdGljIds.push(glj.gljId);
                 }
             }
-            filter.userId = userId;
-            let compleRations = await compleRationModel.find(filter);
+            let compleFilter = {
+                userId: userId,
+                compilationId: compilationId,
+                '$and': [{
+                    '$or': [{'code': {'$regex': keyword, $options: '$i'}}, {'name': {'$regex': keyword, $options: '$i'}}]
+                }, {
+                    '$or': [{deleteInfo: null}, {'deleteInfo.deleted': false}]
+                }]
+            };
+            let compleRations = findCompleRtion ? await compleRationModel.find(compleFilter) : [];
             for(let i = 0, len = compleRations.length; i <len; i++){
                 compleRations[i]._doc.type = 'complementary';
-                for(let glj of stdRations[i].rationGljList){
+                for(let glj of compleRations[i].rationGljList){
                     if(glj.type === 'std'){
                         stdGljIds.push(glj.gljId);
                     }

+ 49 - 2
modules/complementary_ration_lib/models/sectionTreeModel.js

@@ -7,8 +7,36 @@ const compleRationSectionTreeModel = mongoose.model('complementary_ration_sectio
 const compleRationModel = mongoose.model('complementary_ration_items');
 let counter = require('../../../public/counter/counter');
 let stdSectionTreeModel = require ('../../ration_repository/models/ration_section_tree').Model;
+const uuidV1 = require('uuid/v1');
+const sectionTemplateModel = mongoose.model('complementary_ration_section_templates');
 
 class SectionTreeDao {
+    //从补充定额章节树模板中拷贝数据到用户的补充定额章节树中
+    async copyDataFromTemplate(userId, compilationId){
+        let templateData = await sectionTemplateModel.find({compilationId: compilationId});
+        if (templateData.length > 0) {
+            let insertDatas = [],
+                uuidMapping = {};
+            //将ID替换成UUID
+            for (let temData of templateData) {
+                uuidMapping[temData.ID] = uuidV1();
+            }
+            for(let temData of templateData) {
+                let insertD = {
+                    userId: userId,
+                    compilationId: compilationId,
+                    name: temData.name,
+                    ID: uuidMapping[temData.ID],
+                    ParentID: uuidMapping[temData.ParentID] || -1,
+                    NextSiblingID: uuidMapping[temData.NextSiblingID] || -1,
+                };
+                insertDatas.push(insertD);
+            }
+            //插入数据
+            await compleRationSectionTreeModel.insertMany(insertDatas);
+        }
+    }
+
     getNewTreeID(callback){
         counter.counterDAO.getIDAfterCount(counter.moduleName.rationTree, 1, function (err, result) {
             if(err){
@@ -20,9 +48,28 @@ class SectionTreeDao {
         });
 
     }
+    async getRationTree(userId, compilationId, rationRepId, type, callback) {
+        //区分要获取的是标准的数据还是补充的数据
+        const rationLibType = {
+            complementary: 0,
+            std: 1
+        };
+        try {
+            let treeData;
+            if (type === rationLibType.complementary) {
+                treeData = await compleRationSectionTreeModel.find({userId: userId, compilationId: compilationId, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]});
+            } else {
+                treeData = await stdSectionTreeModel.find({rationRepId: rationRepId});
+            }
+            callback(0, treeData);
+        } catch (err) {
+            console.log(err);
+            callback(1, null);
+        }
+    }
 
     //获取补充定额拼接章节树
-    async getRationTree(userID, rationRepId, callback){
+   /* async getRationTree(userID, rationRepId, callback){
         try{
             let stdSectionTree = await stdSectionTreeModel.find({rationRepId: rationRepId, $or: [{isDeleted: null}, {isDeleted: false}]});
             let compleSectionTree = await compleRationSectionTreeModel.find({userId: userID, rationRepId: rationRepId, deleteInfo: null});
@@ -63,7 +110,7 @@ class SectionTreeDao {
         catch (err){
             callback(err, null);
         }
-    }
+    }*/
 
     async updateSection(userID, compilationId, updateData, callback){
         try{

+ 4 - 0
modules/complementary_ration_lib/routes/routes.js

@@ -41,11 +41,15 @@ module.exports = function (app) {
     router.post('/getGljItemsByCodes', compleRationController.init, compleRationController.getGljItemsByCodes);
 
     router.post('/getCoeList', compleRationController.init, compleRationController.getCoeList);
+    router.post('/saveCoeList', compleRationController.init, compleRationController.saveCoeList);
     router.post('/getCoeItemsByIDs', compleRationController.init, compleRationController.getCoeItemsByIDs);
     router.post('/getCoeItemsByNos', compleRationController.init, compleRationController.getCoeItemsByNos);
 
     //安装增加费
     router.post('/getInstallation', compleRationController.init, compleRationController.getInstallation);
+    router.post('/updateFeeItem', compleRationController.init, compleRationController.updateFeeItem);
+    router.post('/updateInstallSection', compleRationController.init, compleRationController.updateInstallSection);
+    router.post('/batchUpdateInst', compleRationController.init, compleRationController.batchUpdateInst);
 
     //造价书定额库
     router.post('/getRationItem', searchController.init, searchController.getRationItem);

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

@@ -36,7 +36,7 @@ let controller = {
     getSameSectionRations:async function(req){//取同个章节相邻的定额
         let data = req.body.data;
         data = JSON.parse(data);
-        return await ration_facade.getSameSectionRations(data,req.session.sessionUser.id);
+        return await ration_facade.getSameSectionRations(data,req.session.sessionUser.id, req.session.sessionCompilation._id);
     }
 };
 

+ 19 - 10
modules/main/facade/ration_facade.js

@@ -20,6 +20,7 @@ let rationItemModel = mongoose.model("std_ration_lib_ration_items");
 let complementaryRationModel = mongoose.model('complementary_ration_items');
 
 let coeMolde = mongoose.model('std_ration_lib_coe_list');
+let compleCoeModel = mongoose.model('complementary_ration_coe_list');
 let _= require('lodash');
 const projectDao = require('../../pm/models/project_model').project;
 let projectModel = mongoose.model('projects');
@@ -37,7 +38,7 @@ async function addNewRation(data,compilation) {
     let startTime = +new Date();
     if(query){
         let searchDao = new SearchDao();
-        stdRation = await searchDao.getRationItem(query.userID,[query.rationRepId],query.code, query.ID);
+        stdRation = await searchDao.getRationItem(query.userID, compilation._id, [query.rationRepId],query.code, query.ID);
         //data.newData.code = query.code;
     }
     let stdRationTime = +new Date();
@@ -64,7 +65,7 @@ async function addMultiRation(datas,compilation) {
     return rst;
 }
 
-async function getSameSectionRations(data,userId){
+async function getSameSectionRations(data,userId,compilationId){
     //let userId
     //要先根据定额获取所属章节的ID
     let from = data.from;    //定额类型,是标准的还是用户定义的
@@ -75,14 +76,15 @@ async function getSameSectionRations(data,userId){
         let ration = await rationItemModel.findOne({rationRepId:libID,code:code},['sectionId']);
         sectionId = ration? ration.sectionId:null;
     }else {
-        let ration = await complementaryRationModel.findOne({userId:userId,code:code},['sectionId']);
+        let ration = await complementaryRationModel.findOne({userId:userId,compilationId: compilationId,code:code},['sectionId']);
         sectionId = ration?ration.sectionId:null;
     }
     if(sectionId){
-        //{
-        let stdRations = await rationItemModel.find({sectionId: sectionId});
-        let comRations = await complementaryRationModel.find({userId: userId, sectionId: sectionId});
-        rations = stdRations.concat(comRations);
+        if (from == 'std') {
+            rations = await rationItemModel.find({sectionId: sectionId});
+        } else {
+            rations = await complementaryRationModel.find({userId: userId, sectionId: sectionId});
+        }
         rations = _.sortBy(rations,'code');
     }
     return rations
@@ -153,7 +155,7 @@ async function replaceRations(userID,data,compilation) {
     let searchDao = new SearchDao();
     let recodes = [];
     for(let recode of data.nodeInfo){
-        let stdRation = await searchDao.getRationItem(userID,data.libIDs,recode.newCode, null);
+        let stdRation = await searchDao.getRationItem(userID,compilation._id,data.libIDs,recode.newCode, null);
         let newRecode = await replaceRation(recode,stdRation,data.defaultLibID,data.projectID,data.calQuantity,compilation);
         if(newRecode){
             recodes.push(newRecode);
@@ -237,7 +239,12 @@ async function addRationCoe(std,newRation,compilation) {
     let seq = 0;
     if(std.hasOwnProperty('rationCoeList')&&std.rationCoeList.length>0){//添加标准库的工料机
         for(let sub of std.rationCoeList){
-            let libCoe = await coeMolde.findOne({'libID':std.rationRepId,'ID':sub.ID,"$or": [{"isDeleted": null}, {"isDeleted": false}]});//std.rationRepId;
+            let libCoe;
+            if (std.type === 'std') {
+                libCoe = await coeMolde.findOne({'libID':std.rationRepId,'ID':sub.ID,"$or": [{"isDeleted": null}, {"isDeleted": false}]});//std.rationRepId;
+            } else {
+                libCoe = await compleCoeModel.findOne({ID: sub.ID, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]});
+            }
             if(libCoe){
                 let newCoe = {};
                 newCoe.ID = uuidV1();
@@ -398,7 +405,9 @@ async function  updateRation(std,defaultLibID,rationID,billsItemID,projectID,cal
     ration.name = std.name;
     ration.caption = std.caption;
     ration.unit = std.unit;
-    ration.libID = std.rationRepId;
+    if (std.type === 'std') {
+        ration.libID = std.rationRepId;
+    }
     ration.content = std.jobContent;
     ration.adjustState = '';
     ration.isFromDetail=0;

+ 15 - 1
modules/pm/controllers/pm_controller.js

@@ -24,6 +24,9 @@ let config = require("../../../config/config.js");
 const optionModel = mongoose.model('options');
 const stdBillsGuidanceLibModel = mongoose.model('std_billsGuidance_lib');
 const fs = require('fs');
+const _ = require('lodash');
+import SectionTreeDao from '../../complementary_ration_lib/models/sectionTreeModel';
+let sectionTreeDao = new SectionTreeDao();
 
 //统一回调函数
 let callback = function(req, res, err, message, data){
@@ -250,7 +253,18 @@ module.exports = {
         let compilationData = await compilationModel.getCompilationById(sessionCompilation._id);
         request.session.sessionCompilation = compilationData;
         sessionCompilation = request.session.sessionCompilation;
-
+        //更新用户的使用过的费用定额列表
+        let userData = await userModel.findOne({_id: mongoose.Types.ObjectId(request.session.sessionUser.id)}, '-_id used_list');
+        if (userData) {
+            let usedCompilation = _.find(userData.used_list, function (o) {
+                return o.compilationId === compilationData._id.toString();
+            });
+            if (!usedCompilation) {
+                await userModel.update({_id: mongoose.Types.ObjectId(request.session.sessionUser.id)}, {$push: {used_list: {compilationId: compilationData._id}}});
+                //拷贝模板数据
+                await sectionTreeDao.copyDataFromTemplate(request.session.sessionUser.id, compilationData._id);
+            }
+        }
         // 清单计价
         let billValuation = sessionCompilation.bill_valuation !== undefined ?
             sessionCompilation.bill_valuation : [];

+ 2 - 0
modules/ration_glj/facade/ration_coe_facade.js

@@ -32,6 +32,8 @@ let updateFunctionMap = {
 
 function create_ration_coe(user_id,datas) {
     return function (callback) {
+        console.log(`datas====================================================================================================`);
+        console.log(datas);
         let ration_coe_list=datas.ration_coe_list;
         var tasks=[];
         for(let i=0;i<ration_coe_list.length;i++){

+ 11 - 0
modules/ration_repository/models/coe.js

@@ -11,6 +11,17 @@ var coeListModel = mongoose.model("std_ration_lib_coe_list");
 
 var coeListDAO = function(){};
 
+const compleCoeModel = mongoose.model('complementary_ration_coe_list');
+
+coeListDAO.prototype.getComplementaryCoes = async function (userId, compilationId, callback) {
+    try {
+        let coeData =  await compleCoeModel.find({userId, compilationId});
+        callback(0, coeData);
+    } catch (err) {
+        callback(1, null);
+    }
+};
+
 coeListDAO.prototype.getCoe = function (data, callback) {
     coeListModel.findOne({
             "libID": data.libID,

+ 12 - 1
public/counter/counter.js

@@ -19,7 +19,8 @@ const COUNTER_MODULE_NAME = {
     unitPriceGLJ: 'unitPriceGLJ',
     template_bills: 'temp_bills',
     billsLib: 'billsLib',
-    coeList: 'coeList'
+    coeList: 'coeList',
+    complementaryCoeList: 'complementary_coe_list'
 }
 /*const PROJECT_COUNTER = 'projects', USER_COUNTER = 'users', BILL_COUNTER = 'bills', RATION_COUNTER = 'rations',
     REPORT_COUNTER = 'rptTemplates', FEE_COUNTER = 'fees'*/
@@ -41,6 +42,16 @@ counterDAO.prototype.getIDAfterCount = function(moduleName, stepCount, callback)
     counterModel.findOneAndUpdate({_id: moduleName}, { $inc: { sequence_value: sc } }, {'new':true}, callback);//findOneAndUpdate
 }
 
+counterDAO.prototype.getIDAfterCountSync = async function (moduleName, stepCount) {
+    let sc = stepCount;
+    if (isNaN(stepCount) || (stepCount < 0)) {
+        sc = 1;
+    } else if (!(/^-?\d+$/.test(stepCount))) {
+        sc = Math.round(stepCount + 0.5);
+    }
+    return await counterModel.findOneAndUpdate({_id: moduleName}, { $inc: { sequence_value: sc } }, {'new':true});//findOneAndUpdate
+};
+
 counterDAO.prototype.getCurrentID = function(moduleName, callback) {
     if (callback) {
         counterModel.findOne({_id: moduleName}).exec()

+ 20 - 0
public/web/id_tree.js

@@ -530,6 +530,26 @@ var idTree = {
             }
             return node;
         };
+        Tree.prototype.insertByID = function (newID, parentID, nextSiblingID) {
+            var node = null, data = {};
+            var parent = parentID == -1 ? null : this.nodes[this.prefix + parentID];
+            var nextSibling = nextSiblingID == -1 ? null: this.nodes[this.prefix + nextSiblingID];
+            if (newID) {
+                data = {};
+                data[this.setting.id] = newID;
+                data[this.setting.pid] = parent ? parent.getID() : this.setting.rootId;
+                data[this.setting.nid] = nextSibling ? nextSibling.getID() : this.setting.rootId;
+                node = new Node(this, data);
+                if (nextSibling) {
+                    tools.addNodes(this, parent, [node], nextSibling.siblingIndex());
+                } else {
+                    tools.addNodes(this, parent, [node]);
+                }
+                this.nodes[this.prefix + newID] = node;
+                tools.sortTreeItems(this);
+            }
+            return node;
+        };
         Tree.prototype.getInsertData = function (parentID, nextSiblingID, uid = null) {
             var data = [];
             var newID = uid ? uuid.v1() : this.newNodeID();

+ 20 - 0
public/web/tree_sheet/tree_sheet_controller.js

@@ -49,6 +49,26 @@ var TREE_SHEET_CONTROLLER = {
                 }
             }
         };
+        controller.prototype.insertByID = function (ID) {
+            var newNode = null, that = this,  sels = this.sheet.getSelections();
+            if (this.tree) {
+                if (this.tree.selected) {
+                    newNode = this.tree.insertByID(ID, this.tree.selected.getParentID(), this.tree.selected.getNextSiblingID());
+                } else {
+                    newNode = this.tree.insertByID(ID);
+                }
+                if (newNode) {
+                    TREE_SHEET_HELPER.massOperationSheet(this.sheet, function () {
+                        that.sheet.addRows(newNode.serialNo(), 1);
+                        TREE_SHEET_HELPER.refreshTreeNodeData(that.setting, that.sheet, [newNode], false);
+                        that.setTreeSelected(newNode);
+                        that.sheet.setSelection(newNode.serialNo(), sels[0].col, 1, 1);
+                        //that.sheet.showRow(newNode.serialNo(), GC.Spread.Sheets.VerticalPosition.center);
+                    });
+                }
+            }
+            return newNode;
+        };
         controller.prototype.delete = function () {
             var that = this, sels = this.sheet.getSelections();
             if (this.tree.selected) {

+ 20 - 1
web/building_saas/complementary_ration_lib/html/anzhuang.html

@@ -151,7 +151,26 @@
             </div>
         </div>
     </div>
-
+    <div class="modal fade" id="delAlert" data-backdrop="static" style="display: none;" aria-hidden="true">
+        <input type="hidden"  value="123">
+        <div class="modal-dialog" role="document">
+            <div class="modal-content">
+                <div class="modal-header">
+                    <h5 class="modal-title">警告</h5>
+                    <button type="button"  class="close" data-dismiss="modal" aria-label="Close">
+                        <span aria-hidden="true">×</span>
+                    </button>
+                </div>
+                <div class="modal-body">
+                    <h5 class="text-danger" id="delText">是否删除当前节点及其子项?</h5>
+                </div>
+                <div class="modal-footer">
+                    <button type="button" class="btn btn-danger" id="delConfirm">确认</button>
+                    <button type="button" class="btn btn-secondary"  data-dismiss="modal">取消</button>
+                </div>
+            </div>
+        </div>
+    </div>
     <!-- JS. -->
     <script src = "/lib/spreadjs/sheets/gc.spread.sheets.all.11.1.2.min.js"></script>
     <script>GC.Spread.Sheets.LicenseKey =  '<%- LicenseKey %>';</script>

+ 60 - 10
web/building_saas/complementary_ration_lib/html/dinge.html

@@ -27,7 +27,18 @@
             border-bottom: 1px solid #fff;
         }
         .modal-lg{max-width: 1000px}
+        .bottom-content {
+            height: 370px;
+            overflow: hidden;
+        }
+        .bottom-content .tab-content .main-data-bottom{
+            height: 340px;
+            overflow: auto;
+        }
     </style>
+    <script>
+        let gljLibId = '<%= gljLibId %>';
+    </script>
 </head>
 <body>
 <div class="header">
@@ -44,39 +55,44 @@
             <li class="nav-item">
                 <a class="nav-link px-3" id="gongliao" href="<%= redirectGlj %>">人材机</a>
             </li>
-            <li class="nav-item">
+            <!--<li class="nav-item">
                 <a class="nav-link px-3" id="fuzhu" href="<%= redirectCoe %>">子目换算</a>
-            </li>
+            </li>-->
             <li class="nav-item">
                 <a class="nav-link px-3" id="anzhuang" href="<%= redirectInstallation %>">安装增加费</a>
             </li>
         </ul>
+        <ul class="nav nav-tabs" role="tablist">
+            <li class="nav-item">
+                <a class="nav-link px-3" href="javascript:void(0);" id="zmhs">子目换算</a>
+            </li>
+        </ul>
     </nav>
 </div>
 <div class="main" style="overflow: hidden">
     <div class="content" style="margin-left: 0px">
         <div class="container-fluid">
             <div class="row">
-                <div class="main-side col-lg-3 p-0" style="width: 100%; height: 100%; overflow: hidden">
+                <div class="main-side p-0" style="width: 25%; height: 100%; overflow: hidden">
                     <div class="tab-bar">
                         <a href="javascript:void(0);" id="tree_Insert" class="btn btn-sm" data-toggle="tooltip" data-placement="bottom" title="" data-original-title="插入"><i class="fa fa-plus" aria-hidden="true"></i></a>
                         <a href="javascript:void(0);" id="tree_remove" class="btn btn-sm" data-toggle="tooltip" data-placement="bottom" title="" data-original-title="删除"><i class="fa fa-remove" aria-hidden="true"></i></a>
-                        <a href="javascript:void(0);" id="tree_upLevel" class="btn btn-sm disabled" data-toggle="tooltip" data-placement="bottom" title="" data-original-title="升级"><i class="fa fa-arrow-left" aria-hidden="true"></i></a>
-                        <a href="javascript:void(0);" id="tree_downLevel" class="btn btn-sm disabled" data-toggle="tooltip" data-placement="bottom" title="" data-original-title="降级"><i class="fa fa-arrow-right" aria-hidden="true"></i></a>
-                        <a href="javascript:void(0);" id="tree_downMove" class="btn btn-sm disabled" data-toggle="tooltip" data-placement="bottom" title="" data-original-title="下移"><i class="fa fa-arrow-down" aria-hidden="true"></i></a>
-                        <a href="javascript:void(0);" id="tree_upMove" class="btn btn-sm disabled" data-toggle="tooltip" data-placement="bottom" title="" data-original-title="上移"><i class="fa fa-arrow-up" aria-hidden="true"></i></a>
+                        <a href="javascript:void(0);" id="tree_upLevel" class="btn btn-sm" data-toggle="tooltip" data-placement="bottom" title="" data-original-title="升级"><i class="fa fa-arrow-left" aria-hidden="true"></i></a>
+                        <a href="javascript:void(0);" id="tree_downLevel" class="btn btn-sm" data-toggle="tooltip" data-placement="bottom" title="" data-original-title="降级"><i class="fa fa-arrow-right" aria-hidden="true"></i></a>
+                        <a href="javascript:void(0);" id="tree_downMove" class="btn btn-sm" data-toggle="tooltip" data-placement="bottom" title="" data-original-title="下移"><i class="fa fa-arrow-down" aria-hidden="true"></i></a>
+                        <a href="javascript:void(0);" id="tree_upMove" class="btn btn-sm" data-toggle="tooltip" data-placement="bottom" title="" data-original-title="上移"><i class="fa fa-arrow-up" aria-hidden="true"></i></a>
                     </div>
                     <div class="tab-content" id="sectionSpread" style="overflow: hidden">
                         <!--<ul id="rationChapterTree" class="ztree"></ul>-->
                     </div>
                 </div>
-                <div class="main-content col-lg-9 p-0">
+                <div class="main-content p-0" id="mainContent" style="width: 75%">
                     <!-- 右标签 -->
                     <ul class="nav nav-tabs tools-bar" role="tablist">
                         <li class="nav-item">
                             <a class="nav-link active" data-toggle="tab" href="#tde" role="tab">定额</a>
                         </li>
-                        <li class="nav-item">
+                    <!--    <li class="nav-item">
                             <a class="nav-link" data-toggle="tab" href="#tsm" role="tab" id="explanationLink">说明</a>
                         </li>
                         <li class="nav-item">
@@ -87,7 +103,7 @@
                         </li>
                         <li class="nav-item">
                             <a class="nav-link" data-toggle="tab" href="#tfz" role="tab">附注</a>
-                        </li>
+                        </li>-->
                     </ul>
                     <div class="tab-content">
                         <!--定额-->
@@ -167,6 +183,15 @@
                         </div>
                     </div>
                 </div>
+                <div class="main-side p-0 main-side-right" id="zmhsContent" style="width: 25%; display: none">
+                    <div class="resize" id="sideResize" style="width: 1%; height: 100%; resize:horizontal; cursor: w-resize; float: left; background: #F1F1F1"></div>
+                    <div style="width: 99%; float: left">
+                        <div class="main-data-top-fluid" id="mainSpread">
+                        </div>
+                        <div class="bottom-content" id="contentSpread">
+                        </div>
+                    </div>
+                </div>
             </div>
         </div>
     </div>
@@ -508,10 +533,32 @@
         </div>
     </div>
 </div>
+<!--删除-->
+<div class="modal fade" id="delAlert" data-backdrop="static" style="display: none;" aria-hidden="true">
+    <input type="hidden"  value="123">
+    <div class="modal-dialog" role="document">
+        <div class="modal-content">
+            <div class="modal-header">
+                <h5 class="modal-title">警告</h5>
+                <button type="button"  class="close" data-dismiss="modal" aria-label="Close">
+                    <span aria-hidden="true">×</span>
+                </button>
+            </div>
+            <div class="modal-body">
+                <h5 class="text-danger" id="delText">是否删除当前节点及其子项?</h5>
+            </div>
+            <div class="modal-footer">
+                <button type="button" class="btn btn-danger" id="delConfirm">确认</button>
+                <button type="button" class="btn btn-secondary"  data-dismiss="modal">取消</button>
+            </div>
+        </div>
+    </div>
+</div>
 <!-- JS. -->
 <script src = "/lib/spreadjs/sheets/gc.spread.sheets.all.11.1.2.min.js"></script>
 <script>GC.Spread.Sheets.LicenseKey =  '<%- LicenseKey %>';</script>
 <!--inject:js-->
+<script src="/public/web/uuid.js"></script>
 <script type="text/javascript" src="/lib/jquery-contextmenu/jquery.contextMenu.min.js"></script>
 <script type="text/javascript" src="/lib/jquery-contextmenu/jquery.ui.position.js"></script>
 <script type="text/javascript" src="/lib/ztree/jquery.ztree.core.js"></script>
@@ -541,6 +588,7 @@
 <script type="text/javascript" src="/web/building_saas/complementary_ration_lib/js/ration_coe.js"></script>
 <script type="text/javascript" src="/web/building_saas/complementary_ration_lib/js/ration_assist.js"></script>
 <script type="text/javascript" src="/web/building_saas/complementary_ration_lib/js/ration_installation.js"></script>
+<script src="/web/building_saas/complementary_ration_lib/js/coe.js"></script>
 <!--endinject-->
 <script type="text/javascript">
     let userID = '<%=userID %>';
@@ -549,6 +597,8 @@
 
         // tabPanel 下有多个Spread时,相互之间不能正确显示。改成一个Spread下多个Sheet。
         var rdSpread = sheetCommonObj.createSpread($("#rdSpread")[0], 4);
+        rdSpread.options.allowUserDragFill = false;
+        rdSpread.options.allowUserDragDrop = false;
         sheetCommonObj.spreadDefaultStyle(rdSpread);
         rationGLJOprObj.buildSheet(rdSpread.getSheet(0));
 

+ 3 - 0
web/building_saas/complementary_ration_lib/html/fuzhu.html

@@ -20,6 +20,9 @@
             border-bottom: 1px solid #fff;
         }
     </style>
+    <script>
+        let gljLibId = '<%- gljLibId %>';
+    </script>
 </head>
 
 <body>

+ 3 - 0
web/building_saas/complementary_ration_lib/html/gongliao.html

@@ -23,6 +23,9 @@
             border-bottom: 1px solid #fff;
         }
     </style>
+    <script>
+        let gljLibId = '<%- gljLibId %>';
+    </script>
 </head>
 
 <body>

+ 476 - 42
web/building_saas/complementary_ration_lib/js/coe.js

@@ -3,28 +3,37 @@
  */
 //modiyied by zhong on 2017/9/21
 
+$('#zmhs').click(function () {
+    if(!$(this).hasClass('active')){
+        $(this).addClass('active');
+        $('#mainContent').css('width', '50%');
+        $('#zmhsContent').show();
+      /*  loadSize(sideResizeEles, 'width', function(){
+
+        });*/
+        if(!coeOprObj.workBook){
+            pageObj.initPage();
+        }
+        coeOprObj.workBook.refresh();
+        gljAdjOprObj.workBook.refresh();
+        rationOprObj.workBook.refresh();
+        rationGLJOprObj.sheet.getParent().refresh();
+    } else {
+        $(this).removeClass('active');
+        $('#mainContent').css('width', '75%')
+        $('#zmhsContent').hide();
+        rationOprObj.workBook.refresh();
+        rationGLJOprObj.sheet.getParent().refresh();
+    }
+});
 
 var pageObj = {
-    libID: null,
-    gljLibID: null,
     initPage: function (){
-        var libID = getQueryString("repository");
         let me = this;
-        CommonAjax.post('/complementaryRation/api/getRationLibs', {ids: [libID]}, function (rstData) {
-            if(rstData.length > 0){
-                let libName = rstData[0].dispName;
-                if (libName) {
-                    let $rationName = $(`<div id='rationname' class='navbar-text'>${libName}</div>`);
-                    $('.header-logo').after($rationName);
-                };
-                me.gljLibID = rstData[0].gljLib;
-                me.libID = libID;
-                coeOprObj.buildSheet($('#mainSpread')[0]);
-                gljAdjOprObj.buildSheet($('#contentSpread')[0]);
-                coeOprObj.getCoeList();
-                gljAdjOprObj.getGljItemsOcc();
-            }
-        });
+        coeOprObj.buildSheet($('#mainSpread')[0]);
+        gljAdjOprObj.buildSheet($('#contentSpread')[0]);
+        coeOprObj.getCoeList();
+        //gljAdjOprObj.getGljItemsOcc();
 
     },
     showData: function(sheet, setting, data) {
@@ -69,20 +78,22 @@ let coeOprObj = {
     currentMaxNo: null,
     setting: {
         header: [
-            {headerName:"编号", headerWidth:60, dataCode:"serialNo", dataType: "String", hAlign: "center", vAlign: "center", readOnly: false},
+            {headerName:"编号", headerWidth:50, dataCode:"serialNo", dataType: "String", hAlign: "center", vAlign: "center", readOnly: false},
             {headerName:"名称", headerWidth:280, dataCode:"name", dataType: "String", hAlign: "left", vAlign: "center", readOnly: false},
-            {headerName:"内容", headerWidth:250, dataCode:"content", dataType: "String", hAlign: "left", vAlign: "center", readOnly: false},
+            {headerName:"内容", headerWidth:150, dataCode:"content", dataType: "String", hAlign: "left", vAlign: "center", readOnly: false},
         ]
     },
     buildSheet: function (container) {
         let me = coeOprObj;
         me.workBook = sheetCommonObj.buildSheet(container, me.setting, 30);
-        sheetCommonObj.spreadDefaultStyle(me.workBook);
+        sheetCommonObj.bindEscKey(me.workBook, [{sheet: me.workBook.getSheet(0), editStarting: null, editEnded: me.onEditEnded}]);
         me.workSheet = me.workBook.getSheet(0);
         me.workSheet.options.isProtected = true;
+        me.onDelOpr(me.workBook, me.setting);
         me.workSheet.bind(GC.Spread.Sheets.Events.SelectionChanged, me.onSelectionChanged);
-        me.workSheet.bind(GC.Spread.Sheets.Events.EditStarting, me.onEditStarting);
+        me.workSheet.bind(GC.Spread.Sheets.Events.EditEnded, me.onEditEnded);
         me.workBook.bind(GC.Spread.Sheets.Events.ClipboardPasting, me.onClipboardPasting);
+        me.workBook.bind(GC.Spread.Sheets.Events.ClipboardPasted, me.onClipboardPasted);
     },
     onSelectionChanged: function (sender, info) {
         let me = coeOprObj, that = gljAdjOprObj;
@@ -104,15 +115,192 @@ let coeOprObj = {
             that.show(that.currentGljAdjList);
         }
     },
-    onEditStarting: function (sender, args) {
-        args.cancel = true;
+    onEditEnded: function (sender, args) {
+        let me = coeOprObj, addArr = [], updateArr = [], dataCode = me.setting.header[args.col].dataCode;
+        if(args.editingText && args.editingText.toString().trim().length > 0){
+            let inputT = args.editingText.toString().trim();
+            //update
+            if(args.row < me.currentCoeList.length){
+                let updateObj = me.currentCoeList[args.row];
+                if(updateObj[dataCode] != inputT){
+                    if(dataCode === 'serialNo'){
+                        if(me.isInt(inputT) && !me.hasTisNo(me.currentCoeList, inputT)){
+                            me.currentMaxNo = me.currentMaxNo >= inputT ? me.currentMaxNo : inputT;
+                            updateObj[dataCode] = inputT;
+                            updateArr.push(updateObj);
+                            me.save([], updateArr, [], true);
+                        }
+                        else if(!me.isInt(inputT)){
+                            alert('编号只能为整数!');
+                            args.sheet.setValue(args.row, args.col, updateObj[dataCode] + '');
+                        }
+                        else if(me.hasTisNo(me.currentCoeList, inputT)){
+                            alert('该编号已存在!');
+                            args.sheet.setValue(args.row, args.col, updateObj[dataCode] + '');
+                        }
+                    }
+                    else {
+                        updateObj[dataCode] = inputT;
+                        updateArr.push(updateObj);
+                        me.save([], updateArr, [], true);
+                    }
+                }
+            }
+            //insert
+            else{
+                let newCoe = {};
+                if(dataCode === 'serialNo'){
+                    if(me.isInt(inputT) && !me.hasTisNo(me.currentCoeList, inputT)){
+                        me.currentMaxNo = me.currentMaxNo >= inputT ? me.currentMaxNo : inputT;
+                        newCoe[dataCode] = inputT;
+                        addArr.push(newCoe);
+                        me.save(addArr, [], [], true, function (result) {
+                            me.updateCurrentCoeList(result);
+                        });
+                    }
+                    else if(!me.isInt(inputT)){
+                        args.sheet.setValue(args.row, args.col, '');
+                        alert('编号只能为整数!');
+                    }
+                    else if(me.hasTisNo(me.currentCoeList, inputT)){
+                        args.sheet.setValue(args.row, args.col, '');
+                        alert('该编号已存在!');
+                    }
+                }
+                else{
+                    newCoe.serialNo = ++me.currentMaxNo;
+                    newCoe[dataCode] = inputT;
+                    addArr.push(newCoe);
+                    me.save(addArr, [], [], true, function (result) {
+                        me.updateCurrentCoeList(result);
+                    });
+                }
+            }
+        }
     },
     onClipboardPasting: function (sender, info) {
-        info.cancel = true;
+        let me = coeOprObj, maxCol = info.cellRange.col + info.cellRange.colCount - 1;
+        if(maxCol > me.setting.header.length){
+            info.cancel = true;
+        }
+    },
+    onClipboardPasted: function (sender, info) {
+        let me = coeOprObj, addArr = [], updateArr = [];
+        let items = sheetCommonObj.analyzePasteData(me.setting, info);
+        let uniqItems = me.makeUniqItems(items);
+        for(let i = 0, len = uniqItems.length; i < len; i++){
+            let row = i + info.cellRange.row;
+            //update
+            if(row < me.currentCoeList.length){
+                let updateObj = me.currentCoeList[row];
+                for(let attr in uniqItems[i]){
+                    if(attr === 'serialNo'){
+                        if(me.isInt(uniqItems[i][attr]) && !me.hasTisNo(me.currentCoeList, uniqItems[i][attr])){
+                            me.currentMaxNo = me.currentMaxNo >= uniqItems[i][attr] ? me.currentMaxNo : uniqItems[i][attr];
+                            updateObj[attr] = uniqItems[i][attr];
+                        }
+                    }
+                    else {
+                        updateObj[attr] = uniqItems[i][attr];
+                    }
+                }
+                updateArr.push(updateObj);
+            }
+            //insert
+            else {
+                if(typeof uniqItems[i].serialNo !== 'undefined' && uniqItems[i] && me.isInt(uniqItems[i].serialNo) && !me.hasTisNo(me.currentCoeList, uniqItems[i].serialNo)){
+                    me.currentMaxNo = me.currentMaxNo >= uniqItems[i].serialNo ? me.currentMaxNo : uniqItems[i].serialNo;
+                }
+                else {
+                    uniqItems[i].serialNo = ++me.currentMaxNo;
+                }
+                addArr.push(uniqItems[i]);
+            }
+        }
+        if(addArr.length > 0 || updateArr.length > 0){
+            me.save(addArr, updateArr, [], true, function (result) {
+                me.updateCurrentCoeList(result);
+            });
+        }
+    },
+    onDelOpr: function (workBook, setting) {
+        let me = coeOprObj, that = gljAdjOprObj;
+        workBook.commandManager().register('coeListDel', function () {
+            let deleteArr = [];
+            let sheet = workBook.getSheet(0);
+            let sels = sheet.getSelections();
+            let idx = sels[0].row;
+            for(let i = 0, len = sels.length; i < len; i++){
+                if(idx > sels[i].row){
+                    idx = sels[i].row;
+                }
+                if(sels[i].colCount === setting.header.length){//can del
+                    for(let r = 0, rLen = sels[i].rowCount; r < rLen; r++){
+                        let row = sels[i].row + r;
+                        if(row < me.currentCoeList.length){
+                            deleteArr.push({userId: me.currentCoeList[row].userId, compilationId: me.currentCoeList[row].compilationId, ID: me.currentCoeList[row].ID});
+                        }
+                    }
+                    me.currentCoeList.splice(sels[i].row, sels[i].rowCount);
+                }
+            }
+            if(deleteArr.length > 0){
+                me.save([], [], deleteArr, true);
+                me.currentCoe = typeof me.currentCoeList[idx] !== 'undefined' ? me.currentCoeList[idx] : null;
+                that.currentGljAdjList = me.currentCoe ? me.currentCoe.coes : [];
+                gljAdjOprObj.show(that.currentGljAdjList);
+            }
+
+        });
+        workBook.commandManager().setShortcutKey(null, GC.Spread.Commands.Key.del, false, false, false, false);
+        workBook.commandManager().setShortcutKey('coeListDel', GC.Spread.Commands.Key.del, false, false, false, false);
+    },
+    //粘贴的数据,编号唯一化,去除编号重复的项
+    makeUniqItems: function (items) {
+        let rst = [];
+        for(let i = 0, len = items.length; i < len; i++){
+            if(typeof items[i].serialNo !== 'undefined' && items[i].serialNo){
+                if(rst.length === 0){
+                    rst.push(items[i]);
+                }
+                else{
+                    let isExist = false;
+                    for(let j = 0, jLen = rst.length; j < jLen; j++){
+                        if(items[i].serialNo === rst[j].serialNo){
+                            isExist = true;
+                            break;
+                        }
+                    }
+                    if(!isExist){
+                        rst.push(items[i]);
+                    }
+                }
+            }
+            else {
+                rst.push(items[i]);
+            }
+        }
+        return rst;
     },
     isInt: function (num) {
         return !isNaN(num) && num % 1 === 0;
     },
+    hasTisNo: function (coeList, newSerialNo) {
+        let rst = false;
+        for(let i = 0, len = coeList.length; i < len; i++){
+            if(coeList[i].serialNo == newSerialNo){
+                rst = true;
+                break;
+            }
+        }
+        return rst;
+    },
+    updateCurrentCoeList: function (newCoeList) {
+        let me = coeOprObj;
+        if(newCoeList){
+            me.currentCoeList = me.currentCoeList.concat(newCoeList);
+        }
+    },
     sortCoeList: function (coeList) {
         coeList.sort(function (a, b) {
             let rst = 0;
@@ -123,12 +311,50 @@ let coeOprObj = {
     },
     getCoeList: function () {
         let me = coeOprObj;
-        CommonAjax.post('api/getCoeList', {libID: pageObj.libID}, function (rstData) {
-            me.currentCoeList = rstData;
-            me.sortCoeList(me.currentCoeList);
-            me.currentMaxNo =  me.currentCoeList.length > 0 ? me.currentCoeList[me.currentCoeList.length - 1].serialNo : 0;
-            pageObj.showData(me.workSheet, me.setting, me.currentCoeList);
-            me.workSheet.clearSelection();
+        $.ajax({
+            type: 'post',
+            url: 'api/getCoeList',
+            dataType: 'json',
+            timeout:20000,
+            success: function (result) {
+                if(!result.error){
+                    me.currentCoeList = result.data;
+                    me.sortCoeList(me.currentCoeList);
+                    me.currentMaxNo =  me.currentCoeList.length > 0 ? me.currentCoeList[me.currentCoeList.length - 1].serialNo : 0;
+                    pageObj.showData(me.workSheet, me.setting, me.currentCoeList);
+                    me.workSheet.clearSelection();
+                }
+            },
+            error:function(err){
+                alert("内部程序错误!");
+            }
+        });
+    },
+    save: function (addArr, updateArr, deleteArr, refresh, callback) {
+        let me = coeOprObj;
+        $.ajax({
+            type:"POST",
+            url:"api/saveCoeList",
+            data: {data: JSON.stringify({addArr: addArr, updateArr: updateArr, deleteArr: deleteArr})},
+            dataType:"json",
+            timeout:5000,
+            success:function(result){
+                if (result.error) {
+                    alert(result.message);
+                } else{
+                    if(callback){
+                        callback(result.data);
+                    }
+                    if(refresh){
+                        me.sortCoeList(me.currentCoeList);
+                        me.currentMaxNo = me.currentCoeList.length > 0 ? me.currentCoeList[me.currentCoeList.length - 1].serialNo : 0;
+                        pageObj.showData(me.workSheet, me.setting, me.currentCoeList);
+                    }
+                }
+            },
+            error:function(err){
+                alert("内部程序错误!");
+            }
         });
     }
 };
@@ -137,18 +363,18 @@ let gljAdjOprObj = {
     workBook: null,
     workSheet: null,
     currentGljAdjList: [],
-    gljList: [],//只含编号和名称的总工料机列表
+    gljList: [],//总工料机列表, gljSelect中获取
     setting: {
         header: [
-            {headerName:"调整类型", headerWidth:100, dataCode:"coeType", dataType: "String", hAlign: "center", vAlign: "center", readOnly: false},
-            {headerName:"人材机编码", headerWidth:100, dataCode:"gljCode", dataType: "String", formatter: '@', hAlign: "center", vAlign: "center", readOnly: false},
+            {headerName:"调整类型", headerWidth:80, dataCode:"coeType", dataType: "String", hAlign: "center", vAlign: "center", readOnly: false},
+            {headerName:"人材机编码", headerWidth:80, dataCode:"gljCode", dataType: "String", formatter: '@', hAlign: "center", vAlign: "center", readOnly: false},
             {headerName:"名称", headerWidth:100, dataCode:"gljName", dataType: "String", hAlign: "center", vAlign: "center", readOnly: true},
             {headerName:"操作符", headerWidth:60, dataCode:"operator", dataType: "String", hAlign: "center", vAlign: "center", readOnly: false},
             {headerName:"数量", headerWidth:80, dataCode:"amount", dataType: "String", hAlign: "center", vAlign: "center" , readOnly: false},
         ],
         comboItems: {
             //调整类型下拉菜单
-            coeType: ['定额子目', '人工', '材料', '机械', '主材', '设备', '单个工料机'],
+            coeType: ['定额', '人工', '材料', '机械', '主材', '设备', '单个工料机'],
             //操作符下拉菜单
             operator: ['+', '-', '*', '/', '=']
         }
@@ -156,13 +382,16 @@ let gljAdjOprObj = {
     buildSheet: function (container) {
         let me = gljAdjOprObj;
         me.workBook = sheetCommonObj.buildSheet(container, me.setting, 3);
-        sheetCommonObj.spreadDefaultStyle(me.workBook);
         me.workSheet = me.workBook.getSheet(0);
+        sheetCommonObj.bindEscKey(me.workBook, [{sheet: me.workBook.getSheet(0), editStarting: me.onEditStart, editEnded: me.onEditEnded}]);
         me.workSheet.options.isProtected = true;
+        me.onDelOpr(me.workBook, me.setting);
         me.workSheet.clearSelection();
         me.workSheet.bind(GC.Spread.Sheets.Events.EditStarting, me.onEditStart);
+        me.workSheet.bind(GC.Spread.Sheets.Events.EditEnded, me.onEditEnded);
         me.workSheet.bind(GC.Spread.Sheets.Events.EnterCell, me.onEnterCell);
         me.workSheet.bind(GC.Spread.Sheets.Events.ClipboardPasting, me.onClipboardPasting);
+        me.workSheet.bind(GC.Spread.Sheets.Events.ClipboardPasted, me.onClipboardPasted);
     },
     buildBaseCell: function (sheet) {
         let me = gljAdjOprObj;
@@ -192,10 +421,203 @@ let gljAdjOprObj = {
     },
     onEditStart: function (sender, args) {
         let me = gljAdjOprObj;
-        args.cancel = true;
+        if(!coeOprObj.currentCoe || args.row >= me.currentGljAdjList.length && args.col === 1
+            || args.row < me.currentGljAdjList.length && args.col === 1 && me.currentGljAdjList[args.row].coeType !== '单个工料机'){
+            args.cancel = true;
+        }
+    },
+    onEditEnded: function (sender, args) {
+        let me = gljAdjOprObj, isUpdate = false,
+            dataCode = me.setting.header[args.col].dataCode;
+        if(args.editingText && args.editingText.toString().trim().length > 0){
+            if(dataCode === 'amount' &&  isNaN(args.editingText)){
+                alert("只能输入数值!");
+                args.sheet.setValue(args.row, args.col, typeof me.currentGljAdjList[args.row] !== 'undefined' && typeof me.currentGljAdjList[args.row][dataCode] !== 'undefined'
+                    ? me.currentGljAdjList[args.row][dataCode] + '' : '');
+            }
+            else {
+                //update
+                if(args.row < me.currentGljAdjList.length && args.editingText.toString().trim() !== me.currentGljAdjList[args.row][dataCode]){
+                    let updateObj = me.currentGljAdjList[args.row];
+                    if(dataCode === 'gljCode' && typeof updateObj.coeType !== 'undefined' && updateObj.coeType === '单个工料机'){
+                        let gljName = me.getGljName(args.editingText, me.gljList);
+                        if(gljName){
+                            updateObj.gljCode = args.editingText;
+                            updateObj.gljName = gljName;
+                            isUpdate = true;
+                        }
+                        else {
+                            alert("不存在编号为"+ args.editingText +"的工料机");
+                        }
+                    }
+                    else if(dataCode === 'coeType'){
+                        isUpdate = true;
+                        updateObj[dataCode] = args.editingText;
+                        updateObj.gljCode = '';
+                        updateObj.gljName = '';
+                    }
+                    else if(dataCode !== 'gljCode') {
+                        isUpdate = true;
+                        updateObj[dataCode] = args.editingText;
+                    }
+                }
+                //insert
+                else if(args.row >= me.currentGljAdjList.length){
+                    isUpdate = true;
+                    let newAdjGlj = {};
+                    newAdjGlj[dataCode] = args.editingText;
+                    me.currentGljAdjList.push(newAdjGlj);
+                }
+                if(isUpdate){
+                    coeOprObj.save([], [coeOprObj.currentCoe], [], false, function () {
+                        console.log(me.currentGljAdjList);
+                        me.show(me.currentGljAdjList);
+                    });
+                }
+                else {
+                    args.sheet.setValue(args.row, args.col, typeof me.currentGljAdjList[args.row] !== 'undefined' && typeof me.currentGljAdjList[args.row][dataCode] !== 'undefined'
+                        ? me.currentGljAdjList[args.row][dataCode] + '' : '');
+                }
+            }
+        }
     },
     onClipboardPasting: function (sender, info) {
-        info.cancel = true;
+
+    },
+    getValidPasteDatas: function (pasteItems, info) {
+        let me = gljAdjOprObj;
+        let rst = [];
+        for(let i = 0, len = pasteItems.length; i < len; i++){
+            let row = i + info.cellRange.row;
+            let validObj = {};
+            //update
+            if(row < me.currentGljAdjList.length){
+                let updateObj = me.currentGljAdjList[row];
+                if(typeof pasteItems[i].coeType !== 'undefined' && typeof pasteItems[i].gljCode !== 'undefined'){
+                    let gljName = me.getGljName(pasteItems[i].gljCode, me.gljList);
+                    if(pasteItems[i].coeType === '单个工料机' && gljName){
+                        validObj.coeType = pasteItems[i].coeType;
+                        validObj.gljCode = pasteItems[i].gljCode;
+                        validObj.gljName = gljName;
+                    }
+                    else if(pasteItems[i].coeType !== '单个工料机' && me.setting.comboItems.coeType.indexOf(pasteItems[i].coeType) !== -1){
+                        validObj.coeType = pasteItems[i].coeType;
+                    }
+                }
+                else if(typeof pasteItems[i].coeType === 'undefined' && typeof pasteItems[i].gljCode !== 'undefined'){
+                    let gljName = me.getGljName(pasteItems[i].gljCode, me.gljList);
+                    if(typeof updateObj.coeType !== 'undefined' && updateObj.coeType === '单个工料机' && gljName){
+                        validObj.gljCode = pasteItems[i].gljCode;
+                        validObj.gljName = gljName;
+                    }
+                }
+                else if(typeof pasteItems[i].coeType !== 'undefined' && typeof pasteItems[i].gljCode === 'undefined'){
+                    if(me.setting.comboItems.coeType.indexOf(pasteItems[i].coeType) !== -1){
+                        validObj.coeType = pasteItems[i].coeType;
+                        if(validObj.coeType !== '单个工料机' && typeof updateObj.gljCode !== '单个工料机' && updateObj.gljCode.toString().trim().length > 0){
+                            validObj.gljCode = '';
+                            validObj.gljName = '';
+                        }
+                    }
+                }
+                else {
+                    if(typeof pasteItems[i].operator !== 'undefined' && me.setting.comboItems.operator.indexOf(pasteItems[i].operator) !== -1){
+                        validObj.operator = pasteItems[i].operator;
+                    }
+                    if(typeof pasteItems[i].amount !== 'undefined' && !isNaN(pasteItems[i].amount)){
+                        validObj.amount = pasteItems[i].amount;
+                    }
+                }
+            }
+            else {
+                if(typeof pasteItems[i].coeType !== 'undefined' && typeof pasteItems[i].gljCode !== 'undefined'){
+                    let gljName = me.getGljName(pasteItems[i].gljCode, me.gljList);
+                    if(pasteItems[i].coeType === '单个工料机' && gljName){
+                        validObj.coeType = pasteItems[i].coeType;
+                        validObj.gljCode = pasteItems[i].gljCode;
+                        validObj.gljName = gljName;
+                    }
+                    else if(pasteItems[i].coeType !== '单个工料机' && me.setting.comboItems.coeType.indexOf(pasteItems[i].coeType) !== -1){
+                        validObj.coeType = pasteItems[i].coeType;
+                    }
+                }
+                else if(typeof pasteItems[i].gljCode === 'undefined') {
+                    if(typeof pasteItems[i].coeType !== 'undefined' && me.setting.comboItems.coeType.indexOf(pasteItems[i].coeType) !== -1){
+                        validObj.coeType = pasteItems[i].coeType;
+                    }
+                    if(typeof pasteItems[i].operator !== 'undefined' && me.setting.comboItems.operator.indexOf(pasteItems[i].operator) !== -1){
+                        validObj.operator = pasteItems[i].operator;
+                    }
+                    if(typeof pasteItems[i].amount !== 'undefined' && !isNaN(pasteItems[i].amount)){
+                        validObj.amount = pasteItems[i].amount;
+                    }
+                }
+            }
+            if(Object.keys(validObj).length > 0){
+                rst.push(validObj);
+            }
+        }
+        return rst;
+    },
+    onClipboardPasted: function (sender, info) {
+        let me = gljAdjOprObj, row;
+        let items = sheetCommonObj.analyzePasteData(me.setting, info);
+        let validDatas = me.getValidPasteDatas(items, info);
+        for(let i = 0, len = validDatas.length; i < len; i++){
+            row = i + info.cellRange.row;
+            //update
+            if(row < me.currentGljAdjList.length){
+                let updateObj = me.currentGljAdjList[row];
+                for(let attr in validDatas[i]){
+                    updateObj[attr] = validDatas[i][attr];
+                }
+            }
+            //insert
+            else{
+                me.currentGljAdjList.push(validDatas[i]);
+            }
+        }
+        if(validDatas.length > 0){
+            coeOprObj.save([], [coeOprObj.currentCoe], [], false, function () {
+                me.show(me.currentGljAdjList);
+            });
+        }
+        else {
+            me.show(me.currentGljAdjList);
+        }
+    },
+    onDelOpr: function (workBook, setting) {
+        let me = gljAdjOprObj;
+        workBook.commandManager().register('gljAdjDel', function () {
+            let sheet = workBook.getSheet(0);
+            let sels = sheet.getSelections();
+            let isUpdate = false;
+            for(let i = 0, len = sels.length; i < len; i++){
+                if(sels[i].colCount === setting.header.length){//can del
+                    if(sels[i].row < me.currentGljAdjList.length){
+                        isUpdate = true;
+                        me.currentGljAdjList.splice(sels[i].row, sels[i].rowCount);
+                    }
+                }
+            }
+            if(isUpdate){
+                coeOprObj.save([], [coeOprObj.currentCoe], [], false, function () {
+                    me.show(me.currentGljAdjList);
+                });
+            }
+        });
+        workBook.commandManager().setShortcutKey(null, GC.Spread.Commands.Key.del, false, false, false, false);
+        workBook.commandManager().setShortcutKey('gljAdjDel', GC.Spread.Commands.Key.del, false, false, false, false);
+    },
+    getGljName: function (gljCode, gljList) {
+        let rst = null;
+        for(let i = 0, len = gljList.length; i < len; i++){
+            if(gljCode === gljList[i].code){
+                rst = gljList[i].name;
+                break;
+            }
+        }
+        return rst;
     },
     show: function (coes) {
         let me = gljAdjOprObj;
@@ -203,11 +625,23 @@ let gljAdjOprObj = {
     },
     getGljItemsOcc: function () {
         let me = gljAdjOprObj;
-        CommonAjax.post('api/getGljItemsOccupied', {gljLibId: pageObj.gljLibID, occupation: '-_id code name'}, function (rstData) {
-            me.gljList = rstData;
+        $.ajax({
+            type: 'post',
+            url: '/stdGljRepository/api/getGljItemsOccupied',
+            data: {repId: pageObj.gljLibID, occupation: '-_id code name'},
+            dataType: 'json',
+            timeout: 5000,
+            success:function(result){
+                if (result.error) {
+                    alert(result.message);
+                } else{
+                    me.gljList = result.data;
+                }
+            },
+            error:function(err){
+                alert("内部程序错误!");
+            }
         });
-
     }
 };
 
-

+ 1 - 0
web/building_saas/complementary_ration_lib/js/gljSelect.js

@@ -56,6 +56,7 @@ let gljSelOprObj = {
             me.setProp('type', 'complementary', me.complementaryGljList);
             me.sortGlj(me.stdGljList);
             me.sortGlj(me.complementaryGljList);
+            gljAdjOprObj.gljList = me.stdGljList.concat(me.complementaryGljList);
             if(callback){
                 callback();
             }

+ 61 - 13
web/building_saas/complementary_ration_lib/js/global.js

@@ -13,17 +13,27 @@ function autoFlashHeight(){
     $(".main-data-top-fluid").height($(window).height()-headerHeight-bottomContentHeight-2);
     $(".main-data").height($(window).height()-headerHeight);
     $(".main-side .tab-content").height($(window).height()-headerHeight-38);
-    $("#explanationShow").height($(window).height()-headerHeight-toolsBar-100);
-    $("#ruleTextShow").height($(window).height()-headerHeight-toolsBar-100);
+    $('#partialBody').height($(window).height()-headerHeight-toolsBar - 60);
+    let partialWidth = $('#tablePartial').width();
+    $('#tablePartial').find('th:eq(0)').width(partialWidth * 0.06);
+    $('#tablePartial').find('th:eq(1)').width(partialWidth * 0.3);
+    $('#tablePartial').find('th:eq(2)').width(partialWidth * 0.64);
+    $('#partialBody').find('tr').find('td:eq(0)').width(partialWidth * 0.06);
+    $('#partialBody').find('tr').find('td:eq(1)').width(partialWidth * 0.3);
+    $('#partialBody').find('tr').find('td:eq(2)').width(partialWidth * 0.64);
+//说明
+    $('#explanationShow').height($(window).height()-headerHeight-toolsBar-100);
+//计算规则
+    $('#ruleTextShow').height($(window).height()-headerHeight-toolsBar-100);
 };
 $(window).resize(autoFlashHeight);
 /*全局自适应高度结束*/
 $(function(){
-/*侧滑*/
-$(".open-sidebar").click(function(){
-    $(".slide-sidebar").animate({width:"800"}).addClass("open");
-});
-$("body").click(function(event){
+    /*侧滑*/
+    $(".open-sidebar").click(function(){
+        $(".slide-sidebar").animate({width:"800"}).addClass("open");
+    });
+    $("body").click(function(event){
         var e = event || window.event; //浏览器兼容性
         if(!$(event.target).is('a')) {
             var elem = event.target || e.srcElement;
@@ -37,10 +47,48 @@ $("body").click(function(event){
         }
 
     });
-/*侧滑*/
-/*工具提示*/
-$('*[data-toggle=tooltip]').mouseover(function() {
- $(this).tooltip('show');
-  });
-/*工具提示*/
+    /*侧滑*/
+    /*工具提示*/
+    $('*[data-toggle=tooltip]').mouseover(function() {
+        $(this).tooltip('show');
+    });
+    /*工具提示*/
 });
+/**
+ * 设置本地缓存
+ *
+ * @param {String} key
+ * @param {String|Number} value
+ * @return {void}
+ */
+function setLocalCache(key, value) {
+    const storage = window.localStorage;
+    if (!storage || key === '' || value === '') {
+        return;
+    }
+
+    storage.setItem(key, value);
+}
+
+/**
+ * 获取本地缓存
+ *
+ * @param {String} key
+ * @return {String}
+ */
+function getLocalCache(key) {
+    const storage = window.localStorage;
+    if (!storage || key === '') {
+        return null;
+    }
+
+    return storage.getItem(key);
+}
+
+function removeLocalCache(key) {
+    const storage = window.localStorage;
+    if (!storage || key === '') {
+        return null;
+    }
+    return storage.removeItem(key);
+}

File diff suppressed because it is too large
+ 1007 - 39
web/building_saas/complementary_ration_lib/js/installation.js


+ 145 - 152
web/building_saas/complementary_ration_lib/js/ration.js

@@ -1,6 +1,7 @@
 /**
  * Created by Tony on 2017/4/28.
  */
+
 const digital = {
     gljPrc: -3,//计算定额基价时单个工料机价格取三位
     rationBasePrc: -2,
@@ -12,18 +13,17 @@ let rationOprObj = {
     currentEditingRation: null,
     currentSectionId: -1,
     rationsCodes: [],
-    type: {std: 'std', complementary: 'complementary'},
     setting: {
         header:[
-            {headerName:"编码",headerWidth:120,dataCode:"code", dataType: "String", formatter: "@"},
-            {headerName:"名称",headerWidth:280,dataCode:"name", dataType: "String"},
-            {headerName:"计量单位",headerWidth:120,dataCode:"unit", dataType: "String", hAlign: "center"},
-            {headerName:"人工费",headerWidth:120,dataCode:"labourPrice", dataType: "Number", formatter: "0.00", hAlign: "right"},
-            {headerName:"材料费",headerWidth:120,dataCode:"materialPrice", dataType: "Number", formatter: "0.00",  hAlign: "right"},
-            {headerName:"机械费",headerWidth:120,dataCode:"machinePrice", dataType: "Number", formatter: "0.00", hAlign: "right"},
-            {headerName:"基价",headerWidth:120,dataCode:"basePrice", dataType: "Number", formatter: "0.00", hAlign: "right"},
-            {headerName:"显示名称(以%s表示参数)",headerWidth:280,dataCode:"caption", dataType: "String"},
-            {headerName:"取费专业",headerWidth:100,dataCode:"feeType", dataType: "Number", hAlign: "center"}
+            {headerName:"编码",headerWidth:70,dataCode:"code", dataType: "String", formatter: "@"},
+            {headerName:"名称",headerWidth:240,dataCode:"name", dataType: "String"},
+            {headerName:"计量单位",headerWidth:70,dataCode:"unit", dataType: "String", hAlign: "center"},
+            {headerName:"人工费",headerWidth:80,dataCode:"labourPrice", dataType: "Number", formatter: "0.00", hAlign: "right"},
+            {headerName:"材料费",headerWidth:80,dataCode:"materialPrice", dataType: "Number", formatter: "0.00",  hAlign: "right"},
+            {headerName:"机械费",headerWidth:80,dataCode:"machinePrice", dataType: "Number", formatter: "0.00", hAlign: "right"},
+            {headerName:"基价",headerWidth:80,dataCode:"basePrice", dataType: "Number", formatter: "0.00", hAlign: "right"},
+            {headerName:"显示名称(以%s表示参数)",headerWidth:240,dataCode:"caption", dataType: "String"},
+            {headerName:"取费专业",headerWidth:70,dataCode:"feeType", dataType: "Number", hAlign: "center"}
         ],
         view:{
             comboBox:[
@@ -41,7 +41,6 @@ let rationOprObj = {
         let rationRepId = getQueryString("repository");
         let me = rationOprObj;
         me.workBook = sheetCommonObj.buildSheet(container, me.setting, 30);
-        sheetCommonObj.spreadDefaultStyle(me.workBook);
         sheetCommonObj.bindEscKey(me.workBook, [{sheet: me.workBook.getSheet(0), editStarting: me.onCellEditStart, editEnded: me.onCellEditEnd}]);
         me.getRationsCodes(rationRepId);
         me.onContextmenuOpr();
@@ -74,7 +73,7 @@ let rationOprObj = {
             me.rationSelInit(row);
         }
     },
-    //focusOnSection,焦点返回章节表
+    //focusOnSection将工作簿焦点移到章节表上
     rationSelInit: function (row, focusOnSection = null) {
         let me = rationOprObj,
             sheetGLJ = rationGLJOprObj.sheet, settingGLJ = rationGLJOprObj.setting,
@@ -88,14 +87,14 @@ let rationOprObj = {
         let cacheSection = me.getCache();
         if (cacheSection && row < cacheSection.length) {
             rationGLJOprObj.getGljItems(cacheSection[row], function () {
-                if (focusOnSection) {
+                if (focusOnSection){
                     sectionTreeObj.workBook.focus(true);
                 } else {
                     me.workBook.focus(true);
                 }
             });
             rationCoeOprObj.getCoeItems(cacheSection[row], function () {
-                if (focusOnSection) {
+                if (focusOnSection){
                     sectionTreeObj.workBook.focus(true);
                 } else {
                     me.workBook.focus(true);
@@ -103,7 +102,7 @@ let rationOprObj = {
             });
             rationAssistOprObj.getAssItems(cacheSection[row]);
             rationInstObj.getInstItems(cacheSection[row], function () {
-                if (focusOnSection) {
+                if (focusOnSection){
                     sectionTreeObj.workBook.focus(true);
                 } else {
                     me.workBook.focus(true);
@@ -117,9 +116,7 @@ let rationOprObj = {
             me.workBook.focus(true);
         }
     },
-    isDef: function (v) {
-        return v !== undefined && v !== null;
-    },
+
     isInt: function (num) {
         return !isNaN(num) && num % 1 === 0;
     },
@@ -152,6 +149,7 @@ let rationOprObj = {
                         cacheSection[j]["rationGljList"] = rstData.ops[i]["rationGljList"];
                         cacheSection[j]["rationCoeList"] = rstData.ops[i]["rationCoeList"];
                         cacheSection[j]["rationAssList"] = rstData.ops[i]["rationAssList"];
+                        cacheSection[j]["rationInstList"] = rstData.ops[i]["rationInstList"];
                     }
                 }
             }
@@ -160,21 +158,25 @@ let rationOprObj = {
             for (let j = 0; j < cacheSection.length; j++) {
                 if (updateArr[i]["ID"] && cacheSection[j]["ID"]) {
                     if (cacheSection[j]["ID"] == updateArr[i]["ID"]) {
-                        updateArr[i]['rationGljList'] = rationGLJOprObj.cache['_GLJ_' + cacheSection[j]['ID']] ? rationGLJOprObj.cache['_GLJ_' + cacheSection[j]['ID']] : [];
-                        updateArr[i]['rationCoeList'] = rationCoeOprObj.cache['_Coe_' + cacheSection[j]['ID']] ? rationCoeOprObj.cache['_Coe_' + cacheSection[j]['ID']] : [];
+                        updateArr[i]['rationGljList'] = rationGLJOprObj.cache['_GLJ_' + cacheSection[j]['ID']] ?
+                            rationGLJOprObj.cache['_GLJ_' + cacheSection[j]['ID']] :
+                            cacheSection[j]['rationGljList'] ?
+                                cacheSection[j]['rationGljList'] : [];
+                        updateArr[i]['rationCoeList'] = cacheSection[j]['rationCoeList'] ? cacheSection[j]['rationCoeList'] : [];
                         updateArr[i]['rationAssList'] = cacheSection[j]['rationAssList'];
                         updateArr[i]['rationInstList'] = cacheSection[j]['rationInstList'];
                         cacheSection[j] = updateArr[i];
-                        cacheSection[j].type = me.type.complementary;
                     }
                 } else {
                     if (cacheSection[j][me.setting.header[0].dataCode] == updateArr[i][me.setting.header[0].dataCode]) {
-                        updateArr[i]['rationGljList'] = rationGLJOprObj.cache['_GLJ_' + cacheSection[j]['ID']] ? rationGLJOprObj.cache['_GLJ_' + cacheSection[j]['ID']] : [];
-                        updateArr[i]['rationCoeList'] = rationCoeOprObj.cache['_Coe_' + cacheSection[j]['ID']] ? rationCoeOprObj.cache['_Coe_' + cacheSection[j]['ID']] : [];
+                        updateArr[i]['rationGljList'] = rationGLJOprObj.cache['_GLJ_' + cacheSection[j]['ID']] ?
+                            rationGLJOprObj.cache['_GLJ_' + cacheSection[j]['ID']] :
+                            cacheSection[j]['rationGljList'] ?
+                                cacheSection[j]['rationGljList'] : [];
+                        updateArr[i]['rationCoeList'] = cacheSection[j]['rationCoeList'] ? cacheSection[j]['rationCoeList'] : [];
                         updateArr[i]['rationAssList'] = cacheSection[j]['rationAssList'];
                         updateArr[i]['rationInstList'] = cacheSection[j]['rationInstList'];
                         cacheSection[j] = updateArr[i];
-                        cacheSection[j].type = me.type.complementary;
                     }
                 }
             }
@@ -203,9 +205,6 @@ let rationOprObj = {
                             if(typeof target.col === 'undefined'){//定位不在表格内
                                 delDis = true;
                             }
-                            else {
-                                delDis = ration.type === 'std' ? true : false;
-                            }
                         }
                     }
                     else{
@@ -215,9 +214,17 @@ let rationOprObj = {
                         callback: function(){},
                         items: {
                             "delete": {name: "删除", disabled: delDis, icon: "fa-remove", callback: function (key, opt) {
-                                me.rationsCodes.splice(me.rationsCodes.indexOf(ration.code.toString()), 1);
-                                me.mixDel = 1;
-                                me.mixUpdateRequest([], [], [ration.ID]);
+
+                                let removeInfo = `确定要删除定额 “${ration.code}” 及其下的所有数据吗?`;
+                                $('#delRationAlert').find('.modal-body h5').text(removeInfo);
+                                $('#delRationAlert').modal('show');
+                                $('#delRationConfirm').bind('click', function () {
+                                    me.rationsCodes.splice(me.rationsCodes.indexOf(ration.code.toString()), 1);
+                                    me.mixDel = 1;
+                                    me.mixUpdateRequest([], [], [ration.ID]);
+                                    $('#delRationConfirm').unbind('click');
+                                    $('#delRationAlert').modal('hide');
+                                });
                             }}
                         }
                     };
@@ -233,21 +240,23 @@ let rationOprObj = {
         me.workBook.commandManager().register('rationDelete', function () {
             let rationSheet = me.workBook.getActiveSheet();
             let sels = rationSheet.getSelections(), updateArr = [], removeArr = [], lockCols = me.setting.view.lockColumns;
+            let removeCodes = [];
             let cacheSection = me.getCache();
             if(sels.length > 0){
                 for(let sel = 0; sel < sels.length; sel++){
                     if(sels[sel].colCount === me.setting.header.length){
                         if(cacheSection){
                             for(let i = 0; i < sels[sel].rowCount; i++){
-                                if(sels[sel].row + i < cacheSection.length && cacheSection[sels[sel].row + i].type !== me.type.std){
+                                if(sels[sel].row + i < cacheSection.length){
                                     removeArr.push(cacheSection[sels[sel].row + i].ID);
+                                    removeCodes.push(cacheSection[sels[sel].row + i].code);
                                     me.rationsCodes.splice(me.rationsCodes.indexOf(cacheSection[sels[sel].row + i].code.toString()), 1);
                                 }
                             }
                         }
                     }
                     else{
-                        if(sels[sel].col === 0 && me.isDef(cacheSection[sels[sel].row]) && cacheSection[sels[sel].row].type !== me.type.std){
+                        if(sels[sel].col === 0){
                             $('#alertText').text("编号不能为空,修改失败!");
                             $('#alertModalBtn').click();
                             $('#alertModalCls').click(function () {
@@ -260,12 +269,12 @@ let rationOprObj = {
                                 for(let i = sels[sel].row === -1 ? 1 : 0; i < sels[sel].rowCount; i++){
                                     if(sels[sel].row + i < cacheSection.length){
                                         for(let col = sels[sel].col; col <= sels[sel].col + sels[sel].colCount - 1; col++){
-                                            if(lockCols.indexOf(col) === -1 && cacheSection[sels[sel].row + i].type !== me.type.std){
+                                            if(lockCols.indexOf(col) === -1){
                                                 cacheSection[sels[sel].row + i][me.setting.header[col].dataCode] = '';
                                             }
                                         }
                                     }
-                                    if(me.isDef(cacheSection[sels[sel].row + i]) && cacheSection[sels[sel].row + i].type !== me.type.std){
+                                    if(cacheSection[sels[sel].row + i] && typeof cacheSection[sels[sel].row + i] !== 'undefined'){
                                         updateArr.push(cacheSection[sels[sel].row + i]);
                                     }
                                 }
@@ -274,10 +283,25 @@ let rationOprObj = {
                     }
                 }
             }
-            if(updateArr.length > 0 || removeArr.length > 0){
+            /*  if(updateArr.length > 0 || removeArr.length > 0){
+             me.mixUpdate = 1;
+             me.mixDel = removeArr.length > 0 ? 1 : 0;
+             me.mixUpdateRequest(updateArr, [], removeArr);
+             }*/
+            if(updateArr.length > 0){
                 me.mixUpdate = 1;
-                me.mixDel = removeArr.length > 0 ? 1 : 0;
-                me.mixUpdateRequest(updateArr, [], removeArr);
+                me.mixUpdateRequest(updateArr, [], []);
+            }
+            if(removeArr.length > 0){
+                let removeInfo = `确定要删除定额 “${removeCodes.join(',')}” 及其下的所有数据吗?`;
+                $('#delRationAlert').find('.modal-body h5').text(removeInfo);
+                $('#delRationAlert').modal('show');
+                $('#delRationConfirm').bind('click', function () {
+                    me.mixDel = 1;
+                    me.mixUpdateRequest([], [], removeArr);
+                    $('#delRationConfirm').unbind('click');
+                    $('#delRationAlert').modal('hide');
+                });
             }
 
         });
@@ -326,14 +350,13 @@ let rationOprObj = {
     },
     onCellEditStart: function(sender, args) {
         let me = rationOprObj;
-        let cacheSection = me.getCache();
-        if(!me.canRations || me.setting.view.lockColumns.indexOf(args.col) !== -1
-        || (me.isDef(cacheSection[args.row]) && cacheSection[args.row].type === me.type.std)){
+        if(!me.canRations || me.setting.view.lockColumns.indexOf(args.col) !== -1){
             args.cancel = true;
         }
         else{
             let rObj = sheetsOprObj.combineRationRowData(me.workBook.getSheet(0), me.setting, args.row);
             me.currentEditingRation = rObj;
+            let cacheSection = me.getCache();
             if (cacheSection) {
                 for (let j = 0; j < cacheSection.length; j++) {
                     if (cacheSection[j][me.setting.header[0].dataCode] == rObj[me.setting.header[0].dataCode]) {
@@ -431,23 +454,14 @@ let rationOprObj = {
     },
     onClipboardPasting: function(sender, args) {
         let me = rationOprObj;
-        let cacheSection = me.getCache();
         let maxCol = args.cellRange.col + args.cellRange.colCount -1;
         if(!me.canRations || !me.canPasted(args.cellRange.col, maxCol) || maxCol > me.setting.header.length - 1){
             args.cancel = true;
-            return;
-        }
-        let hasStd = false;
-        for(let row = args.cellRange.row, len = args.cellRange.row + args.cellRange.rowCount - 1; row < len; row++){
-            if(me.isDef(cacheSection[row]) && me.isDef(cacheSection[row].type) && cacheSection[row].type === me.type.std){
-                hasStd = true;
-            }
-        }
-        if(hasStd){
-            args.cancel = true;
         }
     },
+    //todo: overwrite?
     onClipboardPasted: function(e, info) {
+        console.log('cp');
         let me = rationOprObj;
         let cacheSection = me.getCache();
         let updateArr = [], addArr = [];
@@ -455,9 +469,9 @@ let rationOprObj = {
         for (let i = 0; i < items.length; i++) {
             let rowIdx = info.cellRange.row + i;
             if (cacheSection) {
-               /* if(!me.isValidUnit(items[i], rationUnits)){//无效单位
-                    items[i].unit = rowIdx < cacheSection.length  && typeof cacheSection[rowIdx].unit !== 'undefined' ? cacheSection[rowIdx].unit : '';
-                }*/
+                /*  if(!me.isValidUnit(items[i], rationUnits)){//无效单位
+                 items[i].unit = rowIdx < cacheSection.length  && typeof cacheSection[rowIdx].unit !== 'undefined' ? cacheSection[rowIdx].unit : '';
+                 }*/
                 if(!cacheSection[rowIdx] && info.cellRange.col === 0 ){
                     if(me.rationsCodes.indexOf(items[i].code.toString()) === -1){
                         //jobConten
@@ -501,33 +515,34 @@ let rationOprObj = {
                 }
 
             } else {
-                /*if(!me.isValidUnit(items[i], rationUnits)){//无效单位
-                    items[i].unit = '';
-                }*/
+                /* if(!me.isValidUnit(items[i], rationUnits)){//无效单位
+                 items[i].unit = '';
+                 }*/
                 //add
                 if(info.cellRange.col === 0){
                     //是否含有已存在的编号
-                        if(me.rationsCodes.indexOf(items[i].code.toString()) === -1){
-                            //jobConten
-                            if(jobContentOprObj && jobContentOprObj.currentSituation === jobContentOprObj.situations.ALL){
-                                items[i].jobContent = jobContentOprObj.currentJobContent ? jobContentOprObj.currentJobContent : '';
-                            }
-                            if(annotationOprObj && annotationOprObj.currentSituation === annotationOprObj.situations.ALL){
-                                items[i].annotation = annotationOprObj.currentAnnotation ? annotationOprObj.currentAnnotation : '';
-                            }
-                            me.setInitPrc(items[i]);
-                            addArr.push(items[i]);
+                    if(me.rationsCodes.indexOf(items[i].code.toString()) === -1){
+                        //jobConten
+                        if(jobContentOprObj && jobContentOprObj.currentSituation === jobContentOprObj.situations.ALL){
+                            items[i].jobContent = jobContentOprObj.currentJobContent ? jobContentOprObj.currentJobContent : '';
                         }
+                        if(annotationOprObj && annotationOprObj.currentSituation === annotationOprObj.situations.ALL){
+                            items[i].annotation = annotationOprObj.currentAnnotation ? annotationOprObj.currentAnnotation : '';
+                        }
+                        me.setInitPrc(items[i]);
+                        addArr.push(items[i]);
+                    }
                 }
             }
         };
-         if (updateArr.length > 0 || addArr.length > 0) {
-             me.mixUpdate = 1;
+        if (updateArr.length > 0 || addArr.length > 0) {
+            console.log(updateArr);
+            me.mixUpdate = 1;
             me.mixUpdateRequest(updateArr, addArr, []);
         }
         else{
-             me.getRationItems(me.currentSectionId);
-         }
+            me.getRationItems(me.currentSectionId);
+        }
     },
     setInitPrc: function (obj) {
         obj.labourPrice = 0;
@@ -544,60 +559,63 @@ let rationOprObj = {
     },
     getRationsCodes: function (repId) {
         let me = rationOprObj;
-        CommonAjax.post('api/getRationsCodes', {rationRepId: repId}, function (rstData) {
-            me.rationsCodes = rstData;
-        });
+        $.ajax({
+            type: 'post',
+            url: 'api/getRationsCodes',
+            data: {data: JSON.stringify({repId: repId})},
+            dataType: 'json',
+            success: function (result) {
+                if(!result.error){
+                    me.rationsCodes = result.data;
+                }
+            }
+        })
     },
     mixUpdateRequest: function(updateArr, addArr, removeIds, callback) {
         let me = rationOprObj;
         me.saveInString(updateArr);
-        CommonAjax.post('api/mixUpdateRationItems',
-            {rationRepId: getQueryString("repository"),  sectionId: me.currentSectionId, updateItems: updateArr, addItems: addArr, removeIds: removeIds},
-            function (rstData) {
-                //mark complementary
-                for(let i = 0, len = addArr.length; i < len; i++){
-                    addArr[i].type = me.type.complementary;
+        CommonAjax.post('api/mixUpdateRationItems', {sectionId: me.currentSectionId, updateItems: updateArr, addItems: addArr, removeIds: removeIds}, function (rstData) {
+            let cacheSection = me.updateCache(addArr, updateArr, removeIds, rstData);
+            cacheSection.sort(function(a, b){
+                let rst = 0;
+                if (a.code > b.code) rst = 1
+                else if (a.code < b.code) rst = -1;
+                return rst;
+            });
+            //add
+            let curRow = me.workBook.getActiveSheet().getActiveRowIndex();
+            me.rationSelInit(curRow);
+            //add
+            //jobContent
+            if(jobContentOprObj ){
+                jobContentOprObj.currentRationItems = cacheSection;
+                jobContentOprObj.setRadiosDisabled(cacheSection.length > 0 ? false : true, jobContentOprObj.radios);
+                if(cacheSection.length === 0){
+                    jobContentOprObj.updateSituation(pageOprObj.rationLibId, me.currentSectionId, 'NONE');
                 }
-                let cacheSection = me.updateCache(addArr, updateArr, removeIds, rstData);
-                cacheSection.sort(function(a, b){
-                    let rst = 0;
-                    if (a.code > b.code) rst = 1
-                    else if (a.code < b.code) rst = -1;
-                    return rst;
-                });
-                let curRow = me.workBook.getActiveSheet().getActiveRowIndex();
-                me.rationSelInit(curRow);
-                //jobContent
-                if(jobContentOprObj ){
-                    jobContentOprObj.currentRationItems = cacheSection;
-                    jobContentOprObj.setRadiosDisabled(cacheSection.length > 0 ? false : true, jobContentOprObj.radios);
-                  /*  if(cacheSection.length === 0){
-                        jobContentOprObj.updateSituation(pageOprObj.rationLibId, me.currentSectionId, 'NONE');
-                    }*/
-                    jobContentOprObj.setRadiosChecked(jobContentOprObj.currentSituation, jobContentOprObj.radios);
-                    if(jobContentOprObj.currentSituation === jobContentOprObj.situations.PARTIAL){
-                        jobContentOprObj.buildTablePartial(jobContentOprObj.tablePartial, jobContentOprObj.getGroup(cacheSection));
-                    }
+                jobContentOprObj.setRadiosChecked(jobContentOprObj.currentSituation, jobContentOprObj.radios);
+                if(jobContentOprObj.currentSituation === jobContentOprObj.situations.PARTIAL){
+                    jobContentOprObj.buildTablePartial(jobContentOprObj.tablePartial, jobContentOprObj.getGroup(cacheSection));
                 }
-                if(annotationOprObj ){
-                    annotationOprObj.setRadiosDisabled(cacheSection.length > 0 ? false : true, annotationOprObj.radios);
-                    if(cacheSection.length === 0){
-                        annotationOprObj.updateAnnoSituation(pageOprObj.rationLibId, me.currentSectionId, 'NONE');
-                    }
-                    annotationOprObj.setRadiosChecked(annotationOprObj.currentSituation, annotationOprObj.radios);
-                    if(annotationOprObj.currentSituation === annotationOprObj.situations.PARTIAL){
-                        annotationOprObj.buildTablePartial(annotationOprObj.fzTablePartial, annotationOprObj.getGroup(cacheSection));
-                    }
+            }
+            if(annotationOprObj ){
+                annotationOprObj.setRadiosDisabled(cacheSection.length > 0 ? false : true, annotationOprObj.radios);
+                if(cacheSection.length === 0){
+                    annotationOprObj.updateAnnoSituation(pageOprObj.rationLibId, me.currentSectionId, 'NONE');
                 }
-                me.showRationItems(me.currentSectionId);
-                me.mixUpdate = 0;
-                me.mixDel = 0;
-                if(callback) callback();
-                sectionTreeObj.workBook.focus(false);
-                rationOprObj.workBook.focus(true);
-            }, function () {
-                me.getRationItems(me.currentSectionId);
-            });
+                annotationOprObj.setRadiosChecked(annotationOprObj.currentSituation, annotationOprObj.radios);
+                if(annotationOprObj.currentSituation === annotationOprObj.situations.PARTIAL){
+                    annotationOprObj.buildTablePartial(annotationOprObj.fzTablePartial, annotationOprObj.getGroup(cacheSection));
+                }
+            }
+            me.showRationItems(me.currentSectionId);
+            me.mixUpdate = 0;
+            me.mixDel = 0;
+            me.workBook.focus(true);
+            if(callback) callback();
+        }, function () {
+            me.getRationItems(me.currentSectionId);
+        });
     },
     getRationItems: function(sectionID, callback = null){
         if (sectionID != -1) {
@@ -611,40 +629,30 @@ let rationOprObj = {
                 //annotation
                 annotationOprObj.rationAnnotationOpr(me.currentRations["_SEC_ID_" + sectionID]);
                 me.showRationItems(sectionID);
-                if(callback) {
+                sectionTreeObj.removeBtn.removeClass('disabled');
+                if(callback){
                     callback();
                 }
             } else {
-                CommonAjax.post('/complementaryRation/api/getRationItems', {rationRepId: pageOprObj.rationLibId, sectionId: sectionID}, function (rstData) {
+                CommonAjax.post('api/getRationItems', {sectionId: sectionID}, function (rstData) {
                     me.currentRations["_SEC_ID_" + sectionID] = rstData;
-                    me.currentRations["_SEC_ID_" + sectionID] = me.sortByCode(me.currentRations["_SEC_ID_" + sectionID]);
+                    me.sortByCode(me.currentRations["_SEC_ID_" + sectionID]);
                     //job--
                     jobContentOprObj.currentRationItems = me.currentRations["_SEC_ID_" + sectionID];
                     jobContentOprObj.rationJobContentOpr(me.currentRations["_SEC_ID_" + sectionID]);
                     //annotation
                     annotationOprObj.rationAnnotationOpr(me.currentRations["_SEC_ID_" + sectionID]);
                     me.showRationItems(sectionID);
+                    sectionTreeObj.removeBtn.removeClass('disabled');
                     if(callback) {
                         callback();
                     }
+                }, function () {
+                    sectionTreeObj.removeBtn.removeClass('disabled');
                 });
             }
         }
     },
-    setColor: function (cache) {
-        let me = this;
-        let sheet = me.workBook.getSheet(0);
-        sheet.suspendPaint();
-        for(let i = 0, len = cache.length; i < len; i++){
-            if(cache[i].type === me.type.complementary){
-                sheet.getRange(i, -1, 1, -1).foreColor('gray');
-            }
-            else {
-                sheet.getRange(i, -1, 1, -1).foreColor('');
-            }
-        }
-        sheet.resumePaint();
-    },
     showRationItems: function(sectionID){
         let me = rationOprObj,
             sheetGLJ = rationGLJOprObj.sheet, settingGLJ = rationGLJOprObj.setting,
@@ -656,7 +664,6 @@ let rationOprObj = {
                 let cacheSection = me.currentRations["_SEC_ID_" + sectionID];
                 sheetCommonObj.cleanData(me.workBook.getSheet(0), me.setting, -1);
                 sheetsOprObj.showData(me.workBook.getSheet(0), me.setting, cacheSection);
-                me.setColor(cacheSection);
                 //combo
                 //sheetCommonObj.setStaticCombo(me.workBook.getActiveSheet(), 0, 2, cacheSection.length, rationUnits, 10, false);
                 //--sheetCommonObj.setDynamicCombo(me.workBook.getActiveSheet(), 0, 2, me.workBook.getActiveSheet().getRowCount(), rationUnits, 10, false);
@@ -693,25 +700,11 @@ let rationOprObj = {
                 sheetCommonObj.cleanSheet(sheetAss, settingAss, -1);
                 sheetCommonObj.cleanSheet(sheetInst, settingInst, -1);
             }
-           //--- me.workBook.focus(true);
+            //--- me.workBook.focus(true);
         }
         sectionTreeObj.workBook.focus(true);
     },
     sortByCode: function(arr){
-        let me = rationOprObj;
-        //std complementary
-        let stdArr = [], compleArr = [];
-        for(let i = 0, len = arr.length; i < len; i++){
-            if(arr[i].type === me.type.std){
-                stdArr.push(arr[i]);
-            }
-            else if(arr[i].type === me.type.complementary){
-                compleArr.push(arr[i]);
-            }
-        }
-        stdArr.sort(compare());
-        compleArr.sort(compare());
-        return stdArr.concat(compleArr);
         function compare(){
             return function (a, b) {
                 let rst = 0;
@@ -724,7 +717,7 @@ let rationOprObj = {
                 return rst;
             }
         }
-       // arr.sort(compare());
+        arr.sort(compare());
     },
     saveInString(datas){
         for(let i = 0, len = datas.length; i < len; i++){

+ 6 - 15
web/building_saas/complementary_ration_lib/js/ration_assist.js

@@ -3,7 +3,6 @@
  */
 var rationAssistOprObj = {
     sheet: null,
-    libID: null,
     ration: null,
     setting: {
         header:[
@@ -23,12 +22,7 @@ var rationAssistOprObj = {
     buildSheet: function(sheet) {
         var me = this;
         me.sheet = sheet;
-        //me.libID = storageUtil.getSessionCache("RationGrp","repositoryID"); // 不可靠,有时取不到
-        me.libID = pageOprObj.rationLibId;
-        if (me.libID == undefined){me.libID = getQueryString('repository')};
-
         sheetCommonObj.initSheet(me.sheet, me.setting, 30);
-
         me.sheet.bind(GC.Spread.Sheets.Events.ClipboardPasting, me.onClipboardPasting);
         me.sheet.bind(GC.Spread.Sheets.Events.ClipboardPasted, me.onClipboardPasted);
         me.sheet.bind(GC.Spread.Sheets.Events.EditStarting, me.onEditStarting);
@@ -41,7 +35,7 @@ var rationAssistOprObj = {
         args.sheet.repaint();
         let cellType = args.sheet.getCellType(args.row, 5);
         if(cellType.typeName !== 'undefined' && cellType.typeName === '1'){
-          //  sheetCommonObj.setStaticCombo(args.sheet, 0, 5, 0, me.setting.comboItems, false);
+            //  sheetCommonObj.setStaticCombo(args.sheet, 0, 5, 0, me.setting.comboItems, false);
             sheetCommonObj.setDynamicCombo(args.sheet, 0, 5, me.sheet.getRowCount(), me.setting.comboItems, false, false);
         }
     },
@@ -51,7 +45,7 @@ var rationAssistOprObj = {
         let rationSection = rationOprObj.getCache();
         let rationRow = rationOprObj.workBook.getSheet(0).getSelections()[0].row;
         me.ration = rationRow < rationSection.length ? rationSection[rationRow] : null;
-        if (!me.ration || (me.ration && me.ration.type === rationOprObj.type.std)) {
+        if (!me.ration) {
             args.cancel = true;
         }
     },
@@ -82,7 +76,7 @@ var rationAssistOprObj = {
         let rationSection = rationOprObj.getCache();
         let rationRow = rationOprObj.workBook.getSheet(0).getSelections()[0].row;
         me.ration = rationRow < rationSection.length ? rationSection[rationRow] : null;
-        if(!me.ration || (me.ration && me.ration.type === rationOprObj.type.std)){
+        if(!me.ration){
             args.cancel = true;
         }
     },
@@ -103,7 +97,7 @@ var rationAssistOprObj = {
             return;
         }
         else if(args.col === 4 && args.editingText && (args.editingText.toString().trim().length === 0 ||
-                isNaN(args.editingText) || args.editingText % 1 !== 0)){
+            isNaN(args.editingText) || args.editingText % 1 !== 0)){
             args.sheet.setValue(args.row, args.col, args.row < assList.length ? assList[args.row][dataCode] : 0);
             alert(me.setting.header[args.col].headerName + '只能为整数!');
             return;
@@ -111,7 +105,7 @@ var rationAssistOprObj = {
         // 新增
         if (args.row >= assList.length) {
             if (assObj.decimal == undefined || assObj.decimal == null){assObj.decimal = '0';};
-            if (assObj.carryBit == undefined || assObj.carryBit == null){assObj.carryBit = '四舍五入';};
+            if (assObj.carryBit == undefined || assObj.carryBit == null){assObj.carryBit = '进一';};
             assList.push(assObj);
         }
         // 修改
@@ -147,9 +141,6 @@ var rationAssistOprObj = {
         let me = rationAssistOprObj;
         let workBook = me.sheet.getParent();
         workBook.commandManager().register('rationAssDel', function () {
-            if(!me.ration || me.ration.type === rationOprObj.type.std){
-                return;
-            }
             let sels = me.sheet.getSelections(), isUpdate = false;
             if(me.ration){
                 let curCahe = me.ration.rationAssList;
@@ -180,7 +171,7 @@ var rationAssistOprObj = {
         var me = this;
         me.ration = ration;
 
-        sheetCommonObj.cleanSheet(me.sheet, me.setting, -1);
+        sheetCommonObj.cleanData(me.sheet, me.setting, -1);
         sheetCommonObj.unShieldAllCells(me.sheet);
 
         if (ration == undefined || ration.rationAssList == undefined ||

+ 314 - 223
web/building_saas/complementary_ration_lib/js/ration_coe.js

@@ -1,52 +1,75 @@
 /**
  * Created by CSL on 2017-06-08.
  */
- //modified by zhong on 2017-09-25
+    //modified by zhong on 2017-09-25
 var rationCoeOprObj = {
-    sheet: null,
-    libID: null,
-    curRation: null,
-    tempDelArr: [],
-    cache: {},
-    setting: {
-        header:[
-            {headerName:"编号",headerWidth:120,dataCode:"serialNo", dataType: "Number", hAlign: 'center'},
-            {headerName:"名称",headerWidth:400,dataCode:"name", dataType: "String", hAlign: 'left'},
-            {headerName:"内容",headerWidth:300,dataCode:"content", dataType: "String", hAlign: 'left'}
-        ],
-        view:{
-            comboBox:[],
-            lockColumns:[1,2]
-        }
-    },
+        sheet: null,
+        curRation: null,
+        tempDelArr: [],
+        cache: {},
+        setting: {
+            header:[
+                {headerName:"编号",headerWidth:50,dataCode:"serialNo", dataType: "Number", hAlign: 'center'},
+                {headerName:"名称",headerWidth:280,dataCode:"name", dataType: "String", hAlign: 'left'},
+                {headerName:"内容",headerWidth:150,dataCode:"content", dataType: "String", hAlign: 'left'}
+            ],
+            view:{
+                comboBox:[],
+                lockColumns:[1,2]
+            }
+        },
 
-    buildSheet: function(sheet) {
-        var me = this;
-        me.sheet = sheet;
-        //me.libID = storageUtil.getSessionCache("RationGrp","repositoryID"); // 不可靠,有时取不到
-        me.libID = pageOprObj.rationLibId;
-        if (me.libID == undefined){me.libID = getQueryString('repository')};
-        sheetCommonObj.initSheet(me.sheet, me.setting, 30);
-        me.sheet.bind(GC.Spread.Sheets.Events.ClipboardPasting, me.onClipboardPasting);
-        me.sheet.bind(GC.Spread.Sheets.Events.ClipboardPasted, me.onClipboardPasted);
-        me.sheet.bind(GC.Spread.Sheets.Events.EditStarting, me.onEditStarting);
-        me.sheet.bind(GC.Spread.Sheets.Events.EditEnded, me.onEditEnded);
-       // me.sheet.bind(GC.Spread.Sheets.Events.RangeChanged, me.onRangeChanged);
-    },
+        buildSheet: function(sheet) {
+            var me = this;
+            me.sheet = sheet;
+            sheetCommonObj.initSheet(me.sheet, me.setting, 30);
+            me.sheet.bind(GC.Spread.Sheets.Events.ClipboardPasting, me.onClipboardPasting);
+            me.sheet.bind(GC.Spread.Sheets.Events.ClipboardPasted, me.onClipboardPasted);
+            me.sheet.bind(GC.Spread.Sheets.Events.EditStarting, me.onEditStarting);
+            me.sheet.bind(GC.Spread.Sheets.Events.EditEnded, me.onEditEnded);
+            //右键
+            //me.onContextmenuOpr();
+        },
 
-    onClipboardPasting: function(sender, args) {
-        var me = rationCoeOprObj;
-        let rationSection = rationOprObj.getCache();
-        let rationRow = rationOprObj.workBook.getSheet(0).getSelections()[0].row;
-        me.curRation = rationRow < rationSection.length ? rationSection[rationRow] : null;
-        if (args.cellRange.colCount != 1 || args.cellRange.col != 0 || !(me.curRation) || (me.curRation && me.curRation.type === rationOprObj.type.std)) {
-            args.cancel = true;
-        }
-    },
+        isDef: function (v) {
+            return v !== undefined && v !== null;
+        },
+
+        upMove: function (thisObj, preObj, cell) {
+            let me = this;
+            let tempNo = thisObj.no;
+            thisObj.no = preObj.no;
+            preObj.no = tempNo;
+            //ajax
+            me.updateCurRation(function () {
+                me.showCoeItems(me.curRation.ID);
+                me.sheet.setActiveCell(cell.row, cell.col);
+            });
+        },
+
+        downMove: function (thisObj, nextObj, cell) {
+            let me = this;
+            let tempNo = thisObj.no;
+            thisObj.no = nextObj.no;
+            nextObj.no = tempNo;
+            me.updateCurRation(function () {
+                me.showCoeItems(me.curRation.ID);
+                me.sheet.setActiveCell(cell.row, cell.col);
+            });
+        },
+
+        onClipboardPasting: function(sender, args) {
+            var me = rationCoeOprObj;
+            let rationSection = rationOprObj.getCache();
+            let rationRow = rationOprObj.workBook.getActiveSheet().getSelections()[0].row;
+            me.curRation = rationRow < rationSection.length ? rationSection[rationRow] : null;
+            if (args.cellRange.colCount != 1 || args.cellRange.col != 0 || !(me.curRation)) {
+                args.cancel = true;
+            }
+        },
 
-    onClipboardPasted: function(e, info) {
-        var me = rationCoeOprObj;
-        if (me.libID) {
+        onClipboardPasted: function(e, info) {
+            var me = rationCoeOprObj;
             // 修改第一列(编号)
             if (info.cellRange.col == 0) {
                 me.tempDelArr = [];
@@ -81,14 +104,14 @@ var rationCoeOprObj = {
                 }
                 //delete in front
                 if(me.tempDelArr.length > 0){
-                   for(let i = 0, len = me.tempDelArr.length; i < len; i++){
-                       for(let j = 0; j < curCache.length; j++){
-                           if(me.tempDelArr[i].org.serialNo === curCache[j].serialNo){
-                               curCache.splice(j, 1);
-                               break;
-                           }
-                       }
-                   }
+                    for(let i = 0, len = me.tempDelArr.length; i < len; i++){
+                        for(let j = 0; j < curCache.length; j++){
+                            if(me.tempDelArr[i].org.serialNo === curCache[j].serialNo){
+                                curCache.splice(j, 1);
+                                break;
+                            }
+                        }
+                    }
                 }
                 me.addCoeItems(coeNos);
                 if(isRefresh){
@@ -97,208 +120,276 @@ var rationCoeOprObj = {
             } else {
                 //修改其它列。
             }
-        }
-    },
-    onEditStarting: function (sender, args) {
-        let me = rationCoeOprObj;
-        let rationSection = rationOprObj.getCache();
-        let rationRow = rationOprObj.workBook.getSheet(0).getSelections()[0].row;
-        me.curRation = rationRow < rationSection.length ? rationSection[rationRow] : null;
-        if(!me.curRation || args.col !== 0 || (me.curRation && me.curRation.type === rationOprObj.type.std)){
-            args.cancel = true;
-        }
+        },
+        onEditStarting: function (sender, args) {
+            let me = rationCoeOprObj;
+            let rationSection = rationOprObj.getCache();
+            let rationRow = rationOprObj.workBook.getActiveSheet().getSelections()[0].row;
+            me.curRation = rationRow < rationSection.length ? rationSection[rationRow] : null;
+            if(!me.curRation || args.col !== 0){
+                args.cancel = true;
+            }
 
-    },
-    onEditEnded: function(sender, args){
-        var me = rationCoeOprObj;
-        if (args.col == 0 && args.editingText && args.editingText.toString().trim().length > 0 && !isNaN(args.editingText)) {   // 编号列
-            let curCahe = typeof me.cache["_Coe_" + me.curRation.ID] !== 'undefined' ? me.cache["_Coe_" + me.curRation.ID] : [];
-            me.tempDelArr = [];
-            //update
-            if(args.row < curCahe.length && args.editingText != curCahe[args.row].serialNo){
-                let isExist = false;
-                for(let i = 0, len = curCahe.length; i < len; i++){
-                    if(args.editingText == curCahe[i].serialNo){
-                        isExist = true;
-                        break;
+        },
+        onEditEnded: function(sender, args){
+            var me = rationCoeOprObj;
+            if (args.col == 0 && args.editingText && args.editingText.toString().trim().length > 0 && !isNaN(args.editingText)) {   // 编号列
+                let curCahe = typeof me.cache["_Coe_" + me.curRation.ID] !== 'undefined' ? me.cache["_Coe_" + me.curRation.ID] : [];
+                me.tempDelArr = [];
+                //update
+                if(args.row < curCahe.length && args.editingText != curCahe[args.row].serialNo){
+                    let isExist = false;
+                    for(let i = 0, len = curCahe.length; i < len; i++){
+                        if(args.editingText == curCahe[i].serialNo){
+                            isExist = true;
+                            break;
+                        }
+                    }
+                    if(!isExist){
+                        me.tempDelArr.push({org: curCahe[args.row], newNo: args.editingText});
+                        curCahe.splice(args.row, 1);
+                        me.addCoeItems([args.editingText]);
+                    }
+                    else{
+                        me.showCoeItems(me.curRation.ID);
                     }
                 }
-                if(!isExist){
-                    me.tempDelArr.push({org: curCahe[args.row], newNo: args.editingText});
-                    curCahe.splice(args.row, 1);
-                    me.addCoeItems([args.editingText]);
-                }
+                //insert
                 else{
-                    me.showCoeItems(me.curRation.ID);
+                    me.addCoeItems([args.editingText]);
                 }
             }
-            //insert
             else{
-                me.addCoeItems([args.editingText]);
+                sheetCommonObj.cleanData(me.sheet, me.setting, -1);
+                me.showCoeItems(me.curRation.ID);
             }
-        }
-        else{
-            sheetCommonObj.cleanData(me.sheet, me.setting, -1);
-            me.showCoeItems(me.curRation.ID);
-        }
-    },
+        },
 
-    bindRationCoeDel: function () {
-        let me = rationCoeOprObj;
-        let workBook = me.sheet.getParent();
-        workBook.commandManager().register('rationCoeDel', function () {
-            if(!me.curRation || me.curRation.type === rationOprObj.type.std){
-                return;
-            }
-            let sels = me.sheet.getSelections(), isUpdate = false;
-            let curCahe = me.cache["_Coe_" + me.curRation.ID];
-            for(let i = 0, len = sels.length; i < len; i ++ ){
-                if(sels[i].colCount === me.setting.header.length){
-                    if(sels[i].row < curCahe.length){
-                        isUpdate = true;
-                        curCahe.splice(sels[i].row, sels[i].rowCount);
+        bindRationCoeDel: function () {
+            let me = rationCoeOprObj;
+            let workBook = me.sheet.getParent();
+            workBook.commandManager().register('rationCoeDel', function () {
+                let sels = me.sheet.getSelections(), isUpdate = false;
+                let curCahe = me.cache["_Coe_" + me.curRation.ID];
+                for(let i = 0, len = sels.length; i < len; i ++ ){
+                    if(sels[i].colCount === me.setting.header.length){
+                        if(sels[i].row < curCahe.length){
+                            isUpdate = true;
+                            curCahe.splice(sels[i].row, sels[i].rowCount);
+                        }
                     }
                 }
-            }
-            if(isUpdate){
-                me.updateCurRation(function () {
-                    me.sheet.getParent().focus(true);
-                });
-                sheetCommonObj.cleanData(me.sheet, me.setting, -1);
-                me.showCoeItems(me.curRation.ID);
-            }
-        });
-        workBook.commandManager().setShortcutKey(null, GC.Spread.Commands.Key.del, false, false, false, false);
-        workBook.commandManager().setShortcutKey('rationCoeDel', GC.Spread.Commands.Key.del, false, false, false, false);
-    },
-    getRecoveryArr: function (tempDelArr, newArr) {//获得更新的coe不存在,恢复删除的被更新数据
-        let rst = [];
-        for(let i = 0, len = tempDelArr.length; i < len; i++){
-            let isExist = false;
-            for(let j = 0, jLen = newArr.length; j < jLen; j++){
-                if(tempDelArr[i].newNo == newArr[j].serialNo){
-                    isExist = true;
-                    break;
+                if(isUpdate){
+                    me.updateCurRation(function () {
+                        me.sheet.getParent().focus(true);
+                    });
+                    sheetCommonObj.cleanData(me.sheet, me.setting, -1);
+                    me.showCoeItems(me.curRation.ID);
                 }
-            }
-            if(!isExist){
-                rst.push(tempDelArr[i].org);
-            }
-        }
-        return rst;
-    },
-    addCoeItems: function(coeNos) {
-        var me = this;
-        sheetCommonObj.cleanData(me.sheet, me.setting, -1);
-
-        var curCache = me.cache["_Coe_" + me.curRation.ID];
-        var temp = [];
-        if (curCache) {
-            for (var i = 0; i < coeNos.length; i++) {
-                var isExist = false;
-                for (let obj of curCache) {
-                    if (obj.serialNo == coeNos[i]) {
+            });
+            workBook.commandManager().setShortcutKey(null, GC.Spread.Commands.Key.del, false, false, false, false);
+            workBook.commandManager().setShortcutKey('rationCoeDel', GC.Spread.Commands.Key.del, false, false, false, false);
+        },
+        getRecoveryArr: function (tempDelArr, newArr) {//获得更新的coe不存在,恢复删除的被更新数据
+            let rst = [];
+            for(let i = 0, len = tempDelArr.length; i < len; i++){
+                let isExist = false;
+                for(let j = 0, jLen = newArr.length; j < jLen; j++){
+                    if(tempDelArr[i].newNo == newArr[j].serialNo){
                         isExist = true;
                         break;
+                    }
+                }
+                if(!isExist){
+                    rst.push(tempDelArr[i].org);
+                }
+            }
+            return rst;
+        },
+        addCoeItems: function(coeNos) {
+            var me = this;
+            sheetCommonObj.cleanData(me.sheet, me.setting, -1);
+
+            var curCache = me.cache["_Coe_" + me.curRation.ID];
+            var temp = [];
+            if (curCache) {
+                for (var i = 0; i < coeNos.length; i++) {
+                    var isExist = false;
+                    for (let obj of curCache) {
+                        if (obj.serialNo == coeNos[i]) {
+                            isExist = true;
+                            break;
+                        };
+                    };
+                    if (!isExist) {
+                        temp.push(coeNos[i]);
                     };
                 };
-                if (!isExist) {
-                    temp.push(coeNos[i]);
-                };
+            }else{
+                for (let obj of coeNos){temp.push(obj)};
             };
-        }else{
-            for (let obj of coeNos){temp.push(obj)};
-        };
 
-        if(temp.length == 0){
-            me.showCoeItems(me.curRation.ID);
-            //sheetCommonObj.lockCells(me.sheet, me.setting);
-        }else{
-            CommonAjax.post('api/getCoeItemsByNos', {libID: me.libID, coeNos: temp}, function (rstData) {
-                var rstArr = [];
-                for (let obj of rstData){rstArr.push(obj)};
-                if (curCache) {
-                    curCache = curCache.concat(rstArr);
-                }else{
-                    curCache = rstArr;
-                }
-                let recoveryArr = me.getRecoveryArr(me.tempDelArr, rstData);
-                if(recoveryArr.length > 0){
-                    curCache = curCache.concat(recoveryArr);
-                }
-                me.cache["_Coe_" + me.curRation.ID] = curCache;
-                me.updateCurRation(function () {
-                    me.sheet.getParent().focus(true);
-                });
+            if(temp.length == 0){
                 me.showCoeItems(me.curRation.ID);
-            });
-        };
-    },
-
-    getCoeItems: function(ration, callback) {
-        var me = this;
-        me.curRation = ration;
+                //sheetCommonObj.lockCells(me.sheet, me.setting);
+            }else{
+                $.ajax({
+                    type:"POST",
+                    url:"api/getCoeItemsByNos",
+                    data: {"data": JSON.stringify({"coeNos": temp})},
+                    dataType:"json",
+                    cache:false,
+                    timeout:5000,
+                    success:function(result){
+                        if (result) {
+                            var rstArr = [];
+                            let newNo = curCache && curCache.length > 0 ? curCache[curCache.length - 1].no + 1 : 1;
+                            for (let obj of result.data){
+                                obj.no = newNo++;
+                                rstArr.push(obj)
+                            }
+                            if (curCache) {
+                                curCache = curCache.concat(rstArr);
+                            }else{
+                                curCache = rstArr;
+                            }
+                            let recoveryArr = me.getRecoveryArr(me.tempDelArr, result.data);
+                            if(recoveryArr.length > 0){
+                                curCache = curCache.concat(recoveryArr);
+                            }
+                            me.cache["_Coe_" + me.curRation.ID] = curCache;
+                            me.updateCurRation(function () {
+                                me.sheet.getParent().focus(true);
+                            });
+                            me.showCoeItems(me.curRation.ID);
+                        };
+                        //sheetCommonObj.lockCells(me.sheet, me.setting);
+                    },
+                    error:function(err){
+                        alert(err);
+                    }
+                });
+            };
+        },
 
-        /*if (ration == undefined || ration.rationCoeList == undefined ||
-            ration.rationCoeList.length == 0){return;};*/
+        getCoeItems: function(ration, callback) {
+            var me = this;
+            me.curRation = ration;
 
-        var coeList = ration.rationCoeList ? ration.rationCoeList : [];
-        let coeIDs = [];
-        for(let i = 0, len = coeList.length; i < len; i++){
-            coeIDs.push(coeList[i].ID);
-        }
-        var curCache = me.cache["_Coe_" + ration.ID];
-        if (curCache) {
-            me.showCoeItems(ration.ID);
-            //sheetCommonObj.lockCells(me.sheet, me.setting);
-        } else if(!curCache && typeof coeList !== 'undefined' && coeList.length > 0) {
-            var data = {"libID": me.libID, "coeIDs": coeIDs};
-            CommonAjax.post('api/getCoeItemsByIDs', data, function (rstData) {
-                sheetCommonObj.cleanData(me.sheet, me.setting, -1);
-                var tempResult = [];
-                for (let obj of rstData) {
-                    tempResult.push(obj);
-                };
-                me.cache["_Coe_" + ration.ID] = tempResult;
+            /*if (ration == undefined || ration.rationCoeList == undefined ||
+             ration.rationCoeList.length == 0){return;};*/
 
+            var coeList = ration.rationCoeList;
+            let coeIDs = [];
+            for(let i = 0, len = coeList.length; i < len; i++){
+                coeIDs.push(coeList[i].ID);
+            }
+            var curCache = me.cache["_Coe_" + ration.ID];
+            if (curCache) {
                 me.showCoeItems(ration.ID);
                 //sheetCommonObj.lockCells(me.sheet, me.setting);
-                if(callback) callback();
-            });
-        };
-    },
+            } else if(!curCache && typeof coeList !== 'undefined' && coeList.length > 0) {
+                var data = {"coeIDs": coeIDs};
+                $.ajax({
+                    type:"POST",
+                    url:"api/getCoeItemsByIDs",
+                    data: {"data": JSON.stringify(data)},
+                    dataType:"json",
+                    cache:false,
+                    timeout:5000,
+                    success:function(result){
+                        sheetCommonObj.cleanData(me.sheet, me.setting, -1);
+                        if (result.data) {
+                            var tempResult = [];
+                            for (let obj of result.data) {
+                                for(let i = 0, len = coeList.length; i < len; i++){
+                                    if(obj.ID === coeList[i].ID){
+                                        obj.no = coeList[i].no;
+                                        tempResult.push(obj);
+                                        break;
+                                    }
+                                }
+                            };
 
-    showCoeItems: function(rationID) {
-        var me = this;
-        var curCache = me.cache["_Coe_" + rationID];
-        if (curCache) {
-            curCache.sort(function(a, b) {
-                var rst = 0;
-                if (a.serialNo > b.serialNo) rst = 1
-                else if (a.serialNo < b.serialNo) rst = -1;
-                return rst;
-            });
-            sheetsOprObj.showData(me.sheet, me.setting, curCache);
-        }
-    },
 
-    updateCurRation: function(callback) {
-        var me = this, updateArr = [];
-        if (me.curRation) {
-            var rst = [];
-            var curCache = me.cache["_Coe_" + me.curRation.ID];
+                            me.cache["_Coe_" + ration.ID] = tempResult;
+
+                            me.showCoeItems(ration.ID);
+                        }
+                        //sheetCommonObj.lockCells(me.sheet, me.setting);
+                        if(callback) callback();
+                    },
+                    error:function(err){
+                        alert(err);
+                    }
+                });
+            };
+        },
+
+        showCoeItems: function(rationID) {
+            var me = this;
+            var curCache = me.cache["_Coe_" + rationID];
             if (curCache) {
-                for (let obj of curCache) {
-                    rst.push({ID: obj.ID, no: obj.no});
-                };
-                me.curRation.rationCoeList = rst;
-                updateArr.push(me.curRation);
+                curCache.sort(function(a, b) {
+                    var rst = 0;
+                    if (a.no > b.no) rst = 1
+                    else if (a.no < b.no) rst = -1;
+                    return rst;
+                });
+                sheetsOprObj.showData(me.sheet, me.setting, curCache);
+            }
+        },
+
+        updateCurRation: function(callback) {
+            var me = this, updateArr = [];
+            if (me.curRation) {
+                var rst = [];
+                var curCache = me.cache["_Coe_" + me.curRation.ID];
+                if (curCache) {
+                    for (let obj of curCache) {
+                        rst.push({ID: obj.ID, no: obj.no});
+                    }
+                    me.curRation.rationCoeList = rst;
+                    updateArr.push(me.curRation);
+                    rationOprObj.mixUpdateRequest(updateArr, [], [], function () {
+                        if(callback) callback();
+                    });
+                }
+            }
+        },
+
+        //更新本节所有定额
+        updateSectionRation: function (rations, coe, callback) {
+            let me = this;
+            let updateArr = [];
+            for(let i = 0, len = rations.length; i < len; i++){
+                if(rations[i].ID !== me.curRation.ID){
+                    console.log(`rations[i]`);
+                    console.log(rations[i]);
+                    let rationCoeList = rations[i].rationCoeList;
+                    let isExist = false;
+                    let newNo = 1;
+                    for(let j = 0, jLen = rationCoeList.length; j < jLen; j++){
+                        if(rationCoeList[j].no >= newNo){
+                            newNo = rationCoeList[j].no + 1;
+                        }
+                        if(rationCoeList[j].ID === coe.ID){
+                            isExist = true;
+                        }
+                    }
+                    if(!isExist){
+                        rationCoeList.push({ID: coe.ID, no: newNo});
+                        updateArr.push(rations[i]);
+                    }
+                }
+                console.log(rations[i]);
+            }
+            if(updateArr.length > 0){
                 rationOprObj.mixUpdateRequest(updateArr, [], [], function () {
-                    if(callback) callback();
+                    if(callback) callback(updateArr);
                 });
-            };
-        };
+            }
+        }
     }
-}
 
 

+ 62 - 5
web/building_saas/complementary_ration_lib/js/ration_glj.js

@@ -94,6 +94,7 @@ var rationGLJOprObj = {
     },
     onContextmenuOpr: function () {//右键菜单
         let me = this;
+        let raCoe = rationCoeOprObj;
         $.contextMenu({
             selector: '#rdSpread',
             build: function($triggerElement, e){
@@ -102,12 +103,13 @@ var rationGLJOprObj = {
                 let sheet = me.sheet;
                 let addDis = false, delDis = false;
                 let rationGlj = [];
-                if(me.sheet.getParent().getActiveSheet() === me.sheet && target.hitTestType === 3){//在表格内&& typeof target.row !== 'undefined' && typeof target.col !== 'undefined'
+                if(me.sheet.getParent().getActiveSheetIndex() === 0 && target.hitTestType === 3){//在表格内&& typeof target.row !== 'undefined' && typeof target.col !== 'undefined'
+                    //rationGlj表
                     if(typeof target.row !== 'undefined'){
                         //控制按钮是否可用
                         sheet.setActiveCell(target.row, target.col);
-                        //当前定额为补充定额时按钮有效
-                        if(me.currentRationItem && me.currentRationItem.type === 'complementary'){
+                        console.log(me.currentRationItem);
+                        if(me.currentRationItem){
                             rationGlj =  me.cache['_GLJ_' + me.currentRationItem.ID];
                             if(!rationGlj ||target.row >= rationGlj.length){//右键定位在有数据的行,删除键才显示可用
                                 delDis = true;
@@ -153,6 +155,62 @@ var rationGLJOprObj = {
                         }
                     };
                 }
+                //rationCoe表
+                else if(me.sheet.getParent().getActiveSheetIndex() === 2 && target.hitTestType === 3 && typeof target.row !== 'undefined' && typeof target.col !== 'undefined'){
+                    let currentCache = raCoe.curRation && raCoe.isDef(raCoe.cache["_Coe_" + raCoe.curRation.ID])  ? raCoe.cache["_Coe_" + raCoe.curRation.ID] : [];
+                    sheet.setActiveCell(target.row, target.col);
+                    //控制按钮是否可用
+                    let upDis = false,
+                        downDis = false,
+                        refDis = false;
+                    if(target.row >= currentCache.length){
+                        upDis = true;
+                        downDis = true;
+                        refDis = true;
+                    }
+                    else {
+                        if(!raCoe.isDef(currentCache[target.row - 1])){
+                            upDis = true;
+                        }
+                        if(!raCoe.isDef(currentCache[target.row + 1])){
+                            downDis = true;
+                        }
+                    }
+                    return {
+                        callback: function(){},
+                        items: {
+                            "upMove": {name: "上移", disabled: upDis, icon: "fa-arrow-up", callback: function (key, opt) {
+                                raCoe.upMove(currentCache[target.row], currentCache[target.row - 1], {row: target.row - 1, col: target.col});
+                            }},
+                            "downMove": {name: "下移", disabled: downDis, icon: "fa-arrow-down", callback: function (key, opt) {
+                                raCoe.downMove(currentCache[target.row], currentCache[target.row + 1], {row: target.row + 1, col: target.col});
+                            }},
+                            "ref": {name: "添加到本节其他定额", disabled: refDis, icon: "fa-arrow-left", callback: function (key, opt) {
+                                raCoe.updateSectionRation(rationOprObj.currentRations["_SEC_ID_" + rationOprObj.currentSectionId], currentCache[target.row], function (updateArr) {
+                                    for(let i = 0, len = updateArr.length; i < len; i++){
+                                        let ration = updateArr[i];
+                                        let rationCoeList = updateArr[i].rationCoeList;
+                                        let newNo = 1;
+                                        for(let j = 0, jLen = rationCoeList.length; j < jLen; j++){
+                                            if(rationCoeList[j].no >= newNo){
+                                                newNo = rationCoeList[j].no + 1;
+                                            }
+                                        }
+                                        let theCache = raCoe.cache["_Coe_" + ration.ID];
+                                        if(theCache !== undefined && theCache !== null){
+                                            let newCoe = {};
+                                            for(let attr in currentCache[target.row]){
+                                                newCoe[attr] = currentCache[target.row][attr];
+                                            }
+                                            newCoe.no = newNo;
+                                            theCache.push(newCoe);
+                                        }
+                                    }
+                                });
+                            }}
+                        }
+                    };
+                }
                 else{
                     return false;
                 }
@@ -281,8 +339,7 @@ var rationGLJOprObj = {
             args.cancel = true;
         }
         else {
-            if(args.col !== 0 && args.col !== 5 || args.col === 5 && args.row >= me.cache["_GLJ_" + me.currentRationItem.ID].length
-            || me.currentRationItem.type === rationOprObj.type.std){
+            if(args.col !== 0 && args.col !== 5 || args.col === 5 && args.row >= me.cache["_GLJ_" + me.currentRationItem.ID].length){
                 args.cancel = true;
             }
         }

+ 4 - 19
web/building_saas/complementary_ration_lib/js/ration_installation.js

@@ -5,7 +5,6 @@ let rationInstObj = {
     IDMapping: null, //ID - name
     feeItem: null, //name - ID
     sheet: null,
-    rationRepId: null,
     curRation: null,
     cache: [],
     setting: {
@@ -22,8 +21,6 @@ let rationInstObj = {
         let me = this;
         me.sheet = sheet;
         me.sheet.options.clipBoardOptions = GC.Spread.Sheets.ClipboardPasteOptions.values;
-        me.rationRepId = parseInt(pageOprObj.rationLibId); // 不可靠,有时取不到
-        if (me.rationRepId == undefined){me.rationRepId = parseInt(getQueryString('repository'))};
         sheetCommonObj.initSheet(me.sheet, me.setting, 30);
         me.sheet.bind(GC.Spread.Sheets.Events.ClipboardPasting, me.onClipboardPasting);
         me.sheet.bind(GC.Spread.Sheets.Events.ClipboardPasted, me.onClipboardPasted);
@@ -31,7 +28,7 @@ let rationInstObj = {
         me.sheet.bind(GC.Spread.Sheets.Events.EditStarting, me.onEditStarting);
         me.sheet.bind(GC.Spread.Sheets.Events.EditEnded, me.onEditEnded);
         //右键
-      //  me.onContextmenuOpr();
+        //  me.onContextmenuOpr();
     },
     renderFunc: function (sheet, func) {
         sheet.suspendPaint();
@@ -45,9 +42,9 @@ let rationInstObj = {
     isDef: function (v) {
         return v !== undefined && v !== null;
     },
-    getInstallation: function (rationRepId, callback) {
+    getInstallation: function (callback) {
         let me = this;
-        CommonAjax.post('/complementaryRation/api/getInstallation', {rationRepId: rationRepId}, function (rstData) {
+        CommonAjax.post('api/getInstallation', {}, function (rstData) {
             //建立name - ID 映射, ID - name 映射
             me.feeItem = {};
             me.IDMapping = {feeItem: {}, section: {}};
@@ -86,7 +83,7 @@ let rationInstObj = {
     getInstItems: function (ration, callback) {
         let me = this, rst = [];
         me.curRation = ration;
-        me.cache = me.isDef(ration.rationInstList) ? ration.rationInstList : [];
+        me.cache = ration.rationInstList;
         for(let inst of me.cache){
             let data = Object.create(null);
             let feeItem = me.IDMapping['feeItem'][inst.feeItemId];
@@ -126,10 +123,6 @@ let rationInstObj = {
             args.cancel = true;
             return;
         }
-        if(me.curRation.type === rationOprObj.type.std){
-            args.cancel = true;
-            return;
-        }
         if(!me.isDef(me.cache[args.row]) && args.col === 1){
             args.cancel = true;
             return;
@@ -226,9 +219,6 @@ let rationInstObj = {
         let me = this;
         let workBook = me.sheet.getParent();
         workBook.commandManager().register('rationInstDel', function () {
-            if(me.isDef(me.curRation) && me.curRation.type === rationOprObj.type.std){
-                return;
-            }
             let toUpdate = false;
             let sels = me.sheet.getSelections();
             for(let i = 0, len = sels.length; i < len; i++){
@@ -262,11 +252,6 @@ let rationInstObj = {
         let me = rationInstObj;
         if(!me.isDef(me.curRation)){
             info.cancel = true;
-            return;
-        }
-        if(me.curRation.type === rationOprObj.type.std){
-            info.cancel = true;
-            return;
         }
     },
     onClipboardPasted: function (sender, info) {

+ 8 - 19
web/building_saas/complementary_ration_lib/js/repository_glj.js

@@ -6,27 +6,16 @@ var pageOprObj = {
     rationLibName : null,
     rationLibId: null,
     initPage : function(container) {
-        var me = this, rationLibId = getQueryString("repository");//获取定额库参数
-        me.rationLibId = rationLibId;
-        //getRationLibName
-        CommonAjax.post('/complementaryRation/api/getRationLibs', {ids: [rationLibId]}, function (rstData) {
-            if(rstData.length > 0){
-                me.rationLibName = rstData[0].dispName;
-                let $rationName = $(`<div id='rationname' class='navbar-text'>${me.rationLibName}</div>`);
-                $('.header-logo').after($rationName);
-                repositoryGljObj.buildSheet(container);
-                repositoryGljObj.getGljDistType(function () {
-                    repositoryGljObj.currentRepositoryId = parseInt(rationLibId);
-                    //引用的工料机库
-                    let gljLibID = rstData[0].gljLib;
-                    if(gljLibID && typeof gljLibID !== 'undefined'){
-                        repositoryGljObj.getGljTree(gljLibID, function () {
-                            repositoryGljObj.getGljItems(gljLibID);
-                        });
-                    }
-                    sheetCommonObj.shieldAllCells(repositoryGljObj.workBook.getSheet(0), repositoryGljObj.setting);
+        var me = this;//获取定额库参数
+        repositoryGljObj.buildSheet(container);
+        repositoryGljObj.getGljDistType(function () {
+            //引用的工料机库
+            if(gljLibId && typeof gljLibId !== 'undefined'){
+                repositoryGljObj.getGljTree(gljLibId, function () {
+                    repositoryGljObj.getGljItems(gljLibId);
                 });
             }
+            sheetCommonObj.shieldAllCells(repositoryGljObj.workBook.getSheet(0), repositoryGljObj.setting);
         });
 
     }

+ 238 - 92
web/building_saas/complementary_ration_lib/js/section_tree.js

@@ -4,18 +4,17 @@
 let pageOprObj = {
     rationLibName : null,
     rationLibId : null,
-    gljLibId: null,
+    gljLibId: gljLibId,
     initPage : function() {
-        let me = this, rationLibId = getQueryString("repository");
-        me.getRationLibInfo(rationLibId, function (rstData) {
-            if(rstData.length > 0){
-                me.rationLibName = rstData[0].dispName;
+        let me = this;
+       // me.getRationLibInfo(rationLibId, function (rstData) {
+            //if(rstData.length > 0){
+                //me.rationLibName = rstData[0].dispName;
                 //let $rationName = $(`<div id='rationname' class='navbar-text'><a id='rationLibBtn' href='javascript:void(0);'>定额库</a><i class='fa fa-angle-right fa-fw'></i>${me.rationLibName}</div>`);
-                let $rationName = $(`<div id='rationname' class='navbar-text'>${me.rationLibName}</div>`);
-                $('.header-logo').after($rationName);
-                me.gljLibId = rstData[0].gljLib;
-                me.rationLibId = rationLibId;
-                sectionTreeObj.getSectionTree(rationLibId);
+                //let $rationName = $(`<div id='rationname' class='navbar-text'>${me.rationLibName}</div>`);
+               // $('.header-logo').after($rationName);
+              //  me.gljLibId = rstData[0].gljLib;
+                sectionTreeObj.getSectionTree();
                 //job
                 jobContentOprObj.radiosChange(jobContentOprObj.radios, jobContentOprObj.tableAll, jobContentOprObj.tablePartial);
                 $('#addConBtn').click(jobContentOprObj.bindAddConBtn());
@@ -26,11 +25,11 @@ let pageOprObj = {
                 $('#fzAddConBtn').click(annotationOprObj.bindAddConBtn());
                 $('#fzUpdateConBtn').click(annotationOprObj.bindUpdateConBtn());
                 annotationOprObj.bindAllEvents($('#fzTxtareaAll'));
-            }
-            gljSelOprObj.getGljClassTree(pageOprObj.gljLibId, function () {
-                    gljSelOprObj.getSelGljItems(pageOprObj.gljLibId);
+           // }
+            gljSelOprObj.getGljClassTree(gljLibId, function () {
+                    gljSelOprObj.getSelGljItems(gljLibId);
             });
-        });
+       // });
     },
     getRationLibInfo: function (rationLibId, callback) {
         CommonAjax.post('api/getRationLib', {rationRepId: rationLibId}, callback);
@@ -73,6 +72,10 @@ let sectionTreeObj = {
     updateType: {new: 'new', update: 'update'},
     insertBtn: $('#tree_Insert'),
     removeBtn: $('#tree_remove'),
+    upLevelBtn: $('#tree_upLevel'),
+    downLevelBtn: $('#tree_downLevel'),
+    downMoveBtn: $('#tree_downMove'),
+    upMoveBtn: $('#tree_upMove'),
     type: {std: 'std', complementary: 'complementary'},
     setting: {
         sheet: {
@@ -175,15 +178,7 @@ let sectionTreeObj = {
     },
 
     onEditStarting: function (sender, args) {
-        let me = sectionTreeObj;
-        let node = me.cache[args.row];
-        if(!me.isDef(node)){
-            args.cancel = true;
-            return;
-        }
-        if(node.data.type === me.type.std){
-            args.cancel = true;
-        }
+
     },
 
     onEditEnded: function (sender, args) {
@@ -205,16 +200,7 @@ let sectionTreeObj = {
     },
 
     onClipboardPasting: function (sender, info) {
-        let me = sectionTreeObj;
-        let hasStd = false;
-        for(let row = info.cellRange.row, len = info.cellRange.row + info.cellRange.rowCount - 1; row < len; row ++){
-            if(me.isDef(me.cache[row]) && me.cache[row].data.type === me.type.std){
-                hasStd = true;
-            }
-        }
-        if(hasStd){
-            info.cancel = true;
-        }
+
     },
 
     onClipboardPasted: function (sender, info) {
@@ -250,10 +236,11 @@ let sectionTreeObj = {
         }
     },
 
-    getSectionTree: function (repId) {
+    getSectionTree: function () {
         let me = sectionTreeObj;
         let url = 'api/getRationTree';
-        let postData = {rationRepId: repId};
+        //type: 0-补充库 1-标准库
+        let postData = {type: 0};
         let sucFunc = function (rstData) {
             if(rstData.length > 0){
                 storageUtil.setSessionCache("RationGrp","repositoryID",rstData[0].rationRepId);
@@ -301,11 +288,28 @@ let sectionTreeObj = {
         let me = this;
         me.insertBtn.removeClass('disabled');
         me.removeBtn.removeClass('disabled');
+        me.upLevelBtn.removeClass('disabled');
+        me.downLevelBtn.removeClass('disabled');
+        me.downMoveBtn.removeClass('disabled');
+        me.upMoveBtn.removeClass('disabled');
         if(!me.isDef(selected)){
             me.removeBtn.addClass('disabled');
+            me.upLevelBtn.addClass('disabled');
+            me.downLevelBtn.addClass('disabled');
+            me.downMoveBtn.addClass('disabled');
+            me.upMoveBtn.addClass('disabled');
         }
-        else if(me.isDef(selected.data.type) && selected.data.type !== me.type.complementary){
-            me.removeBtn.addClass('disabled');
+        else {
+            if(!me.isDef(selected.preSibling)){
+                me.downLevelBtn.addClass('disabled');
+                me.upMoveBtn.addClass('disabled');
+            }
+            if(!me.isDef(selected.nextSibling)){
+                me.downMoveBtn.addClass('disabled');
+            }
+            if(!me.isDef(selected.parent)){
+                me.upLevelBtn.addClass('disabled');
+            }
         }
     },
     
@@ -314,64 +318,83 @@ let sectionTreeObj = {
         me.insertBtn.click(function () {
             me.insert();
         });
-        me.removeBtn.click(function () {
-           me.remove(me.tree.selected);
+        $('#delConfirm').click(function () {
+            if(me.canRemoveSection){
+                me.remove(me.tree.selected);
+            }
+            else {
+                $('#delAlert').modal('hide');
+            }
         });
-    },
-    
-    insert: function () {
-        let me = this;
-        me.insertBtn.addClass('disabled');
-        let postData = [];
-        CommonAjax.post('api/getNewTreeID', {user_id: userID}, function (newID) {
-            if(!me.isDef(newID)){
+        me.removeBtn.click(function () {
+            //不可删除有子节点或有定额数据的节点
+            let section = me.cache[me.workBook.getActiveSheet().getActiveRowIndex()];
+            if(!section){
                 return;
             }
-            me.tree.maxNodeID(newID - 1);
-            let selected = me.tree.selected;
-            let insertObj = me.getUpdateObj(me.updateType.new, {ID: newID, NextSiblingID: -1, ParentID: -1, name: ''});
-            if(me.isDef(selected)) {
-                insertObj.updateData.ParentID = selected.getParentID();
-                //同级节点
-                let slNodes = [];
-                slNodes = !me.isDef(selected.parent)? me.tree.roots : selected.parent.children;
-                let updateNode = slNodes[slNodes.length - 1];
-                if(me.isDef(updateNode)){
-                    me.controller.setTreeSelected(updateNode);
-                    if(updateNode.data.type === me.type.complementary){
-                        let updateObj = me.getUpdateObj(me.updateType.update, {ID: updateNode.getID(), NextSiblingID: newID});
-                        postData.push('updateObj');
-                        postData.push(updateObj);
-                    }
-                    else {
-                        insertObj.updateData.isFirst = true;
-                    }
-                }
+            let sectionName = me.isDef(section.data.name) ? section.data.name : '';
+            let sectionRations = rationOprObj.currentRations[`_SEC_ID_${section.data.ID}`];
+            if(section.children.length > 0 || (sectionRations && sectionRations.length > 0)){
+                me.canRemoveSection = false;
+                $('#delAlert').find('.modal-body h5').text('当前节点下有数据,不可删除。');
             }
-            postData.push(insertObj);
-            if(postData.length > 0){
-                //ajax
-                me.sectionTreeAjax(postData, function (rstData) {
-                    me.controller.insert();
-                    me.sheet.getCell(me.sheet.getActiveRowIndex(), 0).foreColor('gray');
-                    me.tree.selected.data = insertObj.updateData;
-                    me.tree.selected.data.type = me.type.complementary;
-                    me.refreshBtn(me.tree.selected);
-                    //fresh tools
-                    me.initTools(me.tree.selected);
-                    me.initSelection(me.tree.selected);
-                });
+            else {
+                me.canRemoveSection = true;
+                $('#delAlert').find('.modal-body h5').text(`确认要删除章节 “${sectionName}”吗?`);
             }
+            $('#delAlert').modal('show');
+        });
+        me.upLevelBtn.click(function () {
+            me.upLevel(me.tree.selected);
         });
+        me.downLevelBtn.click(function () {
+            me.downLevel(me.tree.selected);
+        });
+        me.downMoveBtn.click(function () {
+            me.downMove(me.tree.selected);
+        });
+        me.upMoveBtn.click(function () {
+            me.upMove(me.tree.selected);
+        });
+    },
+    insert: function () {
+        let me = sectionTreeObj;
+        me.insertBtn.addClass('disabled');
+        let postData = [],
+            newID = uuid.v1();
+        let selected = me.tree.selected;
+        let insertObj = me.getUpdateObj(me.updateType.new, {ID: newID, NextSiblingID: -1, ParentID: -1, name: ''});
+        if(me.isDef(selected)) {
+            let updateObj = me.getUpdateObj(me.updateType.update, {ID: selected.getID(), NextSiblingID: newID});
+            postData.push(updateObj);
+            insertObj.updateData.ParentID = selected.getParentID();
+            if(me.isDef(selected.nextSibling)){
+                insertObj.updateData.NextSiblingID = selected.getNextSiblingID();
+            }
+        }
+        postData.push(insertObj);
+        if(postData.length > 0){
+            //ajax
+            me.sectionTreeAjax(postData, function (rstData) {
+                me.controller.insert();
+                me.refreshBtn(me.tree.selected);
+                //fresh tools
+                me.initTools(me.tree.selected);
+                me.workBook.focus();
+                me.initSelection(me.tree.selected);
+            });
+        }
     },
     remove: function (selected) {
         let me = this;
         me.removeBtn.addClass('disabled');
-        let postData = [], IDs = [];
-        let deleteObj = Object.create(null);
-        deleteObj.deleted = true;
-        deleteObj.deleteDateTime = new Date();
-        deleteObj.deleteBy = userID;
+        let postData = [],
+            IDs = [],
+            deleteObj = {
+                deleted: true,
+                deleteDateTime: new Date(),
+                deleteBy: userID
+            };
         if(!selected){
             return;
         }
@@ -386,15 +409,10 @@ let sectionTreeObj = {
                 }
             }
         }
-        if(me.isDef(selected.preSibling) && selected.preSibling.data.type === me.type.complementary){
-            let updateObj = me.getUpdateObj(me.updateType.update, selected.preSibling.getID(), selected.getNextSiblingID(), null, null, null);
+        if(me.isDef(selected.preSibling)){
+            let updateObj = me.getUpdateObj(me.updateType.update, {ID: selected.preSibling.getID(), NextSiblingID: selected.getNextSiblingID()});
             postData.push(updateObj);
         }
-        else if((!me.isDef(selected.preSibling) || (me.isDef(selected.preSibling) && selected.preSibling.data.type === me.type.std))
-            && me.isDef(selected.nextSibling)){
-            let updateNextObj = me.getUpdateObj(me.updateType.update, {ID: selected.nextSibling.getID(), isFirst: true});
-            postData.push(updateNextObj);
-        }
         if(IDs.length > 0){
             for(let i = 0, len = IDs.length; i < len; i++){
                 let delObj = me.getUpdateObj(me.updateType.update, {ID: IDs[i], deleteInfo: deleteObj});
@@ -404,10 +422,137 @@ let sectionTreeObj = {
         if(postData.length > 0){
             //ajax
             me.sectionTreeAjax(postData, function (rstData) {
+                $('#delAlert').modal('hide');
+                me.removeRationsCodes(rationOprObj.currentRations["_SEC_ID_" + selected.data.ID]);
                 me.controller.delete();
                 me.refreshBtn(me.tree.selected);
                 me.initTools(me.tree.selected);
                 me.initSelection(me.tree.selected);
+                me.workBook.focus();
+            });
+        }
+    },
+    removeRationsCodes: function (rations) {
+        for(let ration of rations){
+            rationOprObj.rationsCodes.splice(rationOprObj.rationsCodes.indexOf(ration.code), 1);
+        }
+    },
+    upLevel: function (selected) {
+        let me = this;
+        me.upLevelBtn.addClass('disabled');
+        let postData = [],
+            parent = selected.parent;
+        if(!me.isDef(parent)){
+            return;
+        }
+        //更新父节点
+        postData.push(me.getUpdateObj(me.updateType.update, {ID: parent.getID(), NextSiblingID: selected.getID()}));
+        //更新前节点
+        if(me.isDef(selected.preSibling)){
+            postData.push(me.getUpdateObj(me.updateType.update, {ID: selected.preSibling.getID(), NextSiblingID: -1}));
+        }
+        //更新选中节点的后兄弟节点
+        let nextIDs = [];
+        getNext(selected);
+        function getNext(node){
+            if(me.isDef(node.nextSibling)){
+                nextIDs.push(node.getNextSiblingID());
+                getNext(node.nextSibling);
+            }
+        }
+        for(let nextID of nextIDs){
+            postData.push(me.getUpdateObj(me.updateType.update, {ID: nextID, ParentID: selected.getID()}));
+        }
+        //更新选中节点
+        postData.push(me.getUpdateObj(me.updateType.update,
+            {ID: selected.getID(), NextSiblingID: parent.getNextSiblingID(), ParentID: parent.getParentID()}));
+
+        if(postData.length > 0){
+            //ajax
+            me.sectionTreeAjax(postData, function (rstData) {
+                me.controller.upLevel();
+                me.refreshBtn(me.tree.selected);
+                me.workBook.focus();
+            });
+        }
+    },
+    downLevel: function (selected) {
+        let me = this;
+        me.downLevelBtn.addClass('disabled');
+        let postData = [],
+            preSibling = selected.preSibling;
+        if(!me.isDef(preSibling)){
+            return;
+        }
+        //更新前节点
+        postData.push(me.getUpdateObj(me.updateType.update, {ID: preSibling.getID(), NextSiblingID: selected.getNextSiblingID()}));
+        //更新前节点最末子节点
+        if(preSibling.children.length > 0){
+            postData.push(me.getUpdateObj(me.updateType.update,
+                {ID: preSibling.children[preSibling.children.length - 1].getID(), NextSiblingID: selected.getID()}));
+        }
+        //更新选中节点
+        postData.push(me.getUpdateObj(me.updateType.update, {ID: selected.getID(), NextSiblingID: -1, ParentID: preSibling.getID()}));
+        if(postData.length > 0){
+            //ajax
+            me.sectionTreeAjax(postData, function (rstData) {
+                me.controller.downLevel();
+                me.refreshBtn(me.tree.selected);
+                me.workBook.focus();
+            });
+        }
+    },
+    upMove: function (selected) {
+        let me = this;
+        me.upMoveBtn.addClass('disabled');
+        let postData = [];
+        if(!me.isDef(selected)){
+            return;
+        }
+        if(!me.isDef(selected.preSibling)){
+            return;
+        }
+        let updateObj = me.getUpdateObj(me.updateType.update, {ID: selected.getID(), NextSiblingID: selected.preSibling.getID()});
+        postData.push(updateObj);
+        let updatePre = me.getUpdateObj(me.updateType.update, {ID: selected.preSibling.getID(), NextSiblingID: selected.getNextSiblingID()});
+        postData.push(updatePre);
+        if(me.isDef(selected.preSibling.preSibling)){
+            let updatePrepre = me.getUpdateObj(me.updateType.update, {ID: selected.preSibling.preSibling.getID(), NextSiblingID: selected.getID()});
+            postData.push(updatePrepre);
+        }
+        if(postData.length > 0){
+            //ajax
+            me.sectionTreeAjax(postData, function (rstData) {
+                me.controller.upMove();
+                me.refreshBtn(me.tree.selected);
+                me.workBook.focus();
+            });
+        }
+    },
+    downMove: function (selected) {
+        let me = this;
+        me.downMoveBtn.addClass('disabled');
+        let postData = [];
+        if(!me.isDef(selected)){
+            return;
+        }
+        if(!me.isDef(selected.nextSibling)){
+            return;
+        }
+        if(me.isDef(selected.preSibling)){
+            let updatePre = me.getUpdateObj(me.updateType.update, {ID: selected.preSibling.getID(), NextSiblingID: selected.getNextSiblingID()});
+            postData.push(updatePre);
+        }
+        let updateObj = me.getUpdateObj(me.updateType.update, {ID: selected.getID(), NextSiblingID: selected.nextSibling.getNextSiblingID()});
+        postData.push(updateObj);
+        let updateNext = me.getUpdateObj(me.updateType.update, {ID: selected.getNextSiblingID(), NextSiblingID: selected.getID()});
+        postData.push(updateNext);
+        if(postData.length > 0){
+            //ajax
+            me.sectionTreeAjax(postData, function (rstData) {
+                me.controller.downMove();
+                me.refreshBtn(me.tree.selected);
+                me.workBook.focus();
             });
         }
     },
@@ -445,6 +590,7 @@ let sectionTreeObj = {
     },
     //模仿默认点击
     initSelection: function (node) {
+        node.tree.selected = node ? node : null;
         let me = this;
         if(!me.isDef(node)){
             sheetCommonObj.cleanSheet(rationOprObj.workBook.getActiveSheet(), rationOprObj.setting, -1);

+ 1 - 0
web/building_saas/main/js/controllers/project_controller.js

@@ -179,6 +179,7 @@ ProjectController = {
     },
 
     addRation: function (project, sheetController, rationType, std) {
+        debugger;
         if (!project || !sheetController) { return; }
 
         let selected = project.mainTree.selected, newSource = null, newNode = null;

+ 2 - 0
web/building_saas/main/js/models/ration_coe.js

@@ -97,6 +97,8 @@ var ration_coe = {
                 criteria.ration_coe_list.push(newCoe);
             }
             criteria.updateType = 'ut_create';
+            console.log('enterrrrrrrrrrrrrrrrrrrrrr');
+            console.log(criteria);
             return criteria;
         };
         ration_coe.prototype.getCustomerCoeData = function () {

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

@@ -604,25 +604,29 @@ var projectObj = {
             }
         }
         if(node.sourceType == ModuleNames.ration){ //在定额编码中双击,如果右侧定额库没有展开,则自动展开。
+            let libID = node.data.libID;
+            if (node.data.from === 'cpt') {
+                libID = rationLibObj.compleRationLibId;
+            }
             if(!rationLibObj.tree){
-                sessionStorage.setItem('stdRationLib', node.data.libID);
+                sessionStorage.setItem('stdRationLib', libID);
                 rationLibObj.doAfterGetRationTree = function () {
-                    this.locateAtRation(node.data.libID, code);
+                    this.locateAtRation(libID, code);
                     this.doAfterGetRationTree = null;
                 };
             }
             else {
-                if($('#stdRationLibSelect').select().val() != node.data.libID){
+                if($('#stdRationLibSelect').select().val() != libID){
                     let libOpts = $('#stdRationLibSelect').find('option');
                     for(let libOpt of libOpts){
-                        if($(libOpt).val() == node.data.libID){
+                        if($(libOpt).val() == libID){
                             $(libOpt).prop('selected', 'selected');
                             break;
                         }
                     }
                     $('#stdRationLibSelect').change();
                     rationLibObj.doAfterGetRationTree = function () {
-                        this.locateAtRation(node.data.libID, code);
+                        this.locateAtRation(libID, code);
                         this.doAfterGetRationTree = null;
                     };
                 }
@@ -2669,7 +2673,7 @@ function doAfterImportPosition(positionData){
     let ration_datas = projectObj.project.Ration.datas;
     let quantity_detail_datas = projectObj.project.quantity_detail.datas;
     let ration_glj_datas = projectObj.project.ration_glj.datas;
-    let ration_coe_datas = projectObj.project.ration_coe.datas;
+    let ration_coe_daRtas = projectObj.project.ration_coe.datas;
     let ration_install_datas = projectObj.project.ration_installation.datas;
     let delNodes = [];
     for(let billID of positionData.remove.bill){

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

@@ -5,6 +5,8 @@
 /*var rationChapterSpread, sectionRationsSpread;*/
 
 var rationLibObj = {
+    libType: {complementary: 0, std: 1},
+    compleRationLibId: 'compleRationLib',
     doAfterGetRationTree: null, //获取章节树回调
     doAfterLoadGetRations: null, //获取章节树下定额后回调
     rationChapterSpread: null,
@@ -58,6 +60,9 @@ var rationLibObj = {
             }
             select.append(option);
         });
+        //我的补充定额库
+        let $opt = $('<option>').val(rationLibObj.compleRationLibId).text('我的补充定额');
+        select.append($opt);
         if (select[0].options.length !== 0) {
             rationLibObj.loadStdRation(select.val());
         }
@@ -79,6 +84,7 @@ var rationLibObj = {
     },
     loadStdRation: function (rationLibID) {
         $.bootstrapLoading.start();
+        rationLibObj.curLibType = rationLibID === rationLibObj.compleRationLibId ? rationLibObj.libType.complementary : rationLibObj.libType.std;
         var that = this;
         var showRationChapterTree = function (datas) {
             var rationChapterTree = idTree.createNew({id: 'ID', pid: 'ParentID', nid: 'NextSiblingID', rootId: -1, autoUpdate: false});
@@ -110,8 +116,8 @@ var rationLibObj = {
                 rationLibObj.loadSectionRations();
             };
         };
-
-        CommonAjax.post('/complementaryRation/api/getRationTree', {userId: userID, rationRepId: rationLibID}, function (datas) {
+        //type: 0-补充库 1-标准库
+        CommonAjax.post('/complementaryRation/api/getRationTree', {userId: userID, rationRepId: rationLibID, type: rationLibObj.curLibType}, function (datas) {
             showRationChapterTree(datas);
             if(that.doAfterGetRationTree){
                 that.doAfterGetRationTree();
@@ -164,7 +170,7 @@ var rationLibObj = {
             rationLibObj.setTagForHint(rationSheet, datas);
         };
         if (sectionID) {
-            CommonAjax.post('/complementaryRation/api/getRationGljItemsBySection', {user_Id: userID, sectionId: sectionID}, function (datas) {
+            CommonAjax.post('/complementaryRation/api/getRationGljItemsBySection', {user_Id: userID, sectionId: sectionID, type: me.curLibType}, function (datas) {
                 showDatas(datas, rationLibObj.sectionRationsSetting);
                 if(me.doAfterLoadGetRations){
                     me.doAfterLoadGetRations(datas);
@@ -180,7 +186,12 @@ var rationLibObj = {
     onRationSpreadCellDoubleClick: function (sender, args) {
         var select = $('#stdRationLibSelect'), rationCode = args.sheet.getText(args.row, 0);
         if (rationCode !== '') {
-            projectObj.project.Ration.addNewRation({userID: userID, rationRepId: select.val(), code: rationCode},rationType.ration, function () {
+            let query = {userID: userID, 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 () {
                 projectObj.setActiveCell('quantity', true);
             });
         }
@@ -460,6 +471,7 @@ $('#rationSearchKeyword').keyup(function () {
     let keyword = $('#rationSearchKeyword').val();
     if(keyword === ''){
         if($('#rationSearchResult').is(':visible')){
+            rationLibObj.resultCache = null;
             $('#rationSearchResult').hide();
             $(".main-data-side-search", $('#rationSearchResult')).height(0);
             switchRationSearchMode(0);
@@ -508,6 +520,7 @@ $('#rationSearch').click(function () {
     var keyword = $('#rationSearchKeyword').val();
     if(keyword === ''){
         if($('#rationSearchResult').is(':visible')){
+            rationLibObj.resultCache = null;
             $('#rationSearchResult').hide();
             $(".main-data-side-search", $('#rationSearchResult')).height(0);
             autoFlashHeight();
@@ -523,6 +536,7 @@ $('#rationSearch').click(function () {
         for(let lib of projectInfoObj.projectInfo.engineeringInfo.ration_lib){
             rationLibIDs.push(lib.id);
         }
+        rationLibIDs.push(rationLibObj.compleRationLibId);
     }
     let bindContextmenuOpr = function (sheet) {
         $.contextMenu({
@@ -604,6 +618,7 @@ $('#rationSearch').click(function () {
         $('#rationSearchCount').text(`搜索结果:${result.length.toString()}`);
         $('a', result).unbind('click');
         $('a', resultObj).bind('click', function () {
+            rationLibObj.resultCache = null;
             switchRationSearchMode(0);
             resultObj.hide();
             $(".main-data-side-search", resultObj).height(0);

+ 2 - 1
web/common/html/header.html

@@ -41,7 +41,8 @@
             <li class="nav-item dropdown">
                 <a class="nav-link dropdown-toggle" href="#" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"><i class="fa fa-wrench" data-placement="bottom"></i> 工具</a>
                 <div class="dropdown-menu dropdown-menu-right">
-                    <a id="compleRationLib" class="dropdown-item" href="javascript:void(0);" data-toggle="modal" data-target="#comple-ration">定额库编辑器</a>
+                    <!--<a id="compleRationLib" class="dropdown-item" href="javascript:void(0);" data-toggle="modal" data-target="#comple-ration">定额库编辑器</a> -->
+                    <a id="compleRationLib" class="dropdown-item" href="/complementaryRation/ration" target="_blank">定额库编辑器</a>
                     <a id="compleGljLib" class="dropdown-item" href="/complementaryGlj" target="_">人材机库编辑器</a>
                 </div>
             </li>