zhangweicheng 6 лет назад
Родитель
Сommit
68428c7b07

Разница между файлами не показана из-за своего большого размера
+ 2 - 0
lib/qiniu/qiniu.min.js


+ 1 - 0
modules/all_models/com_electrovalence.js

@@ -10,6 +10,7 @@ let gljListSchema =new Schema({
     GLJID:Number,
     projectGLJID:Number,
     name:String,
+    displayName:String,
     code:String,
     specs:String,
     unit:String,

+ 20 - 0
modules/all_models/import_logs.js

@@ -0,0 +1,20 @@
+/**
+ * Created by zhang on 2019/12/27.
+ */
+import mongoose from "mongoose";
+
+let Schema = mongoose.Schema;
+let collectionName = 'import_logs';
+
+let modelSchema = {
+    // 日志类型
+    key: {type: String, index: true},
+    // 日志内容
+    userID: String,
+    // 关联用户id
+    status:String,
+    // 创建时间
+    create_time: Number,
+    errorMsg:""
+};
+mongoose.model(collectionName, new Schema(modelSchema, {versionKey: false, collection: collectionName}));

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

@@ -903,7 +903,7 @@ async function getGLJListByProjectID(projectId){
         //if(!responseData.data.com_electrovalence) responseData.data.com_electrovalence = {};
         // 先获取对应标段的项目工料机数据
         let gljListModel = new GLJListModel();
-        let [gljList, mixRatioConnectData,mixRatioMap,unitPriceMap] = await gljListModel.getListByProjectId(projectId, unitPriceFileId,responseData.data.freightList,responseData.data.originalList);
+        let [gljList, mixRatioConnectData,mixRatioMap,unitPriceMap] = await gljListModel.getListByProjectId(projectId, unitPriceFileId,responseData.data.freightList,responseData.data.originalList,responseData.data.com_electrovalence);
         responseData.data.gljList = gljList;
         responseData.data.mixRatioConnectData = mixRatioConnectData;
         responseData.data.mixRatioMap = mixRatioMap;

+ 9 - 5
modules/glj/models/glj_list_model.js

@@ -79,13 +79,14 @@ class GLJListModel extends BaseModel {
      * @param {Number} unitPriceFileId
      * @return {Promise}
      */
-    async getListByProjectId(projectId, unitPriceFileId,freightList,originalList) {
+    async getListByProjectId(projectId, unitPriceFileId,freightList,originalList,com_electrovalence) {
         let gljData = null;
         /*let decimal =await decimal_facade.getProjectDecimal(projectId);
         let quantity_decimal = decimal&&decimal.glj.quantity?decimal.glj.quantity:6;//取消耗量保留小数据位,默认6位*/
         let mixRatioConnectData = {};
         let mixRationMap={};
         let keyMap={};
+        let ekeyMap={};
         let unitPriceList={};
         try {
             // 首先获取对应标段下所有的项目工料机数据
@@ -100,12 +101,14 @@ class GLJListModel extends BaseModel {
                 if(this.ownCompositionTypes.indexOf(tmp.type)!=-1){
                     connect_keys.push(c_key);
                 }
-                keyMap[c_key] = tmp; //工料机连接key和工料机的对照表;
+                keyMap[c_key] = tmp; //项目工料机连接key和工料机的对照表;
             }
 
             //检查自采材料和综合电价功能在共享单价文件时,项目文件中可能会缺少项目工料机的情况,如果缺少,则自动插入
             if(freightList && freightList.length > 0)  await this.materialCalcProjectGLJChecking(freightList,keyMap,gljData,connect_keys,projectId,unitPriceFileId);
             if(originalList && originalList.length > 0) await this.materialCalcProjectGLJChecking(originalList,keyMap,gljData,connect_keys,projectId,unitPriceFileId);
+            if(com_electrovalence) await this.materialCalcProjectGLJChecking([com_electrovalence],keyMap,gljData,connect_keys,projectId,unitPriceFileId,"gljList");
+
             // 没有数据则直接返回空
             if (gljData.length <= 0) {
                 throw '无数据';
@@ -161,11 +164,12 @@ class GLJListModel extends BaseModel {
         return [gljData, mixRatioConnectData,mixRationMap,unitPriceList];
     }
 
-    async materialCalcProjectGLJChecking(materialList,keyMap,gljData,connect_keys,projectId,unitPriceFileId){
+    async materialCalcProjectGLJChecking(materialList,keyMap,gljData,connect_keys,projectId,unitPriceFileId,listKey){
         let missGLJs = [];
+        let pkey = listKey?listKey:"ration_gljs";
         for(let m of materialList){
-            if(m.ration_gljs){
-                for(let rg of m.ration_gljs){
+            if(m[pkey]){
+                for(let rg of m[pkey]){
                     let key = this.getIndex(rg);
                     if(keyMap[key])  continue; //如果已经存在,则跳过,不用添加
                     missGLJs.push(rg)

+ 2 - 4
modules/import/controllers/import_controller.js

@@ -8,10 +8,8 @@ let logger = require("../../../logs/log_helper").logger;
 let pm_facade = require('../../pm/facade/pm_facade');
 let controller = {
     importProject:async function (req){
-        let data = req.body.data;
-        let sessionInfo = {session:req.body.session};
-        let fields = req.body.fields;
-        return await pm_facade.importProject(data,sessionInfo,fields);
+        let data = req.body;
+        return await pm_facade.downLoadProjectFile(data);
     },
     exportProject:async function(req){
         let result={

+ 40 - 22
modules/pm/controllers/pm_controller.js

@@ -716,30 +716,48 @@ module.exports = {
             result.message = err.message;
         }
         res.json(result);
-
     },
     importProject:async function(req,res){
-        let form = new multiparty.Form({uploadDir: './tmp'});
-        form.parse(req, async function (err, fields, files) {
-            let path = "";
-            try {
-                console.log(fields);
-                const file = typeof files.file !== 'undefined' ? files.file[0] : null;
-                if (err || !file) {
-                    throw '上传失败。';
-                };
-                path = file.path;
-                let data = fs.readFileSync(file.path,'utf-8');
-                let body = {data: data, fields:fields, session:req.session};
-                let result = await redirectToImportServer(body,"importProject",req);
-                res.json(result);
-            }catch (e){
-                console.log(e);
-                res.json({error:1,msg:"导入失败请检查文件!"})
-            }finally {
-                fs.unlinkSync(path);
-            }
-        })
+        let data = JSON.parse(req.body.data);
+        let result={
+            error:0
+        };
+        try {
+            data.session = req.session;
+            result = await redirectToImportServer(data,"importProject",req);
+        }catch (err){
+            console.log(err);
+            result.error=1;
+            result.message = err.message;
+        }
+        res.json(result);
+    },
+    importProcessChecking:async function (req,res) {
+        let result={
+            error:0
+        };
+        try{
+            let data = JSON.parse(req.body.data);
+            result.data = await pm_facade.importProcessChecking(data);
+        } catch (err){
+            console.log(err);
+            result.error=1;
+            result.message = err.message;
+        }
+        res.json(result);
+    },
+    getUploadToken:function (req,res) {
+        let result={
+            error:0
+        };
+        try {
+            result =pm_facade.uploadToken();
+        }catch (err){
+            console.log(err);
+            result.error=1;
+            result.message = err.message;
+        }
+        res.json(result);
     }
 };
 

+ 109 - 5
modules/pm/facade/pm_facade.js

@@ -29,7 +29,10 @@ module.exports={
     checkFiles:checkFiles,
     copyForSectionError: copyForSectionError,
     exportProject:exportProject,
-    importProject:importProject
+    importProject:importProject,
+    uploadToken:uploadToken,
+    downLoadProjectFile:downLoadProjectFile,
+    importProcessChecking:importProcessChecking
 };
 
 
@@ -54,6 +57,7 @@ let unitPriceFileModel = mongoose.model("unit_price_file");
 let mixRatioModel = mongoose.model("mix_ratio");
 let freightModel = mongoose.model("freight_calc");
 let originalModel = mongoose.model("original_calc");
+let comElectrovalenceModel = mongoose.model("com_electrovalence");
 let unitPriceModel = mongoose.model("unit_price");
 let installationFeeModel = mongoose.model("installation_fee");
 let rationGLJModel = mongoose.model('ration_glj');
@@ -65,6 +69,8 @@ let userModel = mongoose.model('user');
 let compleGljSectionModel = mongoose.model('complementary_glj_section');
 let compleGljSectionTModel = mongoose.model('complementary_glj_section_templates');
 let progressiveModel = mongoose.model('std_progressive_lib');
+let importLogsModel = mongoose.model("import_logs");
+
 
 let featureLibModel =  mongoose.model("std_project_feature_lib");
 let scMathUtil = require('../../../public/scMathUtil').getUtil();
@@ -77,6 +83,20 @@ import billsFlags from '../../common/const/bills_fixed';
 const notDeleted = [{deleteInfo: null}, {'deleteInfo.deleted': false}];
 let cipher = require('../../../public/cipher');
 const compilationModel = mongoose.model('compilation');
+let qiniu = require("qiniu");
+let fs = require("fs");
+let path = require("path");
+let request = require("request");
+
+let qiniu_config = {
+    "AccessKey": "_gR1ed4vi1vT2G2YITGSf4_H0fJu_nRS9Tzk3T4z",
+    "SecretKey": "ty4zd0FHqgEDaiVzSLC8DfHlai99aS7bspLkw6s6",
+    "Bucket": "yun-update",
+    "Domain": "http://serverupdate.smartcost.com.cn"
+};
+let mac = new qiniu.auth.digest.Mac(qiniu_config.AccessKey, qiniu_config.SecretKey);
+
+
 
 
 //拷贝例题项目
@@ -383,6 +403,7 @@ async function copyUnitPriceFile(newProjectID,rootProjectID,userID,originaluUnit
         copySubList(originaluUnitPriceFileID,unitPriceFileID,mixRatioModel),
         copySubList(originaluUnitPriceFileID,unitPriceFileID,freightModel,true),
         copySubList(originaluUnitPriceFileID,unitPriceFileID,originalModel,true),
+        copySubList(originaluUnitPriceFileID,unitPriceFileID,comElectrovalenceModel,true),
         copySubList(originaluUnitPriceFileID,unitPriceFileID,unitPriceModel)
     ];
 
@@ -1074,6 +1095,7 @@ async function exportUnitFiles(rootProjectID){
          tem.mixRatios = await mixRatioModel.find({unit_price_file_id:f.id});
          tem.freights = await freightModel.find({unit_price_file_id:f.id});
          tem.originals = await originalModel.find({unit_price_file_id:f.id});
+         tem.com_electrovalence = await comElectrovalenceModel.find({unit_price_file_id:f.id});
          unitFiles.push(tem);
     }
     return unitFiles;
@@ -1112,8 +1134,72 @@ async function exportTenderData(data){
     return cipher.aesEncrypt(JSON.stringify(result));
 }
 
+async function downLoadProjectFile(info) {
+    let result = {error:0};
+    let bucketManager2 = new qiniu.rs.BucketManager(mac, null);
+    let publicBucketDomain = qiniu_config.Domain;// "http://serverupdate.smartcost.com.cn";//这里不支持https
+    let deadline = parseInt(Date.now() / 1000) + 3600; // 1小时过期
+    let privateDownloadUrl = bucketManager2.privateDownloadUrl(publicBucketDomain, info.key, deadline);
+
+    let data = {
+        key:info.key,
+        userID:info.session.sessionUser.id,
+        status:"start",
+        create_time:+new Date()
+    };
+    await importLogsModel.create(data);
+    doDownLoadAndImport(privateDownloadUrl,info);
+    return result;
+}
+
+
+async function doDownLoadAndImport(privateDownloadUrl,info) {
+    let stream = fs.createWriteStream(path.join(__dirname, "../../../tmp/"+info.key));//
+    request(privateDownloadUrl).pipe(stream).on("close", async function (err) {
+        console.log("文件[" + info.key + "]下载完毕");
+        let doc = {status:"finish"};
+        try {
+            let data = fs.readFileSync(stream.path,'utf-8');
+            let result = await importProject(data,{session:info.session},info.updateData);
+            if(result.error == 1){
+                doc.errorMsg = result.msg;
+                doc.status = "error";
+            }
+        }catch (error){
+            console.log(error);
+            doc.errorMsg = "导入失败,请检查文件!";
+            doc.status = "error";
+        }finally {
+            await importLogsModel.update({key:info.key},doc);
+            fs.unlinkSync(stream.path);
+        }
+    });
+}
+
+async function importProcessChecking(data){
+    let result = {error:0};
+    let log = await importLogsModel.findOne({key:data.key});
+    if(log){
+        if(log.status == "finish"){
+            result.status = "complete";
+            await importLogsModel.remove({key:data.key});
+        }else if(log.status == "start"){
+            result.status = "processing";
+        }else if(log.status == "error"){
+            result.error = 1;
+            result.msg = log.errorMsg;
+            await importLogsModel.remove({key:data.key});
+        }
+    }else {
+        result.error = 1;
+        result.msg = `导入过程中发生错误!`;
+    }
+    return result;
 
-async function importProject(data,req,fields) {
+}
+
+
+async function importProject(data,req,updateData) {
     let result = {error:0};
     let stringArr = data.split("|----|");
     let datas = [];
@@ -1132,7 +1218,7 @@ async function importProject(data,req,fields) {
              result.error = 1;
              result.msg = `导入失败:您要导入的文件是由“${fileCompilationName}”导出,当前软件是“${curCompilationName}”,请选择正确的编制办法再进行操作!`;
          }else {
-            let [projectIDMap,labourCoeFileIDMap,calcProgramFileIDMap] = await handleMainProjectDatas(mainData,JSON.parse(fields.updateData[0]),req.session.sessionUser.id);
+            let [projectIDMap,labourCoeFileIDMap,calcProgramFileIDMap] = await handleMainProjectDatas(mainData,updateData,req.session.sessionUser.id);
             if(datas.length > 1 ){
                 for(let i = 1;i<datas.length;i++){
                     await handleEachProject(datas[i],projectIDMap,labourCoeFileIDMap,calcProgramFileIDMap)
@@ -1306,9 +1392,9 @@ async function handleMainProjectDatas(mainData,updateData,userID) {
 
 async function importUnitPriceFiles(mainData,projectIDMap,unitPriceFileIDMap,userID) {
     if(!mainData.files.unitFiles) return;
-    let unitFiles = [],unitPrices =[],mixRatios=[],freights=[],originals=[];
+    let unitFiles = [],unitPrices =[],mixRatios=[],freights=[],originals=[],com_electrovalences=[];
     for(let f of mainData.files.unitFiles){
-        let file = f.unitFile,prices = f.unitPrices,mixs = f.mixRatios,fres = f.freights,ors = f.originals;
+        let file = f.unitFile,prices = f.unitPrices,mixs = f.mixRatios,fres = f.freights,ors = f.originals,ec=f.com_electrovalence;
         //生成单价文件
         delete file._id;
         file.id = unitPriceFileIDMap[file.id]?unitPriceFileIDMap[file.id]:await getCounterID("unit_price_file");
@@ -1322,12 +1408,14 @@ async function importUnitPriceFiles(mainData,projectIDMap,unitPriceFileIDMap,use
         if(mixs) await setSubList(mixs,mixRatios,file.id,mixRatioModel);
         if(fres) await setSubList(fres,freights,file.id,freightModel,true);
         if(ors) await setSubList(ors,originals,file.id,originalModel,true);
+        if(ec) await setSubList(ec,com_electrovalences,file.id,comElectrovalenceModel,true);
     }
     if(unitFiles.length > 0) await insertMany(unitFiles,unitPriceFileModel);
     if(unitPrices.length > 0) await insertMany(unitPrices,unitPriceModel);
     if(mixRatios.length > 0) await insertMany(mixRatios,mixRatioModel);
     if(freights.length > 0) await insertMany(freights,freightModel);
     if(originals.length > 0) await insertMany(originals,originalModel);
+    if(com_electrovalences.length > 0) await insertMany(com_electrovalences,comElectrovalenceModel);
 
     async function setSubList(oList,nList,fileID,model,UUID=false) {
         for(let o of oList){
@@ -1429,3 +1517,19 @@ async function checkFiles(projects) {
     }
     await Promise.all(task);
 }
+
+function uploadToken() {
+    let options = {
+        scope: qiniu_config.Bucket,
+        deleteAfterDays: 1,
+        returnBody:
+            '{"key":"$(key)","hash":"$(etag)","fsize":$(fsize),"bucket":"$(bucket)","name":"$(x:name)"}'
+    };
+    let putPolicy = new qiniu.rs.PutPolicy(options);
+    let token = putPolicy.uploadToken(mac);
+    let result = {
+            uptoken: token,
+            domain: qiniu_config.Domain
+        }
+    return result
+}

+ 3 - 1
modules/pm/routes/pm_route.js

@@ -12,7 +12,7 @@ module.exports = function (app) {
     app.get('/pm', baseController.init, pmController.index);
 
     let pmRouter = express.Router();
-
+    pmRouter.get('/getUploadToken', pmController.getUploadToken);
     pmRouter.use(function (req, res, next) {
         if (/\/getNewProjectID/.test(req.originalUrl)||/\/importProject/.test(req.originalUrl) || pmController.checkRight(req, res)) {
             next();
@@ -63,6 +63,8 @@ module.exports = function (app) {
     pmRouter.post('/changeFile', pmController.changeFile);
     pmRouter.post('/exportProject', pmController.exportProject);
     pmRouter.post('/importProject', pmController.importProject);
+    pmRouter.post('/importProcessChecking', pmController.importProcessChecking);
+
 
     app.use('/pm/api', pmRouter);
 };

+ 2 - 1
package.json

@@ -56,7 +56,8 @@
     "socket.io": "2.0.3",
     "ua-parser-js": "^0.7.14",
     "uuid": "^3.1.0",
-    "wiredep": "^2.2.2"
+    "wiredep": "^2.2.2",
+    "qiniu": "^7.1.1"
   },
   "scripts": {
     "start": "C:\\Users\\mai\\AppData\\Roaming\\npm\\babel-node.cmd server.js",

+ 6 - 7
public/web/gljUtil.js

@@ -9,7 +9,6 @@ let gljUtil = {
         let rations = rationDatas;
         let rationMap = _.indexBy(rations,'ID');
         let quantityMap={};
-        let quanitytIDMap={};//以项目工料机的ID为Map;(给综合电价计算使用)
         let rationGljGroup = _.groupBy(rationGLJDatas,'projectGLJID');
         let IDarray =  this.getSubdivisionAndTechBillsLeavesID(billsDatas);//分别取分部分项和技术措施项目的所有叶子清单ID
         let billIDs = IDarray[0],tech_billIDS = IDarray[1];
@@ -31,7 +30,6 @@ let gljUtil = {
             pglj[qField] = result.quantity;
             quantityMap[pg_index] = pglj;
             if(pglj.code == gljUtil.getElecCode() && pglj.name == '电' && pglj.unit == "kW·h") elecIndex = pg_index;
-            if(com_electrovalence) quanitytIDMap[pglj.id] = pglj;
         }
         //计算做为组成物的消耗量
         for(let pkey in mixRatioMap){
@@ -72,17 +70,17 @@ let gljUtil = {
                 //网电的消耗量=电的总消耗量×加权系数
                 let eq = scMathUtil.roundForObj(quantityMap[elecIndex][qField] * parseFloat(cg.coe),q_decimal);
                 if(cg.name == '电网电'){
-                    quanitytIDMap[cg.projectGLJID][qField] = eq;
+                    quantityMap[this.getIndex(cg)][qField] = eq;
                 }else {
                     let tquantity = 0;
                     let w = parseInt(cg.name);
                     if(w) tquantity = scMathUtil.roundForObj(eq/w,6);
                     tquantity = scMathUtil.roundForObj(tquantity * this.getElecCoe(),q_decimal);
-                    quanitytIDMap[cg.projectGLJID][qField] = tquantity;
+                    let ekey = this.getIndex(cg);
+                    quantityMap[ekey][qField] = tquantity;
                     //计算机械台班下的组成物的消耗量
-                    let ckey = this.getIndex(quanitytIDMap[cg.projectGLJID]);
-                    if(mixRatioMap[ckey]){
-                        for(let m of mixRatioMap[ckey]){
+                    if(mixRatioMap[ekey]){
+                        for(let m of mixRatioMap[ekey]){
                             let cmkey = this.getIndex(m);
                             if(quantityMap[cmkey] && tquantity > 0){//混凝土、砂浆、配合比组成物的消耗量在定额下已经有体现了,不用再计算进去
                                 let c_m_quantity = scMathUtil.roundForObj(tquantity * parseFloat(m.consumption),6);
@@ -377,6 +375,7 @@ let gljUtil = {
         t_index = k_arr.join("|-|");
         return t_index;
     },
+
     getMainType:function (type) {
         let str = type + "";
         return parseInt(str.substr(0,1));

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

@@ -1688,7 +1688,7 @@ ProjectGLJ.prototype.loadNewProjectGLJToCache = function (data) {//把新插入
     let mixRatioMap = this.datas.mixRatioMap;
     let mixRatioConnectData = this.datas.mixRatioConnectData;
     let tem =  _.find(project_gljs,{'id':data.id});
-    if(tem) return; //判断该工料机是否已经存在,是的话不用再次添加
+    if(tem) return tem; //判断该工料机是否已经存在,是的话不用再次添加
     //查看是否有组成物,有组成物的话先添加组成物信息
     data.ratio_data=[];
     if(data.subList && data.subList.length){
@@ -1706,4 +1706,5 @@ ProjectGLJ.prototype.loadNewProjectGLJToCache = function (data) {//把新插入
     let uIndex = gljUtil.getIndex(data.unit_price);
     if(!unitPriceMap[uIndex])  unitPriceMap[uIndex] = data.unit_price;
     this.datas.gljList.push(data);
+    return data;
 };

+ 15 - 8
web/building_saas/main/js/views/electrovalence_view.js

@@ -5,7 +5,7 @@ let electrovalenceObj = {
     setting:{
         header:[
             {headerName: "代号", headerWidth: 70, dataCode: "code", dataType: "String"},
-            {headerName: "名称", headerWidth: 150, dataCode: "name",dataType: "String"},
+            {headerName: "名称", headerWidth: 150, dataCode: "displayName",dataType: "String"},
             {headerName: "规格", headerWidth: 70, dataCode: "specs", dataType: "Number",validator:"number"},
             {headerName: "预算价", headerWidth: 75, dataCode: "electPrice", hAlign: "right", dataType: "Number",validator:"number"},
             {headerName: "加权系数", headerWidth: 80, dataCode: "coe", hAlign: "right", dataType: "Number",validator:"number"}
@@ -58,7 +58,7 @@ let electrovalenceObj = {
         this.calcPertElectrovalenceMarketPrice(this.datas);
         sheetCommonObj.showData(this.sheet, this.setting,this.datas);
         this.sheet.setRowCount(this.datas.length+1);
-        let nameCol = _.findIndex(this.setting.header,{'dataCode':'name'});
+        let nameCol = _.findIndex(this.setting.header,{'dataCode':'displayName'});
         let nameOptions = this.getElectrovalenceOptions();
         sheetCommonObj.setComboBox(-1,nameCol,this.sheet,nameOptions,false,false,5);
         sel.row =  oldData?_.findIndex(this.datas,{'ID':oldData.ID}):sel.row ;
@@ -66,11 +66,16 @@ let electrovalenceObj = {
     },
     getElectrovalenceDatas:function () {
         let datas = [];
+        let pgljMap = {};
         let com_electrovalence = projectObj.project.projectGLJ.datas.com_electrovalence;
+        for(let pg of projectObj.project.projectGLJ.datas.gljList){
+            pgljMap[gljUtil.getIndex(pg)] = pg;
+        }
         if(com_electrovalence && com_electrovalence.gljList){
             for (let g of com_electrovalence.gljList){
                 let t = this.createNewElectrovalenceData(g);
-                gljOprObj.setGLJPrice(t);
+                let tg = pgljMap[gljUtil.getIndex(g)];
+                if(tg) gljOprObj.setGLJPrice(t,tg);
                 datas.push(t);
             }
         }
@@ -82,6 +87,7 @@ let electrovalenceObj = {
             GLJID:g.GLJID,
             projectGLJID:g.projectGLJID,
             name:g.name,
+            displayName:g.displayName,
             code:g.code,
             specs:g.specs,
             unit:g.unit,
@@ -130,7 +136,7 @@ let electrovalenceObj = {
         let me = electrovalenceObj;
         let dataCode = me.setting.header[args.col].dataCode;
         let value = args.newValue;
-        if(dataCode == "name" && args.row >= me.datas.length) {//新增
+        if(dataCode == "displayName" && args.row >= me.datas.length) {//新增
              me.addElectrovalence(value);
         }else { //修改
             let tem = me.datas[args.row];
@@ -145,7 +151,7 @@ let electrovalenceObj = {
                 }
                 tem[dataCode] = value;
                 if(dataCode == 'electPrice') tem.marketPrice = value;
-            }else if(dataCode == 'name'){//下拉替换
+            }else if(dataCode == 'displayName'){//下拉替换
                 me.editElectrovalence(value,args.row,"replace");
             }
             me.showDatas(me.datas);
@@ -159,18 +165,19 @@ let electrovalenceObj = {
         try {
             let glj = _.find(this.options,{name:name});
             if(glj){
-                let tem = {name:glj.name,code:glj.code,specs:glj.specs,unit:glj.unit,type:glj.type,projectID : projectObj.project.ID()};
+                let tem = {displayName:glj.name,code:glj.code,specs:glj.specs,unit:glj.unit,type:glj.type,projectID : projectObj.project.ID()};
                 tem.ID = uuid.v1();
                 $.bootstrapLoading.start();
                 let result =  await ajaxPost('/glj/insertElectrovalence',tem);
                 //插入项目工料机列表
-                projectObj.project.projectGLJ.loadNewProjectGLJToCache(result.projetcGLJData);
+                let newProjectPGJ = projectObj.project.projectGLJ.loadNewProjectGLJToCache(result.projetcGLJData);
                 //加入综合电价显示列表缓存
                 tem.GLJID = result.projetcGLJData.glj_id;
                 tem.projectGLJID = result.projetcGLJData.id;
+                tem.name =  result.projetcGLJData.name;
                 tem.coe = 0;
                 tem.from = "std";
-                gljOprObj.setGLJPrice(tem);
+                gljOprObj.setGLJPrice(tem,newProjectPGJ);
 
                 if(type == "add"){
                     this.datas.push(tem);

+ 1 - 0
web/building_saas/pm/html/project-management.html

@@ -687,6 +687,7 @@
 <!-- JS. -->
 <script src = "/lib/spreadjs/sheets/gc.spread.sheets.all.11.1.2.min.js"></script>
 <script src = "/lib/fileSaver/FileSaver.min.js"></script>
+<script src="/lib/qiniu/qiniu.min.js"></script>
 <script>GC.Spread.Sheets.LicenseKey = '<%- LicenseKey %>';</script>
 <!-- inject:js -->
 <script src="/web/building_saas/js/global.js"></script>

+ 78 - 50
web/building_saas/pm/js/pm_newMain.js

@@ -404,8 +404,11 @@ const projTreeObj = {
                 return true;
             },
             callback: function (key, opt) {
-                //获取当前节点的建设项目ID
+
+
+                $("#confirm-import").hide();
                 $("#import").modal('show');
+                projTreeObj.getUploadToken();
             }
         }
     },
@@ -1588,6 +1591,11 @@ const projTreeObj = {
         }
         updateData["self"] ={ParentID:parent.id(),NextSiblingID:next?next.id():-1};
         return updateData;
+    },
+    getUploadToken:async function () {
+        let result =await ajaxGet("/pm/api/getUploadToken");
+        $("#confirm-import").show();
+        projTreeObj.uptoken=result.uptoken;
     }
 
 };
@@ -3785,58 +3793,78 @@ $("#confirm-import").click(function() {
         return;
     }
     STATE.importing = true;
-    const self = $(this);
-    try {
-        let formData = new FormData();
-        let file = $("input[name='import_project_data']")[0];
-        if (file.files.length <= 0) {
-            throw '请选择文件!';
-        }
-        formData.append('file', file.files[0]);
-        formData.append('userID', userID);
-        formData.append("updateData",JSON.stringify(projTreeObj.getImportProjectDate()));
-        $('#import').modal("hide");
-        $.bootstrapLoading.progressStart("导入建设项目",true);
-        $.ajax({
-            url: '/pm/api/importProject',
-            type: 'POST',
-            data: formData,
-            cache: false,
-            contentType: false,
-            processData: false,
-            timeout:300000,
-            beforeSend: function() {
-                self.attr('disabled', 'disabled');
-                self.text('上传中...');
-            },
-            success: function(response){
-                STATE.importing = false;
-                self.text('确定导入');
-                $.bootstrapLoading.progressEnd();
-                if(response.error == 1){
-                    alert(response.msg);
-                    setTimeout(function () {
-                        $.bootstrapLoading.progressEnd();//不做这个的话太快,页面不会自动关闭
-                    },500)
-                }else {
-                    refreshAllPage();
-                }
 
-            },
-            error: function(){
-                STATE.importing = false;
-                setTimeout(function () {
-                    self.text('确定导入');
-                    $.bootstrapLoading.progressEnd();
-                    alert("导入失败,请检查文件!");
-                },1000)
+    let input = $("input[name='import_project_data']")[0];
+    if (input.files.length <= 0) {
+        throw '请选择文件!';
+    }
+    let token = projTreeObj.uptoken;
+    $('#import').modal("hide");
+    $.bootstrapLoading.progressStart("上传文件中",true);
+    let file = input.files[0];
+    let key = uuid.v1() + ".ybp"; //file.name;
+    if (file) {
+        let config = {
+            useCdnDomain: true,
+            disableStatisticsReport: false,
+            retryCount: 6,
+            region: qiniu.region.z2
+        };
+        let putExtra = {
+            fname: "",
+            params: {"x:name":key.split(".")[0]},
+            mimeType: null
+        };
+        // 添加上传dom面板
+        let observable = qiniu.upload(file, key, token, putExtra, config);
+         observable.subscribe({
+             next:function (reponse) {
+                 console.log(reponse);
+             },
+             error:function (err) {
+                 console.log(err);
+             },
+             complete:function(res){
+                 console.log("complete")
+                 $("#progress_modal_body").text("正在导入建设项目");
+                 startImportProject(key);
+                 projTreeObj.uptoken = null;
+             }
+         });
+    }
+
+    async function  startImportProject(key) {
+        try {
+            console.log("start Import");
+            let result = await ajaxPost("/pm/api/importProject",{key:key,updateData:projTreeObj.getImportProjectDate()});
+            setTimeout(importProcessChecking,2000);
+        }catch (error){
+            alert(error);
+            $.bootstrapLoading.end();
+        }finally {
+            STATE.importing = false;
+        }
+    }
+
+    async function importProcessChecking() {
+        let result = await ajaxPost("/pm/api/importProcessChecking",{key:key,user_id:userID});
+        if(result.error == 1){
+            let message = result.msg?result.msg:result.message;
+            setTimeout(function () {
+                $.bootstrapLoading.progressEnd();//不做这个的话太快,页面不会自动关闭
+            },500);
+            alert(message)
+        }else if(result.error == 0){
+            if(result.status == "processing"){
+                setTimeout(importProcessChecking,2000);
+            }else if(result.status == "complete"){
+                $.bootstrapLoading.progressEnd();
+                refreshAllPage();
             }
-        });
-    } catch(error) {
-        STATE.importing = false;
-        alert(error);
-        $.bootstrapLoading.end();
+        }
     }
+    
+    
 });
 
 $("#import_project_data").change(function(){