pm_controller.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  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. //统一回调函数
  25. let callback = function(req, res, err, message, data){
  26. res.json({error: err, message: message, data: data});
  27. };
  28. module.exports = {
  29. checkRight: function (req, res) {
  30. if(typeof req.body.data === 'object'){
  31. req.body.data = JSON.stringify(req.body.data);
  32. }
  33. let data = JSON.parse(req.body.data);
  34. if (data.user_id) {
  35. return data.user_id === req.session.sessionUser.id;
  36. } else {
  37. return false;
  38. }
  39. },
  40. checkProjectRight: function (userId, projectId, callback) {
  41. ProjectsData.getProject(projectId).then(function (result) {
  42. /**
  43. * result._doc.userID(Number): MongoDB
  44. * userId(String): Session.userID
  45. */
  46. //result._doc.userID == userId &&
  47. let isShare = false;
  48. if(userId !== result.userID){
  49. //判断是否是打开分享的项目
  50. for(let shareData of result.shareInfo){
  51. if(shareData.userID === userId){
  52. isShare = true;
  53. break;
  54. }
  55. }
  56. }
  57. if ((userId === result.userID || isShare) && result._doc.projType === projType.tender) {
  58. callback(true);
  59. } else {
  60. callback(false);
  61. }
  62. }).catch(function (err) {
  63. callback(false);
  64. });
  65. },
  66. getProjects: async function(req, res){
  67. await ProjectsData.getUserProjects(req.session.sessionUser.id, req.session.sessionCompilation._id, function(err, message, projects){
  68. if (projects) {
  69. callback(req, res, err, message, projects);
  70. } else {
  71. callback(req, res, err, message, null);
  72. }
  73. });
  74. },
  75. updateProjects: async function (req, res) {
  76. let data = JSON.parse(req.body.data);
  77. await ProjectsData.updateUserProjects(req.session.sessionUser.id, req.session.sessionCompilation._id, data.updateData, function (err, message, data) {
  78. if (err === 0) {
  79. callback(req, res, err, message, data);
  80. } else {
  81. callback(req, res, err, message, null);
  82. }
  83. });
  84. },
  85. // CSL, 2017-12-14 该方法用于项目属性:提交保存混合型数据,这些数据来自不同的表,包括projects.property、ration、bills、labour_coes.
  86. updateMixDatas: function(req, res){
  87. let datas = JSON.parse(req.body.data).mixDataArr;
  88. let functions = [];
  89. function updateFunc(model, cod, doc) {
  90. return function (cb) {
  91. model.update(cod, doc, cb);
  92. }
  93. };
  94. function updateLC(){
  95. return function (cb) {
  96. datas.labourCoes.updateData.projectID = datas.projectID;
  97. labourCoe.save(datas.labourCoes.updateData, cb);
  98. }
  99. };
  100. // 项目属性
  101. if (Object.keys(datas.properties).length > 0){
  102. functions.push(updateFunc(projectModel, {ID: datas.projectID}, datas.properties));
  103. };
  104. // 人工系数
  105. if (datas.labourCoes&&datas.labourCoes.updateData){
  106. functions.push(updateLC());
  107. };
  108. // 清单:每文档doc只存储一条清单,每条清单都必须定位一次文档,无法合并处理
  109. if (datas.bills.length > 0){
  110. for (let bill of datas.bills){
  111. functions.push(updateFunc(billsModel, {projectID: datas.projectID, ID: bill.ID, deleteInfo: null}, bill));
  112. };
  113. };
  114. // 定额:每文档doc只存储一条定额,每条定额都必须定位一次文档,无法合并处理
  115. if (datas.rations.length > 0){
  116. for (let ration of datas.rations){
  117. functions.push(updateFunc(rationsModel, {projectID: datas.projectID, ID: ration.ID, deleteInfo: null}, ration));
  118. };
  119. };
  120. asyncTool.parallel(functions, function(err, result){
  121. {
  122. if (!err) {
  123. res.json({error: 0, message: err, data: result});
  124. } else {
  125. res.json({error: 1, message: err, data: null});
  126. }
  127. }
  128. });
  129. },
  130. updateFiles: async function(req, res){
  131. let data = JSON.parse(req.body.data);
  132. let updateDatas = data.updateDatas;
  133. await ProjectsData.udpateUserFiles(req.session.sessionUser.id, updateDatas, function (err, message, data) {
  134. callback(req, res, err, message, data);
  135. });
  136. },
  137. /* copyProjects: function (req, res) {
  138. let data = JSON.parse(req.body.data);
  139. ProjectsData.copyUserProjects(req.session.sessionUser.id, req.session.sessionCompilation._id, data.updateData, function (err, message, data) {
  140. if (err === 0) {
  141. callback(req, res, err, message, data);
  142. } else {
  143. callback(req, res, err, message, null);
  144. }
  145. });
  146. },*/
  147. rename: function (req, res) {
  148. let data = JSON.parse(req.body.data);
  149. ProjectsData.rename(req.session.sessionUser.id, req.session.sessionCompilation._id, data, function (err, message) {
  150. callback(req, res, err, message, null);
  151. });
  152. },
  153. getProject: function(req, res){
  154. let data = JSON.parse(req.body.data);
  155. ProjectsData.getUserProject(req.session.sessionUser.id, data.proj_id, async function(err, message, data){
  156. if (err === 0) {
  157. let engineeringLibModel = new EngineeringLibModel();
  158. let engineeringInfo = data !== null && data.property.engineering_id !== undefined ?
  159. await engineeringLibModel.getEngineering(data.property.engineering_id) : null;
  160. let strData = JSON.stringify(data);
  161. let projInfo = JSON.parse(strData);
  162. if (engineeringInfo !== null) {
  163. projInfo.engineeringInfo = engineeringInfo;
  164. }
  165. callback(req, res, err, message, projInfo);
  166. } else {
  167. callback(req, res, err, message, null);
  168. }
  169. });
  170. },
  171. beforeOpenProject: function (req, res) {
  172. let data = JSON.parse(req.body.data);
  173. ProjectsData.beforeOpenProject(req.session.sessionUser.id, data.proj_id, data.updateData, function (err, message, data) {
  174. callback(req, res, err, message, data);
  175. });
  176. },
  177. getNewProjectID: function (req, res) {
  178. let data = JSON.parse(req.body.data);
  179. ProjectsData.getNewProjectID(data.count, function (err, message, data) {
  180. callback(req, res, err, message, data);
  181. });
  182. },
  183. // 项目管理首页
  184. index: async function(request, response) {
  185. // 获取编办信息
  186. let sessionCompilation = request.session.sessionCompilation;
  187. if (sessionCompilation === undefined) {
  188. return response.redirect('/logout');
  189. }
  190. let compilationModel = new CompilationModel();
  191. //更新编办信息
  192. let compilationData = await compilationModel.getCompilationById(sessionCompilation._id);
  193. request.session.sessionCompilation = compilationData;
  194. sessionCompilation = request.session.sessionCompilation;
  195. // 清单计价
  196. let billValuation = sessionCompilation.bill_valuation !== undefined ?
  197. sessionCompilation.bill_valuation : [];
  198. // 获取标准库数据
  199. let engineeringLibModel = new EngineeringLibModel();
  200. billValuation = await engineeringLibModel.getLib(billValuation);
  201. // 定额计价
  202. let rationValuation = sessionCompilation.ration_valuation !== undefined ?
  203. sessionCompilation.ration_valuation : [];
  204. rationValuation = await engineeringLibModel.getLib(rationValuation);
  205. let renderData = {
  206. userAccount: request.session.userAccount,
  207. userID: request.session.sessionUser.id,
  208. compilationData: JSON.stringify(sessionCompilation),
  209. billValuation: JSON.stringify(billValuation),
  210. rationValuation: JSON.stringify(rationValuation),
  211. engineeringList: JSON.stringify(engineering.List),
  212. versionName: sessionCompilation.name + '免费版',
  213. LicenseKey:config.getLicenseKey(process.env.NODE_ENV)
  214. };
  215. response.render('building_saas/pm/html/project-management.html', renderData);
  216. },
  217. // 获取单价文件列表
  218. getUnitFileList: async function(request, response) {
  219. let data = request.body.data;
  220. try {
  221. data = JSON.parse(data);
  222. let projectId = data.parentID !== undefined ? data.parentID : 0;
  223. if (isNaN(projectId) && projectId <= 0) {
  224. throw {msg: 'id数据有误!', err: 1};
  225. }
  226. /*// 获取对应建设项目下所有的单位工程id
  227. let idList = await ProjectsData.getTenderByProjectId(projectId);
  228. if (idList.length <= 0) {
  229. throw {msg: '不存在对应单位工程', err: 0};
  230. }*/
  231. // 获取对应的单价文件
  232. let unitPriceFileModel = new UnitPriceFileModel();
  233. let unitPriceFileData = await unitPriceFileModel.getDataByRootProject(projectId);
  234. if (unitPriceFileData === null) {
  235. throw {msg: '不存在对应单价文件', err: 0};
  236. }
  237. // 整理数据
  238. let unitPriceFileList = [];
  239. for (let unitPriceFile of unitPriceFileData) {
  240. let tmp = {
  241. name: unitPriceFile.name,
  242. id: unitPriceFile.id
  243. };
  244. unitPriceFileList.push(tmp);
  245. }
  246. callback(request, response, 0, '', unitPriceFileList);
  247. } catch (error) {
  248. console.log(error);
  249. let responseData = error.err === 1 ? null : [];
  250. callback(request, response, error.err, error.msg, responseData);
  251. }
  252. },
  253. getFeeRateFileList:async function(request, response) {
  254. let data = request.body.data;
  255. try {
  256. data = JSON.parse(data);
  257. let projectId = data.parentID !== undefined ? data.parentID : 0;
  258. if (isNaN(projectId) && projectId <= 0) {
  259. throw {msg: 'id数据有误!', err: 1};
  260. }
  261. // 获取对应建设项目下所有的单位工程id
  262. let feeRateFileList = await fee_rate_facade.getFeeRatesByProject(projectId);
  263. callback(request, response, 0, '',feeRateFileList );
  264. } catch (error) {
  265. console.log(error);
  266. let responseData = error.err === 1 ? null : [];
  267. callback(request, response, error.err, error.msg, responseData);
  268. }
  269. },
  270. getGCDatas: async function(request, response) {
  271. let userID = request.session.sessionUser.id;
  272. let compilatoinId = request.session.sessionCompilation._id;
  273. let rst = [];
  274. let _projs = Object.create(null), _engs = Object.create(null), prefix = 'ID_';
  275. try{
  276. let gc_unitPriceFiles = await ProjectsData.getGCFiles(fileType.unitPriceFile, userID);
  277. let gc_feeRateFiles = await ProjectsData.getGCFiles(fileType.feeRateFile, userID);
  278. let gc_tenderFiles = await ProjectsData.getGCFiles(projType.tender, userID);
  279. for(let i = 0, len = gc_unitPriceFiles.length; i < len; i++){
  280. let gc_uf = gc_unitPriceFiles[i];
  281. let theProj = _projs[prefix + gc_uf.root_project_id] || null;
  282. if(!theProj){
  283. let tempProj = await ProjectsData.getProjectsByIds(userID, compilatoinId, [gc_uf.root_project_id]);
  284. if(tempProj.length > 0 && tempProj[0].projType !== projType.folder){
  285. theProj = _projs[prefix + gc_uf.root_project_id] = tempProj[0]._doc;
  286. buildProj(theProj);
  287. }
  288. }
  289. if(theProj){
  290. theProj.unitPriceFiles.push(gc_uf);
  291. }
  292. }
  293. for(let i = 0, len = gc_feeRateFiles.length; i < len; i++){
  294. let gc_ff = gc_feeRateFiles[i];
  295. let theProj = _projs[prefix + gc_ff.rootProjectID] || null;
  296. if(!theProj){
  297. let tempProj = await ProjectsData.getProjectsByIds(userID, compilatoinId, [gc_ff.rootProjectID]);
  298. if(tempProj.length > 0 && tempProj[0].projType !== projType.folder){
  299. theProj = _projs[prefix + gc_ff.rootProjectID] = tempProj[0]._doc;
  300. buildProj(theProj);
  301. }
  302. }
  303. if(theProj) {
  304. theProj.feeRateFiles.push(gc_ff);
  305. }
  306. }
  307. if(gc_tenderFiles.length > 0){
  308. for(let i = 0, len = gc_tenderFiles.length; i < len; i++){
  309. let gc_t = gc_tenderFiles[i];
  310. let theEng = _engs[prefix + gc_t.ParentID] || null;
  311. if(!theEng){
  312. let tempEngs = await ProjectsData.getProjectsByIds(userID, compilatoinId, [gc_t.ParentID]);
  313. if(tempEngs.length > 0 && tempEngs[0].projType === projType.engineering){
  314. theEng = _engs[prefix + gc_t.ParentID] = tempEngs[0]._doc;
  315. theEng.children = [];
  316. }
  317. }
  318. if(theEng) {
  319. theEng.children.push(gc_t);
  320. let theProj = _projs[prefix + theEng.ParentID] || null;
  321. if(!theProj){
  322. let tempProj = await ProjectsData.getProjectsByIds(userID, compilatoinId, [theEng.ParentID]);
  323. if(tempProj.length > 0 && tempProj[0].projType === projType.project){
  324. theProj = _projs[prefix + theEng.ParentID] = tempProj[0]._doc;
  325. buildProj(theProj);
  326. }
  327. }
  328. if(theProj) {
  329. let isExist = false;
  330. for(let j = 0, jLen = theProj.children.length; j < jLen; j++){
  331. if(theProj.children[j].ID === theEng.ID){
  332. isExist = true;
  333. break;
  334. }
  335. }
  336. if(!isExist){
  337. theProj.children.push(theEng);
  338. }
  339. }
  340. }
  341. }
  342. }
  343. for(let i in _projs){
  344. rst.push(_projs[i]);
  345. }
  346. function buildProj(proj){
  347. proj.children = [];
  348. proj.unitPriceFiles = [];
  349. proj.feeRateFiles = [];
  350. }
  351. callback(request, response, 0, 'success', rst);
  352. }
  353. catch (error){
  354. callback(request, response, true, error, null);
  355. }
  356. },
  357. recGC: function(request, response){
  358. let userID = request.session.sessionUser.id;
  359. let data = JSON.parse(request.body.data);
  360. let nodes = data.nodes;
  361. ProjectsData.recGC(userID, nodes, function (err, msg, data) {
  362. callback(request, response, err, msg, data);
  363. });
  364. },
  365. delGC: async function(request, response){
  366. let data = JSON.parse(request.body.data);
  367. let delDatas = data.delDatas;
  368. let bulkProjs = [], bulkUFs = [], bulkFFs = [];
  369. try{
  370. for(let data of delDatas){
  371. if(data.updateType === 'Project'){
  372. bulkProjs.push({updateOne: {filter: {ID: data.ID}, update: {'deleteInfo.completeDeleted': true}}});
  373. }
  374. else if(data.updateType === fileType.unitPriceFile){
  375. bulkUFs.push({updateOne: {filter: {id: data.ID}, update: {'deleteInfo.completeDeleted': true}}});
  376. }
  377. else{
  378. bulkFFs.push({updateOne: {filter: {ID: data.ID}, update: {'deleteInfo.completeDeleted': true}}});
  379. }
  380. }
  381. if(bulkProjs.length > 0){
  382. await projectModel.bulkWrite(bulkProjs);
  383. }
  384. if(bulkUFs.length > 0){
  385. await unitPriceFileModel.bulkWrite(bulkUFs);
  386. }
  387. if(bulkFFs.length > 0){
  388. await feeRateFileModel.bulkWrite(bulkFFs);
  389. }
  390. callback(request, response, 0, 'success', null);
  391. } catch(err){
  392. callback(request, response, 1, err, null);
  393. }
  394. },
  395. moveProject:async function(req,res){
  396. let result={
  397. error:0
  398. };
  399. try {
  400. let data = req.body.data;
  401. let rdata= await pm_facade.moveProject(data);
  402. result.data= rdata;
  403. }catch (err){
  404. console.log(err);
  405. result.error=1;
  406. result.message = err.message;
  407. }
  408. res.json(result);
  409. },
  410. copyProjects:async function (req, res) {
  411. let result={
  412. error:0
  413. };
  414. try {
  415. let data = JSON.parse(req.body.data);
  416. result.data = await pm_facade.copyProject(req.session.sessionUser.id, req.session.sessionCompilation._id,data);
  417. }catch (err){
  418. console.log(err);
  419. result.error=1;
  420. result.message = err.message;
  421. }
  422. res.json(result);
  423. },
  424. projectShareInfo: async function(req, res){
  425. try{
  426. let data = JSON.parse(req.body.data);
  427. let shareInfo = await projectModel.findOne({ID: data.projectID, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]}, '-_id shareInfo');
  428. callback(req, res, 0, 'success', shareInfo);
  429. }
  430. catch (err){
  431. callback(req, res, 1, err, null);
  432. }
  433. },
  434. share: async function(req, res){
  435. try{
  436. let data = JSON.parse(req.body.data);
  437. //添加分享
  438. let shareData = {userID: data.userID, allowCopy: data.allowCopy, shareDate: moment(Date.now()).format('YYYY-MM-DD HH:mm:ss')};
  439. if(data.type === 'create'){
  440. await projectModel.update({ID: data.projectID, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]}, {$addToSet: {shareInfo: shareData}});
  441. }
  442. //取消分享
  443. else {
  444. await projectModel.update({ID: data.projectID, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]}, {$pull: {shareInfo: {userID: data.userID}}});
  445. }
  446. callback(req, res, 0, 'success', null);
  447. }
  448. catch (err){
  449. callback(req, res, 1, err, null);
  450. }
  451. },
  452. getShareProjects: async function (req, res) {
  453. try {
  454. let userID = req.session.sessionUser.id;
  455. let rst = {receive: [], share: []}//接收的、由我分享的
  456. let shareProjects = await projectModel.find({userID: userID,
  457. $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}], compilation: req.session.sessionCompilation._id, 'shareInfo.0': {$exists: true}});
  458. //项目类型为分享给别人
  459. let shareToUserIDs = [];
  460. for(let proj of shareProjects){
  461. proj._doc.shareType = 'shareTo';
  462. for(let shareToUser of proj.shareInfo){
  463. shareToUserIDs.push(shareToUser.userID);
  464. }
  465. }
  466. shareToUserIDs = Array.from(new Set(shareToUserIDs));
  467. let shareToObjIDs = [];
  468. for(let userID of shareToUserIDs){
  469. shareToObjIDs.push(mongoose.Types.ObjectId(userID));
  470. }
  471. let shareToUsers = await userModel.find({_id: {$in: shareToObjIDs}});
  472. for(let shareToUser of shareToUsers){
  473. for(let proj of shareProjects){
  474. for(let user of proj.shareInfo){
  475. if(user.userID === shareToUser._id.toString()){
  476. user._doc.company = shareToUser.company;
  477. user._doc.email = shareToUser.email;
  478. user._doc.name = shareToUser.real_name;
  479. user._doc.mobile = shareToUser.mobile;
  480. }
  481. }
  482. }
  483. }
  484. rst.share = shareProjects;
  485. let receiveProjects = await projectModel.find({
  486. $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}], compilation: req.session.sessionCompilation._id, 'shareInfo.userID': userID});
  487. //设置原项目用户信息
  488. if(receiveProjects.length > 0){
  489. let orgUserIDs = [];
  490. for(let proj of receiveProjects){
  491. orgUserIDs.push(proj.userID);
  492. }
  493. orgUserIDs = Array.from(new Set(orgUserIDs));
  494. let userObjIDs = [];
  495. for(let uID of orgUserIDs){
  496. userObjIDs.push(mongoose.Types.ObjectId(uID));
  497. }
  498. let orgUsersInfo = await userModel.find({_id: {$in : userObjIDs}});
  499. for(let proj of receiveProjects){
  500. //设置项目类型为来自别人分享
  501. proj._doc.shareType = 'receive';
  502. for(let userData of orgUsersInfo){
  503. if(proj.userID == userData._id.toString()){
  504. let userInfo = {name: userData.real_name, mobile: userData.mobile, company: userData.company, email: userData.email};
  505. proj._doc.userInfo = userInfo;
  506. }
  507. }
  508. }
  509. }
  510. rst.receive = receiveProjects;
  511. callback(req, res, 0, 'success', rst);
  512. }
  513. catch (err){
  514. callback(req, res, 1, err, null);
  515. }
  516. },
  517. getProjectsByQuery: async function (req, res) {
  518. try{
  519. let data = JSON.parse(req.body.data);
  520. let compilation = req.session.sessionCompilation._id;
  521. let query = data.query;
  522. query.compilation = compilation;
  523. console.log(`compilation===============================`);
  524. console.log(compilation);
  525. console.log(query);
  526. let options = data.options;
  527. let projects = await projectModel.find(query, options);
  528. callback(req, res, 0, 'success', projects);
  529. }
  530. catch (err){
  531. callback(req, res, 1, err, null);
  532. }
  533. },
  534. getSummaryInfo: async function(req, res){
  535. try{
  536. let data = JSON.parse(req.body.data);
  537. let summaryInfo = await pm_facade.getSummaryInfo(data.projectIDs);
  538. callback(req, res, 0, 'success', summaryInfo);
  539. }
  540. catch (err){
  541. callback(req, res, 1, err, null);
  542. }
  543. },
  544. };