pm_controller.js 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776
  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. console.log(err);
  314. callback(request, response, 1, err.message, null);
  315. }
  316. },
  317. // 获取单价文件列表
  318. getUnitFileList: async function(request, response) {
  319. let data = request.body.data;
  320. try {
  321. data = JSON.parse(data);
  322. let projectId = data.parentID !== undefined ? data.parentID : 0;
  323. if (isNaN(projectId) && projectId <= 0) {
  324. throw {msg: 'id数据有误!', err: 1};
  325. }
  326. /*// 获取对应建设项目下所有的单位工程id
  327. let idList = await ProjectsData.getTenderByProjectId(projectId);
  328. if (idList.length <= 0) {
  329. throw {msg: '不存在对应单位工程', err: 0};
  330. }*/
  331. // 获取对应的单价文件
  332. let unitPriceFileModel = new UnitPriceFileModel();
  333. let unitPriceFileData = await unitPriceFileModel.getDataByRootProject(projectId);
  334. if (unitPriceFileData === null) {
  335. throw {msg: '不存在对应单价文件', err: 0};
  336. }
  337. // 整理数据
  338. let unitPriceFileList = [];
  339. for (let unitPriceFile of unitPriceFileData) {
  340. let tmp = {
  341. name: unitPriceFile.name,
  342. id: unitPriceFile.id
  343. };
  344. unitPriceFileList.push(tmp);
  345. }
  346. callback(request, response, 0, '', unitPriceFileList);
  347. } catch (error) {
  348. console.log(error);
  349. let responseData = error.err === 1 ? null : [];
  350. callback(request, response, error.err, error.msg, responseData);
  351. }
  352. },
  353. getFeeRateFileList:async function(request, response) {
  354. let data = request.body.data;
  355. try {
  356. data = JSON.parse(data);
  357. let projectId = data.parentID !== undefined ? data.parentID : 0;
  358. if (isNaN(projectId) && projectId <= 0) {
  359. throw {msg: 'id数据有误!', err: 1};
  360. }
  361. // 获取对应建设项目下所有的单位工程id
  362. let feeRateFileList = await fee_rate_facade.getFeeRatesByProject(projectId);
  363. callback(request, response, 0, '',feeRateFileList );
  364. } catch (error) {
  365. console.log(error);
  366. let responseData = error.err === 1 ? null : [];
  367. callback(request, response, error.err, error.msg, responseData);
  368. }
  369. },
  370. getGC: async function(req, res) {
  371. const userID = req.session.sessionUser.id;
  372. const compilationId = req.session.sessionCompilation._id;
  373. try {
  374. const rst = [];
  375. const priceFilesTask = ProjectsData.getGCFiles(fileType.unitPriceFile, userID);
  376. const feeRateFilesTask = ProjectsData.getGCFiles(fileType.feeRateFile, userID);
  377. const tendersTask = ProjectsData.getGCFiles(projType.tender, userID);
  378. const [priceFiles, rateFiles, tenders] = await Promise.all([priceFilesTask, feeRateFilesTask, tendersTask]);
  379. // 建设项目
  380. let projectIDs = tenders.reduce((acc, cur) => {
  381. acc.push(cur.ParentID);
  382. return acc;
  383. }, []);
  384. projectIDs = [...new Set(projectIDs)];
  385. const projects = await ProjectsData.getProjectsByIds(userID, compilationId, projectIDs);
  386. projects.forEach(project => {
  387. const projectDoc = project._doc;
  388. const relTenders = tenders.filter(tender => tender.ParentID === projectDoc.ID);
  389. const unitPriceFiles = priceFiles.filter(file => relTenders.find(tender => tender.property.unitPriceFile.id === file.id));
  390. const feeRateFiles = rateFiles.filter(file => relTenders.find(tender => tender.property.feeFile.id === file.ID));
  391. projectDoc.children = relTenders;
  392. projectDoc.unitPriceFiles = unitPriceFiles;
  393. projectDoc.feeRateFiles = feeRateFiles;
  394. rst.push(projectDoc);
  395. });
  396. callback(req, res, 0, 'success', rst);
  397. } catch (err) {
  398. console.log(err);
  399. callback(req, res, true, err.message, null);
  400. }
  401. },
  402. getGCDatas: async function(request, response) {
  403. let userID = request.session.sessionUser.id;
  404. let compilatoinId = request.session.sessionCompilation._id;
  405. let rst = [];
  406. let _projs = Object.create(null), _engs = Object.create(null), prefix = 'ID_';
  407. try{
  408. let gc_unitPriceFiles = await ProjectsData.getGCFiles(fileType.unitPriceFile, userID);
  409. let gc_feeRateFiles = await ProjectsData.getGCFiles(fileType.feeRateFile, userID);
  410. let gc_tenderFiles = await ProjectsData.getGCFiles(projType.tender, userID);
  411. for(let i = 0, len = gc_unitPriceFiles.length; i < len; i++){
  412. let gc_uf = gc_unitPriceFiles[i];
  413. let theProj = _projs[prefix + gc_uf.root_project_id] || null;
  414. if(!theProj){
  415. let tempProj = await ProjectsData.getProjectsByIds(userID, compilatoinId, [gc_uf.root_project_id]);
  416. if(tempProj.length > 0 && tempProj[0].projType !== projType.folder){
  417. theProj = _projs[prefix + gc_uf.root_project_id] = tempProj[0]._doc;
  418. buildProj(theProj);
  419. }
  420. }
  421. if(theProj){
  422. theProj.unitPriceFiles.push(gc_uf);
  423. }
  424. }
  425. for(let i = 0, len = gc_feeRateFiles.length; i < len; i++){
  426. let gc_ff = gc_feeRateFiles[i];
  427. let theProj = _projs[prefix + gc_ff.rootProjectID] || null;
  428. if(!theProj){
  429. let tempProj = await ProjectsData.getProjectsByIds(userID, compilatoinId, [gc_ff.rootProjectID]);
  430. if(tempProj.length > 0 && tempProj[0].projType !== projType.folder){
  431. theProj = _projs[prefix + gc_ff.rootProjectID] = tempProj[0]._doc;
  432. buildProj(theProj);
  433. }
  434. }
  435. if(theProj) {
  436. theProj.feeRateFiles.push(gc_ff);
  437. }
  438. }
  439. if(gc_tenderFiles.length > 0){
  440. for(let i = 0, len = gc_tenderFiles.length; i < len; i++){
  441. let gc_t = gc_tenderFiles[i];
  442. let theProj = _projs[prefix + gc_t.ParentID] || null;
  443. if(!theProj){
  444. let tempProjs = await ProjectsData.getProjectsByIds(userID, compilatoinId, [gc_t.ParentID]);
  445. if(tempProjs.length > 0 && tempProjs[0].projType === projType.project){
  446. theProj = _projs[prefix + gc_t.ParentID] = tempProjs[0]._doc;
  447. buildProj(theProj);
  448. }
  449. }
  450. if(theProj) {
  451. theProj.children.push(gc_t);
  452. }
  453. }
  454. }
  455. for(let i in _projs){
  456. rst.push(_projs[i]);
  457. }
  458. function buildProj(proj){
  459. proj.children = [];
  460. proj.unitPriceFiles = [];
  461. proj.feeRateFiles = [];
  462. }
  463. callback(request, response, 0, 'success', rst);
  464. }
  465. catch (error){
  466. callback(request, response, true, error, null);
  467. }
  468. },
  469. recGC: function(request, response){
  470. let userID = request.session.sessionUser.id,
  471. compilationId = request.session.sessionCompilation._id;
  472. let data = JSON.parse(request.body.data);
  473. let nodes = data.nodes;
  474. ProjectsData.recGC(userID, compilationId, nodes, function (err, msg, data) {
  475. callback(request, response, err, msg, data);
  476. });
  477. },
  478. delGC: async function(request, response){
  479. let data = JSON.parse(request.body.data);
  480. let delDatas = data.delDatas;
  481. let bulkProjs = [], bulkUFs = [], bulkFFs = [];
  482. try{
  483. for(let data of delDatas){
  484. if(data.updateType === 'Project'){
  485. bulkProjs.push({updateOne: {filter: {ID: data.ID}, update: {'deleteInfo.completeDeleted': true}}});
  486. }
  487. else if(data.updateType === fileType.unitPriceFile){
  488. bulkUFs.push({updateOne: {filter: {id: data.ID}, update: {'deleteInfo.completeDeleted': true}}});
  489. }
  490. else{
  491. bulkFFs.push({updateOne: {filter: {ID: data.ID}, update: {'deleteInfo.completeDeleted': true}}});
  492. }
  493. }
  494. if(bulkProjs.length > 0){
  495. await projectModel.bulkWrite(bulkProjs);
  496. }
  497. if(bulkUFs.length > 0){
  498. await unitPriceFileModel.bulkWrite(bulkUFs);
  499. }
  500. if(bulkFFs.length > 0){
  501. await feeRateFileModel.bulkWrite(bulkFFs);
  502. }
  503. callback(request, response, 0, 'success', null);
  504. } catch(err){
  505. callback(request, response, 1, err, null);
  506. }
  507. },
  508. moveProject:async function(req,res){
  509. let result={
  510. error:0
  511. };
  512. try {
  513. let data = req.body.data;
  514. let rdata= await pm_facade.moveProject(data);
  515. result.data= rdata;
  516. }catch (err){
  517. console.log(err);
  518. result.error=1;
  519. result.message = err.message;
  520. }
  521. res.json(result);
  522. },
  523. copyProjects:async function (req, res) {
  524. let result={
  525. error:0
  526. };
  527. try {
  528. let data = {dataString:req.body.data,userID:req.session.sessionUser.id,compilationID:req.session.sessionCompilation._id};
  529. result = await redirectToImportServer(data,"copyProject",req);
  530. }catch (err){
  531. console.log(err);
  532. result.error=1;
  533. result.message = err.message;
  534. }
  535. res.json(result);
  536. },
  537. projectShareInfo: async function(req, res){
  538. try{
  539. let data = JSON.parse(req.body.data);
  540. let shareInfo = await projectModel.findOne({ID: data.projectID, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]}, '-_id shareInfo');
  541. callback(req, res, 0, 'success', shareInfo);
  542. }
  543. catch (err){
  544. callback(req, res, 1, err, null);
  545. }
  546. },
  547. share: async function(req, res){
  548. try{
  549. let data = JSON.parse(req.body.data);
  550. let shareDate = moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'),
  551. shareUserIDs = [];
  552. for (let data of data.shareData) {
  553. shareUserIDs.push(data.userID);
  554. data.shareDate = shareDate;
  555. }
  556. //添加分享
  557. if(data.type === 'create'){
  558. //新增
  559. for (let sData of data.shareData) {
  560. await projectModel.update({ID: data.projectID, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]}, {$addToSet: {shareInfo: sData}});
  561. }
  562. } else if (data.type === 'update') {
  563. await projectModel.update({ID: data.projectID, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]}, {$set: {shareInfo: data.shareData}});
  564. }
  565. //取消分享
  566. else {
  567. await projectModel.update({ID: data.projectID, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]}, {$pull: {shareInfo: {userID: {$in: shareUserIDs}}}});
  568. }
  569. callback(req, res, 0, 'success', data.shareData);
  570. }
  571. catch (err){
  572. callback(req, res, 1, err, null);
  573. }
  574. },
  575. receiveProjects: async function(req, res) {
  576. try {
  577. let rst = {grouped: [], ungrouped: [], summaryInfo: null};
  578. let userID = req.session.sessionUser.id;
  579. let receiveProjects = await projectModel.find({
  580. $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}], compilation: req.session.sessionCompilation._id, 'shareInfo.userID': userID}, '-_id');
  581. //设置原项目用户信息
  582. if(receiveProjects.length > 0){
  583. let orgUserIDs = [];
  584. for(let proj of receiveProjects){
  585. orgUserIDs.push(proj.userID);
  586. if (proj.projType === projType.tender) {
  587. //设置工程专业
  588. proj._doc.feeStandardName = proj.property.feeStandardName || '';
  589. //设置项目类别
  590. proj._doc.valuationType = proj.property.valuationType === 'bill' ? '预算' : '工程清单';
  591. }
  592. delete proj._doc.property;
  593. }
  594. orgUserIDs = Array.from(new Set(orgUserIDs));
  595. let userObjIDs = [];
  596. for(let uID of orgUserIDs){
  597. userObjIDs.push(mongoose.Types.ObjectId(uID));
  598. }
  599. let orgUsersInfo = await userModel.find({_id: {$in : userObjIDs}});
  600. //建设项目
  601. let consProjIDs = [],
  602. ungroupedTenders = [];
  603. for(let proj of receiveProjects){
  604. if (proj.projType === projType.project) {
  605. consProjIDs.push(proj.ID);
  606. }
  607. //获取分享项目子项
  608. if (proj.projType !== projType.tender) {
  609. proj._doc.children = await pm_facade.getPosterityProjects([proj.ID]);
  610. for (let projC of proj._doc.children) {
  611. if (projC.projType === projType.project) {
  612. consProjIDs.push(projC.ID);
  613. } else if (projC.projType === projType.tender) {
  614. //设置工程专业
  615. projC._doc.feeStandardName = projC.property.feeStandardName || '';
  616. }
  617. delete projC._doc.property;
  618. }
  619. } else {//未分类的单位工程不进行汇总,只取价格信息
  620. ungroupedTenders.push(proj._doc);
  621. }
  622. //设置分组,单位工程及单项工程分到未分组那
  623. if (proj.projType === projType.tender || proj.projType === projType.engineering) {
  624. rst.ungrouped.push(proj);
  625. } else {
  626. rst.grouped.push(proj);
  627. }
  628. //设置项目类型为来自别人分享
  629. proj._doc.shareType = 'receive';
  630. for(let userData of orgUsersInfo){
  631. if(proj.userID == userData._id.toString()){
  632. let userInfo = {name: userData.real_name, mobile: userData.mobile, company: userData.company, email: userData.email};
  633. proj._doc.userInfo = userInfo;
  634. }
  635. }
  636. }
  637. consProjIDs = Array.from(new Set(consProjIDs));
  638. let summaryInfo = await pm_facade.getSummaryInfo(consProjIDs);
  639. let tendersFeeInfo = await pm_facade.getTendersFeeInfo(ungroupedTenders);
  640. rst.summaryInfo = {grouped: summaryInfo, ungrouped: tendersFeeInfo};
  641. }
  642. callback(req, res, 0, 'success', rst);
  643. }
  644. catch (err){
  645. console.log(err);
  646. callback(req, res, 1, err, null);
  647. }
  648. },
  649. getProjectsByQuery: async function (req, res) {
  650. try{
  651. let data = JSON.parse(req.body.data);
  652. let compilation = req.session.sessionCompilation._id;
  653. let query = data.query;
  654. query.compilation = compilation;
  655. let options = data.options;
  656. let projects = await projectModel.find(query, options);
  657. callback(req, res, 0, 'success', projects);
  658. }
  659. catch (err){
  660. callback(req, res, 1, err, null);
  661. }
  662. },
  663. getSummaryInfo: async function(req, res){
  664. try{
  665. let data = JSON.parse(req.body.data);
  666. let summaryInfo = await pm_facade.getSummaryInfo(data.projectIDs);
  667. callback(req, res, 0, 'success', summaryInfo);
  668. }
  669. catch (err){
  670. callback(req, res, 1, err, null);
  671. }
  672. },
  673. changeFile:async function(req,res){
  674. try{
  675. let data = JSON.parse(req.body.data);
  676. console.log(data);
  677. await pm_facade.changeFile(data.projects,data.user_id,data.fileID,data.name,data.from,data.type);
  678. callback(req, res, 0, 'success', []);
  679. }
  680. catch (err){
  681. console.log(err);
  682. callback(req, res, 1, err, null);
  683. }
  684. },
  685. exportProject:async function(req,res){
  686. let result={
  687. error:0
  688. };
  689. try {
  690. let data = {dataString:req.body.data,userID:req.session.sessionUser.id};
  691. result = await redirectToImportServer(data,"exportProject",req);
  692. }catch (err){
  693. console.log(err);
  694. result.error=1;
  695. result.message = err.message;
  696. }
  697. res.json(result);
  698. },
  699. importProject:async function(req,res){
  700. let data = JSON.parse(req.body.data);
  701. let result={
  702. error:0
  703. };
  704. try {
  705. data.session = req.session;
  706. result = await redirectToImportServer(data,"importProject",req);
  707. }catch (err){
  708. console.log(err);
  709. result.error=1;
  710. result.message = err.message;
  711. }
  712. res.json(result);
  713. },
  714. importProcessChecking:async function (req,res) {
  715. let result={
  716. error:0
  717. };
  718. try{
  719. let data = JSON.parse(req.body.data);
  720. result.data = await pm_facade.importProcessChecking(data);
  721. } catch (err){
  722. console.log(err);
  723. result.error=1;
  724. result.message = err.message;
  725. }
  726. res.json(result);
  727. },
  728. getUploadToken:function (req,res) {
  729. let result={
  730. error:0
  731. };
  732. try {
  733. result =pm_facade.uploadToken();
  734. }catch (err){
  735. console.log(err);
  736. result.error=1;
  737. result.message = err.message;
  738. }
  739. res.json(result);
  740. }
  741. };
  742. async function redirectToImportServer(data,action,req) {
  743. let importURL = config.getImportURL(process.env.NODE_ENV,req.headers.origin);
  744. let options = {
  745. method: 'POST',
  746. uri: `http://${importURL}/import/${action}`,
  747. body: data,
  748. timeout:220000,
  749. json: true
  750. };
  751. console.log("post import data to:"+options.uri);
  752. return await rp.post(options);
  753. }