pm_controller.js 31 KB

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