pm_controller.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724
  1. /**
  2. * Created by Mai on 2017/1/18.
  3. */
  4. import UnitPriceFileModel from "../../glj/models/unit_price_file_model";
  5. import moment from 'moment';
  6. import CompilationModel from "../../users/models/compilation_model";
  7. let mongoose = require('mongoose');
  8. let ProjectsData = require('../models/project_model').project;
  9. let labourCoe = require('../../main/facade/labour_coe_facade');
  10. let projType = require('../models/project_model').projType;
  11. let fileType = require('../models/project_model').fileType;
  12. const engineering = require("../../common/const/engineering");
  13. let EngineeringLibModel = require("../../users/models/engineering_lib_model");
  14. let fee_rate_facade = require("../../fee_rates/facade/fee_rates_facade");
  15. let billsModel = require('../../main/models/bills').model;
  16. let rationsModel = require('../../main/models/ration').model;
  17. let projectModel = mongoose.model('projects');
  18. let unitPriceFileModel = mongoose.model('unit_price_file');
  19. let feeRateFileModel = mongoose.model('fee_rate_file');
  20. let asyncTool = require('async');
  21. let pm_facade = require('../facade/pm_facade');
  22. const userModel = mongoose.model('user');
  23. let config = require("../../../config/config.js");
  24. const optionModel = mongoose.model('options');
  25. const stdBillsGuidanceLibModel = mongoose.model('std_billsGuidance_lib');
  26. const fs = require('fs');
  27. const _ = require('lodash');
  28. import SectionTreeDao from '../../complementary_ration_lib/models/sectionTreeModel';
  29. let sectionTreeDao = new SectionTreeDao();
  30. let consts = require('../../main/models/project_consts');
  31. import multiparty from 'multiparty';
  32. let rp = require('request-promise');
  33. //统一回调函数
  34. let callback = function(req, res, err, message, data){
  35. res.json({error: err, message: message, data: data});
  36. };
  37. module.exports = {
  38. checkRight: function (req, res) {
  39. if(typeof req.body.data === 'object'){
  40. req.body.data = JSON.stringify(req.body.data);
  41. }
  42. let data = JSON.parse(req.body.data);
  43. if (data.user_id) {
  44. return data.user_id === req.session.sessionUser.id;
  45. } else {
  46. return false;
  47. }
  48. },
  49. checkProjectRight: function (userId, projectId, callback) {
  50. ProjectsData.getProject(projectId).then(async function (result) {
  51. /**
  52. * result._doc.userID(Number): MongoDB
  53. * userId(String): Session.userID
  54. */
  55. let shareInfo = null;
  56. //判断是否是打开分享的项目,分享项目shareInfo不为null
  57. if(userId !== result.userID){
  58. shareInfo = await pm_facade.getShareInfo(userId, result);
  59. }
  60. if ((userId === result.userID || shareInfo) && result._doc.projType === projType.tender) {
  61. callback(true, result, shareInfo);
  62. } else {
  63. callback(false);
  64. }
  65. }).catch(function (err) {
  66. callback(false);
  67. });
  68. },
  69. getProjects: async function(req, res){
  70. await ProjectsData.getUserProjects(req.session.sessionUser.id, req.session.sessionCompilation._id, function(err, message, projects){
  71. if (projects) {
  72. callback(req, res, err, message, projects);
  73. } else {
  74. callback(req, res, err, message, null);
  75. }
  76. });
  77. },
  78. updateProjects: async function (req, res) {
  79. let data = JSON.parse(req.body.data);
  80. await ProjectsData.updateUserProjects(req.session.sessionUser.id, req.session.sessionCompilation._id, req.session.sessionCompilation, data.updateData, function (err, message, data) {
  81. if (err === 0) {
  82. callback(req, res, err, message, data);
  83. } else {
  84. callback(req, res, err, message, null);
  85. }
  86. });
  87. },
  88. // CSL, 2017-12-14 该方法用于项目属性:提交保存混合型数据,这些数据来自不同的表,包括projects.property、ration、bills、labour_coes.
  89. updateMixDatas: async function(req, res){
  90. let datas = JSON.parse(req.body.data).mixDataArr;
  91. let functions = [];
  92. function updateFunc(model, cod, doc) {
  93. return function (cb) {
  94. model.update(cod, doc, cb);
  95. }
  96. };
  97. function updateLC(){
  98. return function (cb) {
  99. datas.labourCoes.updateData.projectID = datas.projectID;
  100. labourCoe.save(datas.labourCoes.updateData, cb);
  101. }
  102. };
  103. // 项目属性
  104. if (Object.keys(datas.properties).length > 0){
  105. //基本信息特殊处理,更新建设项目
  106. if(datas.properties['property.basicInformation']){
  107. let constructionProject = await pm_facade.getConstructionProject(datas.projectID);
  108. if(constructionProject){
  109. functions.push(updateFunc(projectModel, {ID: constructionProject.ID}, {'property.basicInformation': datas.properties['property.basicInformation']}));
  110. }
  111. delete datas.properties['property.basicInformation'];
  112. }
  113. functions.push(updateFunc(projectModel, {ID: datas.projectID}, datas.properties));
  114. };
  115. //选项
  116. if(datas.options && datas.options.updateData){
  117. functions.push(updateFunc(optionModel, {user_id: req.session.sessionUser.id, compilation_id: req.session.sessionCompilation._id}, {'options.GENERALOPTS': datas.options.updateData}));
  118. }
  119. // 人工系数
  120. if (datas.labourCoes&&datas.labourCoes.updateData){
  121. functions.push(updateLC());
  122. };
  123. // 清单:每文档doc只存储一条清单,每条清单都必须定位一次文档,无法合并处理
  124. if (datas.bills.length > 0){
  125. for (let bill of datas.bills){
  126. functions.push(updateFunc(billsModel, {projectID: datas.projectID, ID: bill.ID, deleteInfo: null}, bill));
  127. };
  128. };
  129. // 定额:每文档doc只存储一条定额,每条定额都必须定位一次文档,无法合并处理
  130. if (datas.rations.length > 0){
  131. for (let ration of datas.rations){
  132. functions.push(updateFunc(rationsModel, {projectID: datas.projectID, ID: ration.ID, deleteInfo: null}, ration));
  133. };
  134. };
  135. asyncTool.parallel(functions, function(err, result){
  136. {
  137. if (!err) {
  138. res.json({error: 0, message: err, data: result});
  139. } else {
  140. res.json({error: 1, message: err, data: null});
  141. }
  142. }
  143. });
  144. },
  145. updateFiles: async function(req, res){
  146. let data = JSON.parse(req.body.data);
  147. let updateDatas = data.updateDatas;
  148. await ProjectsData.udpateUserFiles(req.session.sessionUser.id, updateDatas, function (err, message, data) {
  149. callback(req, res, err, message, data);
  150. });
  151. },
  152. defaultSettings: async function(req, res){
  153. try{
  154. let data = JSON.parse(req.body.data);
  155. let projectID = data.projectID;
  156. let defaultSettingSc = await ProjectsData.defaultSettings(req.session.sessionUser.id, req.session.sessionCompilation._id, projectID);
  157. if(!defaultSettingSc){
  158. throw '恢复失败';
  159. }
  160. res.json({error: 0, message: '恢复成功', data: null});
  161. }
  162. catch(error){
  163. console.log(error);
  164. res.json({error: 1, message: error, data: null});
  165. }
  166. },
  167. /* copyProjects: function (req, res) {
  168. let data = JSON.parse(req.body.data);
  169. ProjectsData.copyUserProjects(req.session.sessionUser.id, req.session.sessionCompilation._id, data.updateData, function (err, message, data) {
  170. if (err === 0) {
  171. callback(req, res, err, message, data);
  172. } else {
  173. callback(req, res, err, message, null);
  174. }
  175. });
  176. },*/
  177. rename: function (req, res) {
  178. let data = JSON.parse(req.body.data);
  179. ProjectsData.rename(req.session.sessionUser.id, req.session.sessionCompilation._id, data, function (err, message) {
  180. callback(req, res, err, message, null);
  181. });
  182. },
  183. //project getData接口
  184. getData: function(projectID, callback) {
  185. projectModel.findOne({$or: [{deleteInfo: null}, {'deleteInfo.deleted': false}], ID: projectID}, '-_id').then(async function (project) {
  186. if (!project) {
  187. callback('', consts.projectConst.PROJECT_INFO, {});
  188. }
  189. let engineeringLibModel = new EngineeringLibModel();
  190. let engineeringInfo = project !== null && project.property.engineering_id !== undefined ?
  191. await engineeringLibModel.getEngineering(project.property.engineering_id) : null;
  192. let projInfo = project._doc;
  193. if (engineeringInfo !== null) {
  194. if(engineeringInfo.billsGuidance_lib){
  195. for(let billsGuidanceLib of engineeringInfo.billsGuidance_lib){
  196. let stdBillsGuidanceLib = await stdBillsGuidanceLibModel.findOne({ID: billsGuidanceLib.id});
  197. if(stdBillsGuidanceLib){
  198. billsGuidanceLib.type = stdBillsGuidanceLib.type ? stdBillsGuidanceLib.type : 1;
  199. }
  200. }
  201. }
  202. projInfo.engineeringInfo = engineeringInfo;
  203. }
  204. //读取建设项目的基本信息
  205. let basicInfo = await ProjectsData.getBasicInfo(projectID);
  206. if(basicInfo !== null){
  207. projInfo.property.basicInformation = basicInfo;
  208. }
  209. //获取单位工程完整目录结构
  210. let fullPath = await pm_facade.getFullPath(projectID);
  211. projInfo.fullPath = fullPath;
  212. callback('', consts.projectConst.PROJECT_INFO, project);
  213. }, function (err) {
  214. callback(err, consts.projectConst.PROJECT_INFO, {});
  215. });
  216. },
  217. getProject: function(req, res){
  218. let data = JSON.parse(req.body.data);
  219. let projectID = data.proj_id;
  220. ProjectsData.getUserProject(req.session.sessionUser.id, data.proj_id, async function(err, message, data){
  221. if (err === 0) {
  222. let engineeringLibModel = new EngineeringLibModel();
  223. let engineeringInfo = data !== null && data.property.engineering_id !== undefined ?
  224. await engineeringLibModel.getEngineering(data.property.engineering_id) : null;
  225. let strData = JSON.stringify(data);
  226. let projInfo = JSON.parse(strData);
  227. if (engineeringInfo !== null) {
  228. if(engineeringInfo.billsGuidance_lib){
  229. for(let billsGuidanceLib of engineeringInfo.billsGuidance_lib){
  230. let stdBillsGuidanceLib = await stdBillsGuidanceLibModel.findOne({ID: billsGuidanceLib.id});
  231. if(stdBillsGuidanceLib){
  232. billsGuidanceLib.type = stdBillsGuidanceLib.type ? stdBillsGuidanceLib.type : 1;
  233. }
  234. }
  235. }
  236. projInfo.engineeringInfo = engineeringInfo;
  237. }
  238. //读取建设项目的基本信息
  239. let basicInfo = await ProjectsData.getBasicInfo(projectID);
  240. if(basicInfo !== null){
  241. projInfo.property.basicInformation = basicInfo;
  242. }
  243. //获取单位工程完整目录结构
  244. let fullPath = await pm_facade.getFullPath(projectID);
  245. projInfo.fullPath = fullPath;
  246. callback(req, res, err, message, projInfo);
  247. } else {
  248. callback(req, res, err, message, null);
  249. }
  250. });
  251. },
  252. beforeOpenProject: function (req, res) {
  253. let data = JSON.parse(req.body.data);
  254. ProjectsData.beforeOpenProject(req.session.sessionUser.id, data.proj_id, data.updateData, function (err, message, data) {
  255. callback(req, res, err, message, data);
  256. });
  257. },
  258. getNewProjectID: function (req, res) {
  259. let data = JSON.parse(req.body.data);
  260. ProjectsData.getNewProjectID(data.count, function (err, message, data) {
  261. callback(req, res, err, message, data);
  262. });
  263. },
  264. // 项目管理首页
  265. index: async function(request, response) {
  266. // 获取编办信息
  267. let sessionCompilation = request.session.sessionCompilation;
  268. if (sessionCompilation === undefined ||sessionCompilation ===null) {
  269. return response.redirect('/logout');
  270. }
  271. let compilationModel = new CompilationModel();
  272. //更新编办信息
  273. let compilationData = await compilationModel.getCompilationById(sessionCompilation._id);
  274. request.session.sessionCompilation = compilationData;
  275. sessionCompilation = request.session.sessionCompilation;
  276. //更新用户的使用过的费用定额列表
  277. //是否第一次进入该费用定额
  278. let isFirst = await pm_facade.isFirst(request.session.sessionUser.id, compilationData._id.toString());
  279. // 清单计价
  280. let billValuation = sessionCompilation.bill_valuation !== undefined ?
  281. sessionCompilation.bill_valuation : [];
  282. // 获取标准库数据
  283. let engineeringLibModel = new EngineeringLibModel();
  284. billValuation = await engineeringLibModel.getLib(billValuation);
  285. // 定额计价
  286. let rationValuation = sessionCompilation.ration_valuation !== undefined ?
  287. sessionCompilation.ration_valuation : [];
  288. rationValuation = await engineeringLibModel.getLib(rationValuation);
  289. let absoluteUrl = compilationData.overWriteUrl ? request.app.locals.rootDir + compilationData.overWriteUrl : request.app.locals.rootDir;
  290. let overWriteUrl = fs.existsSync(absoluteUrl) && fs.statSync(absoluteUrl).isFile()? compilationData.overWriteUrl : null;
  291. let renderData = {
  292. isFirst: isFirst,
  293. userAccount: request.session.userAccount,
  294. userID: request.session.sessionUser.id,
  295. compilationData: JSON.stringify(sessionCompilation),
  296. overWriteUrl: overWriteUrl,
  297. billValuation: JSON.stringify(billValuation),
  298. rationValuation: JSON.stringify(rationValuation),
  299. engineeringList: JSON.stringify(engineering.List),
  300. compilationName: sessionCompilation.name,
  301. versionName: request.session.compilationVersion,
  302. LicenseKey:config.getLicenseKey(process.env.NODE_ENV)
  303. };
  304. response.render('building_saas/pm/html/project-management.html', renderData);
  305. },
  306. //第一次进入该费用定额时准备的初始数据
  307. prepareInitialData: async function(request, response) {
  308. try {
  309. let sessionCompilation = request.session.sessionCompilation;
  310. await pm_facade.prepareInitialData(request.session.sessionUser.id, sessionCompilation._id, sessionCompilation.example);
  311. callback(request, response, 0, 'success', null);
  312. } catch(err) {
  313. callback(request, response, 1, err, null);
  314. }
  315. },
  316. // 获取单价文件列表
  317. getUnitFileList: async function(request, response) {
  318. let data = request.body.data;
  319. try {
  320. data = JSON.parse(data);
  321. let projectId = data.parentID !== undefined ? data.parentID : 0;
  322. if (isNaN(projectId) && projectId <= 0) {
  323. throw {msg: 'id数据有误!', err: 1};
  324. }
  325. /*// 获取对应建设项目下所有的单位工程id
  326. let idList = await ProjectsData.getTenderByProjectId(projectId);
  327. if (idList.length <= 0) {
  328. throw {msg: '不存在对应单位工程', err: 0};
  329. }*/
  330. // 获取对应的单价文件
  331. let unitPriceFileModel = new UnitPriceFileModel();
  332. let unitPriceFileData = await unitPriceFileModel.getDataByRootProject(projectId);
  333. if (unitPriceFileData === null) {
  334. throw {msg: '不存在对应单价文件', err: 0};
  335. }
  336. // 整理数据
  337. let unitPriceFileList = [];
  338. for (let unitPriceFile of unitPriceFileData) {
  339. let tmp = {
  340. name: unitPriceFile.name,
  341. id: unitPriceFile.id
  342. };
  343. unitPriceFileList.push(tmp);
  344. }
  345. callback(request, response, 0, '', unitPriceFileList);
  346. } catch (error) {
  347. console.log(error);
  348. let responseData = error.err === 1 ? null : [];
  349. callback(request, response, error.err, error.msg, responseData);
  350. }
  351. },
  352. getFeeRateFileList:async function(request, response) {
  353. let data = request.body.data;
  354. try {
  355. data = JSON.parse(data);
  356. let projectId = data.parentID !== undefined ? data.parentID : 0;
  357. if (isNaN(projectId) && projectId <= 0) {
  358. throw {msg: 'id数据有误!', err: 1};
  359. }
  360. // 获取对应建设项目下所有的单位工程id
  361. let feeRateFileList = await fee_rate_facade.getFeeRatesByProject(projectId);
  362. callback(request, response, 0, '',feeRateFileList );
  363. } catch (error) {
  364. console.log(error);
  365. let responseData = error.err === 1 ? null : [];
  366. callback(request, response, error.err, error.msg, responseData);
  367. }
  368. },
  369. getGCDatas: async function(request, response) {
  370. let userID = request.session.sessionUser.id;
  371. let compilatoinId = request.session.sessionCompilation._id;
  372. let rst = [];
  373. let _projs = Object.create(null), _engs = Object.create(null), prefix = 'ID_';
  374. try{
  375. let gc_unitPriceFiles = await ProjectsData.getGCFiles(fileType.unitPriceFile, userID);
  376. let gc_feeRateFiles = await ProjectsData.getGCFiles(fileType.feeRateFile, userID);
  377. let gc_tenderFiles = await ProjectsData.getGCFiles(projType.tender, userID);
  378. for(let i = 0, len = gc_unitPriceFiles.length; i < len; i++){
  379. let gc_uf = gc_unitPriceFiles[i];
  380. let theProj = _projs[prefix + gc_uf.root_project_id] || null;
  381. if(!theProj){
  382. let tempProj = await ProjectsData.getProjectsByIds(userID, compilatoinId, [gc_uf.root_project_id]);
  383. if(tempProj.length > 0 && tempProj[0].projType !== projType.folder){
  384. theProj = _projs[prefix + gc_uf.root_project_id] = tempProj[0]._doc;
  385. buildProj(theProj);
  386. }
  387. }
  388. if(theProj){
  389. theProj.unitPriceFiles.push(gc_uf);
  390. }
  391. }
  392. for(let i = 0, len = gc_feeRateFiles.length; i < len; i++){
  393. let gc_ff = gc_feeRateFiles[i];
  394. let theProj = _projs[prefix + gc_ff.rootProjectID] || null;
  395. if(!theProj){
  396. let tempProj = await ProjectsData.getProjectsByIds(userID, compilatoinId, [gc_ff.rootProjectID]);
  397. if(tempProj.length > 0 && tempProj[0].projType !== projType.folder){
  398. theProj = _projs[prefix + gc_ff.rootProjectID] = tempProj[0]._doc;
  399. buildProj(theProj);
  400. }
  401. }
  402. if(theProj) {
  403. theProj.feeRateFiles.push(gc_ff);
  404. }
  405. }
  406. if(gc_tenderFiles.length > 0){
  407. for(let i = 0, len = gc_tenderFiles.length; i < len; i++){
  408. let gc_t = gc_tenderFiles[i];
  409. let theProj = _projs[prefix + gc_t.ParentID] || null;
  410. if(!theProj){
  411. let tempProjs = await ProjectsData.getProjectsByIds(userID, compilatoinId, [gc_t.ParentID]);
  412. if(tempProjs.length > 0 && tempProjs[0].projType === projType.project){
  413. theProj = _projs[prefix + gc_t.ParentID] = tempProjs[0]._doc;
  414. buildProj(theProj);
  415. }
  416. }
  417. if(theProj) {
  418. theProj.children.push(gc_t);
  419. }
  420. }
  421. }
  422. for(let i in _projs){
  423. rst.push(_projs[i]);
  424. }
  425. function buildProj(proj){
  426. proj.children = [];
  427. proj.unitPriceFiles = [];
  428. proj.feeRateFiles = [];
  429. }
  430. callback(request, response, 0, 'success', rst);
  431. }
  432. catch (error){
  433. callback(request, response, true, error, null);
  434. }
  435. },
  436. recGC: function(request, response){
  437. let userID = request.session.sessionUser.id,
  438. compilationId = request.session.sessionCompilation._id;
  439. let data = JSON.parse(request.body.data);
  440. let nodes = data.nodes;
  441. ProjectsData.recGC(userID, compilationId, nodes, function (err, msg, data) {
  442. callback(request, response, err, msg, data);
  443. });
  444. },
  445. delGC: async function(request, response){
  446. let data = JSON.parse(request.body.data);
  447. let delDatas = data.delDatas;
  448. let bulkProjs = [], bulkUFs = [], bulkFFs = [];
  449. try{
  450. for(let data of delDatas){
  451. if(data.updateType === 'Project'){
  452. bulkProjs.push({updateOne: {filter: {ID: data.ID}, update: {'deleteInfo.completeDeleted': true}}});
  453. }
  454. else if(data.updateType === fileType.unitPriceFile){
  455. bulkUFs.push({updateOne: {filter: {id: data.ID}, update: {'deleteInfo.completeDeleted': true}}});
  456. }
  457. else{
  458. bulkFFs.push({updateOne: {filter: {ID: data.ID}, update: {'deleteInfo.completeDeleted': true}}});
  459. }
  460. }
  461. if(bulkProjs.length > 0){
  462. await projectModel.bulkWrite(bulkProjs);
  463. }
  464. if(bulkUFs.length > 0){
  465. await unitPriceFileModel.bulkWrite(bulkUFs);
  466. }
  467. if(bulkFFs.length > 0){
  468. await feeRateFileModel.bulkWrite(bulkFFs);
  469. }
  470. callback(request, response, 0, 'success', null);
  471. } catch(err){
  472. callback(request, response, 1, err, null);
  473. }
  474. },
  475. moveProject:async function(req,res){
  476. let result={
  477. error:0
  478. };
  479. try {
  480. let data = req.body.data;
  481. let rdata= await pm_facade.moveProject(data);
  482. result.data= rdata;
  483. }catch (err){
  484. console.log(err);
  485. result.error=1;
  486. result.message = err.message;
  487. }
  488. res.json(result);
  489. },
  490. copyProjects:async function (req, res) {
  491. let result={
  492. error:0
  493. };
  494. try {
  495. let data = {dataString:req.body.data,userID:req.session.sessionUser.id,compilationID:req.session.sessionCompilation._id};
  496. result = await redirectToImportServer(data,"copyProject",req);
  497. }catch (err){
  498. console.log(err);
  499. result.error=1;
  500. result.message = err.message;
  501. }
  502. res.json(result);
  503. },
  504. projectShareInfo: async function(req, res){
  505. try{
  506. let data = JSON.parse(req.body.data);
  507. let shareInfo = await projectModel.findOne({ID: data.projectID, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]}, '-_id shareInfo');
  508. callback(req, res, 0, 'success', shareInfo);
  509. }
  510. catch (err){
  511. callback(req, res, 1, err, null);
  512. }
  513. },
  514. share: async function(req, res){
  515. try{
  516. let data = JSON.parse(req.body.data);
  517. let shareDate = moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'),
  518. shareUserIDs = [];
  519. for (let data of data.shareData) {
  520. shareUserIDs.push(data.userID);
  521. data.shareDate = shareDate;
  522. }
  523. //添加分享
  524. if(data.type === 'create'){
  525. //新增
  526. for (let sData of data.shareData) {
  527. await projectModel.update({ID: data.projectID, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]}, {$addToSet: {shareInfo: sData}});
  528. }
  529. } else if (data.type === 'update') {
  530. await projectModel.update({ID: data.projectID, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]}, {$set: {shareInfo: data.shareData}});
  531. }
  532. //取消分享
  533. else {
  534. await projectModel.update({ID: data.projectID, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]}, {$pull: {shareInfo: {userID: {$in: shareUserIDs}}}});
  535. }
  536. callback(req, res, 0, 'success', data.shareData);
  537. }
  538. catch (err){
  539. callback(req, res, 1, err, null);
  540. }
  541. },
  542. receiveProjects: async function(req, res) {
  543. try {
  544. let rst = {grouped: [], ungrouped: [], summaryInfo: null};
  545. let userID = req.session.sessionUser.id;
  546. let receiveProjects = await projectModel.find({
  547. $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}], compilation: req.session.sessionCompilation._id, 'shareInfo.userID': userID}, '-_id');
  548. //设置原项目用户信息
  549. if(receiveProjects.length > 0){
  550. let orgUserIDs = [];
  551. for(let proj of receiveProjects){
  552. orgUserIDs.push(proj.userID);
  553. if (proj.projType === projType.tender) {
  554. //设置工程专业
  555. proj._doc.feeStandardName = proj.property.feeStandardName || '';
  556. //设置项目类别
  557. proj._doc.valuationType = proj.property.valuationType === 'bill' ? '预算' : '工程清单';
  558. }
  559. delete proj._doc.property;
  560. }
  561. orgUserIDs = Array.from(new Set(orgUserIDs));
  562. let userObjIDs = [];
  563. for(let uID of orgUserIDs){
  564. userObjIDs.push(mongoose.Types.ObjectId(uID));
  565. }
  566. let orgUsersInfo = await userModel.find({_id: {$in : userObjIDs}});
  567. //建设项目
  568. let consProjIDs = [],
  569. ungroupedTenders = [];
  570. for(let proj of receiveProjects){
  571. if (proj.projType === projType.project) {
  572. consProjIDs.push(proj.ID);
  573. }
  574. //获取分享项目子项
  575. if (proj.projType !== projType.tender) {
  576. proj._doc.children = await pm_facade.getPosterityProjects([proj.ID]);
  577. for (let projC of proj._doc.children) {
  578. if (projC.projType === projType.project) {
  579. consProjIDs.push(projC.ID);
  580. } else if (projC.projType === projType.tender) {
  581. //设置工程专业
  582. projC._doc.feeStandardName = projC.property.feeStandardName || '';
  583. }
  584. delete projC._doc.property;
  585. }
  586. } else {//未分类的单位工程不进行汇总,只取价格信息
  587. ungroupedTenders.push(proj._doc);
  588. }
  589. //设置分组,单位工程及单项工程分到未分组那
  590. if (proj.projType === projType.tender || proj.projType === projType.engineering) {
  591. rst.ungrouped.push(proj);
  592. } else {
  593. rst.grouped.push(proj);
  594. }
  595. //设置项目类型为来自别人分享
  596. proj._doc.shareType = 'receive';
  597. for(let userData of orgUsersInfo){
  598. if(proj.userID == userData._id.toString()){
  599. let userInfo = {name: userData.real_name, mobile: userData.mobile, company: userData.company, email: userData.email};
  600. proj._doc.userInfo = userInfo;
  601. }
  602. }
  603. }
  604. consProjIDs = Array.from(new Set(consProjIDs));
  605. let summaryInfo = await pm_facade.getSummaryInfo(consProjIDs);
  606. let tendersFeeInfo = await pm_facade.getTendersFeeInfo(ungroupedTenders);
  607. rst.summaryInfo = {grouped: summaryInfo, ungrouped: tendersFeeInfo};
  608. }
  609. callback(req, res, 0, 'success', rst);
  610. }
  611. catch (err){
  612. console.log(err);
  613. callback(req, res, 1, err, null);
  614. }
  615. },
  616. getProjectsByQuery: async function (req, res) {
  617. try{
  618. let data = JSON.parse(req.body.data);
  619. let compilation = req.session.sessionCompilation._id;
  620. let query = data.query;
  621. query.compilation = compilation;
  622. let options = data.options;
  623. let projects = await projectModel.find(query, options);
  624. callback(req, res, 0, 'success', projects);
  625. }
  626. catch (err){
  627. callback(req, res, 1, err, null);
  628. }
  629. },
  630. getSummaryInfo: async function(req, res){
  631. try{
  632. let data = JSON.parse(req.body.data);
  633. let summaryInfo = await pm_facade.getSummaryInfo(data.projectIDs);
  634. callback(req, res, 0, 'success', summaryInfo);
  635. }
  636. catch (err){
  637. callback(req, res, 1, err, null);
  638. }
  639. },
  640. changeFile:async function(req,res){
  641. try{
  642. let data = JSON.parse(req.body.data);
  643. console.log(data);
  644. await pm_facade.changeFile(data.projects,data.user_id,data.fileID,data.name,data.from,data.type);
  645. callback(req, res, 0, 'success', []);
  646. }
  647. catch (err){
  648. console.log(err);
  649. callback(req, res, 1, err, null);
  650. }
  651. },
  652. exportProject:async function(req,res){
  653. let result={
  654. error:0
  655. };
  656. try {
  657. let data = {dataString:req.body.data,userID:req.session.sessionUser.id};
  658. result = await redirectToImportServer(data,"exportProject",req);
  659. }catch (err){
  660. console.log(err);
  661. result.error=1;
  662. result.message = err.message;
  663. }
  664. res.json(result);
  665. },
  666. importProject:async function(req,res){
  667. let form = new multiparty.Form({uploadDir: './tmp'});
  668. form.parse(req, async function (err, fields, files) {
  669. let path = "";
  670. try {
  671. console.log(fields);
  672. const file = typeof files.file !== 'undefined' ? files.file[0] : null;
  673. if (err || !file) {
  674. throw '上传失败。';
  675. };
  676. path = file.path;
  677. let data = fs.readFileSync(file.path,'utf-8');
  678. let body = {data: data, fields:fields, session:req.session};
  679. let result = await redirectToImportServer(body,"importProject",req);
  680. res.json(result);
  681. }catch (e){
  682. console.log(e);
  683. res.json({error:1,msg:"导入失败请检查文件!"})
  684. }finally {
  685. fs.unlinkSync(path);
  686. }
  687. })
  688. }
  689. };
  690. async function redirectToImportServer(data,action,req) {
  691. let importURL = config.getImportURL(process.env.NODE_ENV,req.headers.origin);
  692. let options = {
  693. method: 'POST',
  694. uri: `http://${importURL}/import/${action}`,
  695. body: data,
  696. timeout:220000,
  697. json: true
  698. };
  699. console.log("post import data to:"+options.uri);
  700. return await rp.post(options);
  701. }