pm_controller.js 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045
  1. /**
  2. * Created by Mai on 2017/1/18.
  3. */
  4. const UnitPriceFileModel = require("../../glj/models/unit_price_file_model");
  5. const moment = require('moment');
  6. const CompilationModel = require("../../users/models/compilation_model");
  7. const UserModel = require("../../users/models/user_model");
  8. const userModelObj = new UserModel();
  9. let mongoose = require('mongoose');
  10. let ProjectsData = require('../models/project_model').project;
  11. let labourCoe = require('../../main/facade/labour_coe_facade');
  12. let projType = require('../models/project_model').projType;
  13. let fileType = require('../models/project_model').fileType;
  14. const engineering = require("../../common/const/engineering");
  15. let EngineeringLibModel = require("../../users/models/engineering_lib_model");
  16. let fee_rate_facade = require("../../fee_rates/facade/fee_rates_facade");
  17. let billsModel = require('../../main/models/bills').model;
  18. let rationsModel = require('../../main/models/ration').model;
  19. let projectModel = mongoose.model('projects');
  20. let unitPriceFileModel = mongoose.model('unit_price_file');
  21. let feeRateFileModel = mongoose.model('fee_rate_file');
  22. let asyncTool = require('async');
  23. let pm_facade = require('../facade/pm_facade');
  24. const userModel = mongoose.model('user');
  25. let config = require("../../../config/config.js");
  26. const optionModel = mongoose.model('options');
  27. const stdBillsGuidanceLibModel = mongoose.model('std_billsGuidance_lib');
  28. const fs = require('fs');
  29. const _ = require('lodash');
  30. const SectionTreeDao = require('../../complementary_ration_lib/models/sectionTreeModel');
  31. const uuidV1 = require('uuid/v1');
  32. let sectionTreeDao = new SectionTreeDao();
  33. let consts = require('../../main/models/project_consts');
  34. let rp = require('request-promise');
  35. const commonUtil = require('../../../public/common_util');
  36. //统一回调函数
  37. let callback = function (req, res, err, message, data) {
  38. res.json({ error: err, message: message, data: data });
  39. };
  40. module.exports = {
  41. redirectToImportServer,
  42. checkRight: function (req, res) {
  43. if (typeof req.body.data === 'object') {
  44. req.body.data = JSON.stringify(req.body.data);
  45. }
  46. let data = JSON.parse(req.body.data);
  47. if (data.user_id) {
  48. return data.user_id === req.session.sessionUser.id;
  49. } else {
  50. return false;
  51. }
  52. },
  53. checkProjectRight: function (userId, projectId, callback) {
  54. ProjectsData.getProject(projectId).then(async function (result) {
  55. /**
  56. * result._doc.userID(Number): MongoDB
  57. * userId(String): Session.userID
  58. */
  59. let shareInfo = null;
  60. let isOpenShareProject = false;
  61. //判断是否是打开分享的项目,分享项目shareInfo不为null
  62. if (userId !== result.userID) {
  63. shareInfo = await pm_facade.getShareInfo(userId, result.ID);
  64. isOpenShareProject = true;
  65. }
  66. if ((userId === result.userID || shareInfo) && result._doc.projType === projType.tender) {
  67. const allowCooperate = (shareInfo || {}).allowCooperate;
  68. callback(true, result, isOpenShareProject, allowCooperate);
  69. } else {
  70. callback(false);
  71. }
  72. }).catch(function (err) {
  73. callback(false);
  74. });
  75. },
  76. getProjects: async function (req, res) {
  77. await ProjectsData.getUserProjects(req.session.sessionUser.id, req.session.sessionCompilation._id, function(err, message, projects){
  78. if (projects) {
  79. callback(req, res, err, message, projects);
  80. } else {
  81. callback(req, res, err, message, null);
  82. }
  83. });
  84. },
  85. updateProjects: async function (req, res) {
  86. let data = JSON.parse(req.body.data);
  87. try {
  88. await ProjectsData.updateUserProjects(req.session.sessionUser.id, req.session.sessionCompilation._id, req.session.sessionCompilation, data.updateData, function (err, message, data) {
  89. if (err === 0) {
  90. callback(req, res, err, message, data);
  91. } else {
  92. callback(req, res, err, message, null);
  93. }
  94. });
  95. } catch (err) {
  96. console.log(err);
  97. callback(req, res, 1, String(err), null);
  98. }
  99. },
  100. // CSL, 2017-12-14 该方法用于项目属性:提交保存混合型数据,这些数据来自不同的表,包括projects.property、ration、bills、labour_coes.
  101. updateMixDatas: async function (req, res) {
  102. let datas = JSON.parse(req.body.data).mixDataArr;
  103. let functions = [];
  104. function updateFunc(model, cod, doc) {
  105. return function (cb) {
  106. model.update(cod, doc, cb);
  107. }
  108. };
  109. function updateLC() {
  110. return function (cb) {
  111. datas.labourCoes.updateData.projectID = datas.projectID;
  112. labourCoe.save(datas.labourCoes.updateData, cb);
  113. }
  114. };
  115. // 项目属性
  116. if (Object.keys(datas.properties).length > 0) {
  117. //基本信息特殊处理,更新建设项目
  118. if (datas.properties['property.basicInformation']) {
  119. let constructionProject = await pm_facade.getConstructionProject(datas.projectID);
  120. if (constructionProject) {
  121. functions.push(updateFunc(projectModel, { ID: constructionProject.ID }, { 'property.basicInformation': datas.properties['property.basicInformation'] }));
  122. }
  123. delete datas.properties['property.basicInformation'];
  124. }
  125. functions.push(updateFunc(projectModel, { ID: datas.projectID }, datas.properties));
  126. };
  127. //选项
  128. if (datas.options && datas.options.updateData) {
  129. functions.push(updateFunc(optionModel, { user_id: req.session.sessionUser.id, compilation_id: req.session.sessionCompilation._id }, { 'options.GENERALOPTS': datas.options.updateData }));
  130. }
  131. // 人工系数
  132. if (datas.labourCoes && datas.labourCoes.updateData) {
  133. functions.push(updateLC());
  134. };
  135. // 清单:每文档doc只存储一条清单,每条清单都必须定位一次文档,无法合并处理
  136. if (datas.bills && datas.bills.length > 0) {
  137. for (let bill of datas.bills) {
  138. functions.push(updateFunc(billsModel, { projectID: datas.projectID, ID: bill.ID, deleteInfo: null }, bill));
  139. };
  140. };
  141. // 定额:每文档doc只存储一条定额,每条定额都必须定位一次文档,无法合并处理
  142. if (datas.rations && datas.rations.length > 0) {
  143. for (let ration of datas.rations) {
  144. functions.push(updateFunc(rationsModel, { projectID: datas.projectID, ID: ration.ID, deleteInfo: null }, ration));
  145. };
  146. };
  147. asyncTool.parallel(functions, function (err, result) {
  148. {
  149. if (!err) {
  150. res.json({ error: 0, message: err, data: result });
  151. } else {
  152. res.json({ error: 1, message: err, data: null });
  153. }
  154. }
  155. });
  156. },
  157. updateFiles: async function (req, res) {
  158. let data = JSON.parse(req.body.data);
  159. let updateDatas = data.updateDatas;
  160. await ProjectsData.udpateUserFiles(req.session.sessionUser.id, updateDatas, function (err, message, data) {
  161. callback(req, res, err, message, data);
  162. });
  163. },
  164. defaultSettings: async function (req, res) {
  165. try {
  166. let data = JSON.parse(req.body.data);
  167. let projectID = data.projectID;
  168. let defaultSettingSc = await ProjectsData.defaultSettings(req.session.sessionUser.id, req.session.sessionCompilation, projectID);
  169. if (!defaultSettingSc) {
  170. throw '恢复失败';
  171. }
  172. res.json({ error: 0, message: '恢复成功', data: null });
  173. }
  174. catch (error) {
  175. console.log(error);
  176. res.json({ error: 1, message: error, data: null });
  177. }
  178. },
  179. /* copyProjects: function (req, res) {
  180. let data = JSON.parse(req.body.data);
  181. ProjectsData.copyUserProjects(req.session.sessionUser.id, req.session.sessionCompilation._id, data.updateData, function (err, message, data) {
  182. if (err === 0) {
  183. callback(req, res, err, message, data);
  184. } else {
  185. callback(req, res, err, message, null);
  186. }
  187. });
  188. },*/
  189. rename: function (req, res) {
  190. let data = JSON.parse(req.body.data);
  191. ProjectsData.rename(req.session.sessionUser.id, req.session.sessionCompilation._id, data, function (err, message) {
  192. callback(req, res, err, message, null);
  193. });
  194. },
  195. //project getData接口
  196. getData: function (projectID, callback, isReport, userID) {
  197. projectModel.findOne({ $or: [{ deleteInfo: null }, { 'deleteInfo.deleted': false }], ID: projectID }, '-_id').then(async function (project) {
  198. if (!project) {
  199. callback('', consts.projectConst.PROJECT_INFO, {});
  200. }
  201. let engineeringLibModel = new EngineeringLibModel();
  202. let engineeringInfo = project !== null && project.property.engineering_id !== undefined ?
  203. await engineeringLibModel.getEngineering(project.property.engineering_id) : null;
  204. let projInfo = project._doc;
  205. if (engineeringInfo !== null) {
  206. if (engineeringInfo.billsGuidance_lib) {
  207. for (let billsGuidanceLib of engineeringInfo.billsGuidance_lib) {
  208. let stdBillsGuidanceLib = await stdBillsGuidanceLibModel.findOne({ ID: billsGuidanceLib.id });
  209. if (stdBillsGuidanceLib) {
  210. billsGuidanceLib.type = stdBillsGuidanceLib.type ? stdBillsGuidanceLib.type : 1;
  211. }
  212. }
  213. }
  214. projInfo.engineeringInfo = engineeringInfo;
  215. }
  216. // 获取建设项目相关信息
  217. const constructionProject = await pm_facade.getConstructionProject(projectID);
  218. if (constructionProject) {
  219. projInfo.property.basicInformation = constructionProject.property && constructionProject.property.basicInformation || null;
  220. projInfo.property.projectValuationType = constructionProject.property && constructionProject.property.valuationType || null;
  221. }
  222. //获取单位工程完整目录结构
  223. let fullPath = await pm_facade.getFullPath(projectID);
  224. projInfo.fullPath = fullPath;
  225. // 获取分享的tip
  226. projInfo.shareTip = await pm_facade.getShareTip(projectID, 2);
  227. // 获取分享状态
  228. if (typeof userID === 'string') {
  229. projInfo.shareState = await pm_facade.getShareState(projectID, userID);
  230. }
  231. // 获取项目所属用户
  232. projInfo.owner = await userModel.findOne({_id: mongoose.Types.ObjectId(project.userID)}, 'real_name mobile').lean();
  233. projInfo.opener = await userModel.findOne({_id: mongoose.Types.ObjectId(userID)}, 'real_name mobile').lean();
  234. callback('', consts.projectConst.PROJECT_INFO, project);
  235. }, function (err) {
  236. callback(err, consts.projectConst.PROJECT_INFO, {});
  237. });
  238. },
  239. getProject: function (req, res) {
  240. let data = JSON.parse(req.body.data);
  241. let projectID = data.proj_id;
  242. ProjectsData.getUserProject(req.session.sessionUser.id, data.proj_id, async function (err, message, data) {
  243. if (err === 0) {
  244. let engineeringLibModel = new EngineeringLibModel();
  245. let engineeringInfo = data !== null && data.property.engineering_id !== undefined ?
  246. await engineeringLibModel.getEngineering(data.property.engineering_id) : null;
  247. let strData = JSON.stringify(data);
  248. let projInfo = JSON.parse(strData);
  249. if (engineeringInfo !== null) {
  250. if (engineeringInfo.billsGuidance_lib) {
  251. for (let billsGuidanceLib of engineeringInfo.billsGuidance_lib) {
  252. let stdBillsGuidanceLib = await stdBillsGuidanceLibModel.findOne({ ID: billsGuidanceLib.id });
  253. if (stdBillsGuidanceLib) {
  254. billsGuidanceLib.type = stdBillsGuidanceLib.type ? stdBillsGuidanceLib.type : 1;
  255. }
  256. }
  257. }
  258. projInfo.engineeringInfo = engineeringInfo;
  259. }
  260. //读取建设项目的基本信息
  261. let basicInfo = await ProjectsData.getBasicInfo(projectID);
  262. if(basicInfo !== null){
  263. projInfo.property.basicInformation = basicInfo;
  264. }
  265. //获取单位工程完整目录结构
  266. let fullPath = await pm_facade.getFullPath(projectID);
  267. projInfo.fullPath = fullPath;
  268. callback(req, res, err, message, projInfo);
  269. } else {
  270. callback(req, res, err, message, null);
  271. }
  272. });
  273. },
  274. beforeOpenProject: function (req, res) {
  275. let data = JSON.parse(req.body.data);
  276. ProjectsData.beforeOpenProject(req.session.sessionUser.id, data.proj_id, data.updateData, function (err, message, data) {
  277. callback(req, res, err, message, data);
  278. });
  279. },
  280. getNewProjectID: function (req, res) {
  281. let data = JSON.parse(req.body.data);
  282. ProjectsData.getNewProjectID(data.count, function (err, message, data) {
  283. callback(req, res, err, message, data);
  284. });
  285. },
  286. // 项目管理首页
  287. index: async function (request, response) {
  288. //await pm_facade.prepareShareList();
  289. // 获取编办信息
  290. let sessionCompilation = request.session.sessionCompilation;
  291. if (sessionCompilation === undefined || sessionCompilation === null) {
  292. return response.redirect('/logout');
  293. }
  294. let compilationModel = new CompilationModel();
  295. //更新编办信息
  296. let compilationData = await compilationModel.getCompilationById(sessionCompilation._id);
  297. request.session.sessionCompilation = compilationData;
  298. sessionCompilation = request.session.sessionCompilation;
  299. //更新用户的使用过的费用定额列表
  300. let isFirst = await pm_facade.isFirst(request.session.sessionUser.id, compilationData._id.toString());
  301. // 清单计价
  302. let billValuation = sessionCompilation.bill_valuation !== undefined ?
  303. sessionCompilation.bill_valuation : [];
  304. // 获取标准库数据
  305. let engineeringLibModel = new EngineeringLibModel();
  306. billValuation = await engineeringLibModel.getLib(billValuation);
  307. // 定额计价
  308. let rationValuation = sessionCompilation.ration_valuation !== undefined ?
  309. sessionCompilation.ration_valuation : [];
  310. rationValuation = await engineeringLibModel.getLib(rationValuation);
  311. let absoluteUrl = compilationData.overWriteUrl ? request.app.locals.rootDir + compilationData.overWriteUrl : request.app.locals.rootDir;
  312. let overWriteUrl = fs.existsSync(absoluteUrl) && fs.statSync(absoluteUrl).isFile() ? compilationData.overWriteUrl : null;
  313. //欢迎页显示控制
  314. let [isShow,context,showTime] = await pm_facade.getWelcomeInfo(sessionCompilation._id,request.session.sessionUser,request.session.compilationVersion.includes('学习'));
  315. const unreadShareList = await pm_facade.getUnreadShareListByCompilation(request.session.sessionUser.id, sessionCompilation._id);
  316. let renderData = {
  317. unreadShareList: JSON.stringify(unreadShareList),
  318. isFirst: isFirst,
  319. isShow:isShow,
  320. context:context,
  321. showTime:showTime,
  322. userAccount: request.session.userAccount,
  323. userID: request.session.sessionUser.id,
  324. compilationData: JSON.stringify(sessionCompilation),
  325. overWriteUrl: overWriteUrl,
  326. billValuation: JSON.stringify(billValuation),
  327. rationValuation: JSON.stringify(rationValuation),
  328. engineeringList: JSON.stringify(engineering.List),
  329. compilationName: sessionCompilation.name,
  330. versionName: request.session.compilationVersion,
  331. socketPort:config[process.env.NODE_ENV].socketPort?config[process.env.NODE_ENV].socketPort:5500,
  332. LicenseKey:config.getLicenseKey(process.env.NODE_ENV),
  333. title:config[process.env.NODE_ENV].title?config[process.env.NODE_ENV].title:"纵横公路养护云造价"
  334. };
  335. response.render('building_saas/pm/html/project-management.html', renderData);
  336. },
  337. //第一次进入该费用定额时准备的初始数据
  338. prepareInitialData: async function (request, response) {
  339. try {
  340. const data = {
  341. userID: request.session.sessionUser.id,
  342. compilationID: request.session.sessionCompilation._id,
  343. example: request.session.sessionCompilation.example
  344. };
  345. await redirectToImportServer(data, 'prepareInitialData', request);
  346. callback(request, response, 0, 'success', null);
  347. } catch (err) {
  348. console.log(err);
  349. callback(request, response, 1, err.toString(), null);
  350. }
  351. },
  352. // 获取单价文件列表
  353. getUnitFileList: 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 idList = await ProjectsData.getTenderByProjectId(projectId);
  363. if (idList.length <= 0) {
  364. throw {msg: '不存在对应单位工程', err: 0};
  365. }*/
  366. // 获取对应的单价文件
  367. let unitPriceFileModel = new UnitPriceFileModel();
  368. let unitPriceFileData = await unitPriceFileModel.getDataByRootProject(projectId);
  369. if (unitPriceFileData === null) {
  370. throw { msg: '不存在对应单价文件', err: 0 };
  371. }
  372. // 整理数据
  373. let unitPriceFileList = [];
  374. for (let unitPriceFile of unitPriceFileData) {
  375. let tmp = {
  376. name: unitPriceFile.name,
  377. id: unitPriceFile.id
  378. };
  379. unitPriceFileList.push(tmp);
  380. }
  381. callback(request, response, 0, '', unitPriceFileList);
  382. } catch (error) {
  383. console.log(error);
  384. let responseData = error.err === 1 ? null : [];
  385. callback(request, response, error.err, error.msg, responseData);
  386. }
  387. },
  388. getFeeRateFileList: async function (request, response) {
  389. let data = request.body.data;
  390. try {
  391. data = JSON.parse(data);
  392. let projectId = data.parentID !== undefined ? data.parentID : 0;
  393. if (isNaN(projectId) && projectId <= 0) {
  394. throw { msg: 'id数据有误!', err: 1 };
  395. }
  396. // 获取对应建设项目下所有的单位工程id
  397. let feeRateFileList = await fee_rate_facade.getFeeRatesByProject(projectId);
  398. callback(request, response, 0, '', feeRateFileList);
  399. } catch (error) {
  400. console.log(error);
  401. let responseData = error.err === 1 ? null : [];
  402. callback(request, response, error.err, error.msg, responseData);
  403. }
  404. },
  405. getGC: async function(req, res) {
  406. const userID = req.session.sessionUser.id;
  407. const compilationId = req.session.sessionCompilation._id;
  408. try {
  409. const rst = [];
  410. const priceFilesTask = ProjectsData.getGCFiles(fileType.unitPriceFile, userID);
  411. const feeRateFilesTask = ProjectsData.getGCFiles(fileType.feeRateFile, userID);
  412. const tendersTask = ProjectsData.getGCFiles(projType.tender, userID);
  413. const [priceFiles, rateFiles, tenders] = await Promise.all([priceFilesTask, feeRateFilesTask, tendersTask]);
  414. // 建设项目
  415. let projectIDs = tenders.reduce((acc, cur) => {
  416. acc.push(cur.ParentID);
  417. return acc;
  418. }, []);
  419. projectIDs = [...new Set(projectIDs)];
  420. const projects = await ProjectsData.getProjectsByIds(userID, compilationId, projectIDs);
  421. projects.forEach(project => {
  422. const projectDoc = project._doc;
  423. const relTenders = tenders.filter(tender => tender.ParentID === projectDoc.ID);
  424. const unitPriceFiles = priceFiles.filter(file => relTenders.find(tender => tender.property.unitPriceFile.id === file.id));
  425. const feeRateFiles = rateFiles.filter(file => relTenders.find(tender => tender.property.feeFile.id === file.ID));
  426. projectDoc.children = relTenders;
  427. projectDoc.unitPriceFiles = unitPriceFiles;
  428. projectDoc.feeRateFiles = feeRateFiles;
  429. rst.push(projectDoc);
  430. });
  431. callback(req, res, 0, 'success', rst);
  432. } catch (err) {
  433. console.log(err);
  434. callback(req, res, true, err.message, null);
  435. }
  436. },
  437. getGCDatas: async function (request, response) {
  438. let userID = request.session.sessionUser.id;
  439. let compilatoinId = request.session.sessionCompilation._id;
  440. let rst = [];
  441. let _projs = Object.create(null), _engs = Object.create(null), prefix = 'ID_';
  442. try {
  443. let gc_unitPriceFiles = await ProjectsData.getGCFiles(fileType.unitPriceFile, userID);
  444. let gc_feeRateFiles = await ProjectsData.getGCFiles(fileType.feeRateFile, userID);
  445. let gc_tenderFiles = await ProjectsData.getGCFiles(projType.tender, userID);
  446. for (let i = 0, len = gc_unitPriceFiles.length; i < len; i++) {
  447. let gc_uf = gc_unitPriceFiles[i];
  448. let theProj = _projs[prefix + gc_uf.root_project_id] || null;
  449. if (!theProj) {
  450. let tempProj = await ProjectsData.getProjectsByIds(userID, compilatoinId, [gc_uf.root_project_id]);
  451. if (tempProj.length > 0 && tempProj[0].projType !== projType.folder) {
  452. theProj = _projs[prefix + gc_uf.root_project_id] = tempProj[0]._doc;
  453. buildProj(theProj);
  454. }
  455. }
  456. if (theProj) {
  457. theProj.unitPriceFiles.push(gc_uf);
  458. }
  459. }
  460. for (let i = 0, len = gc_feeRateFiles.length; i < len; i++) {
  461. let gc_ff = gc_feeRateFiles[i];
  462. let theProj = _projs[prefix + gc_ff.rootProjectID] || null;
  463. if (!theProj) {
  464. let tempProj = await ProjectsData.getProjectsByIds(userID, compilatoinId, [gc_ff.rootProjectID]);
  465. if (tempProj.length > 0 && tempProj[0].projType !== projType.folder) {
  466. theProj = _projs[prefix + gc_ff.rootProjectID] = tempProj[0]._doc;
  467. buildProj(theProj);
  468. }
  469. }
  470. if (theProj) {
  471. theProj.feeRateFiles.push(gc_ff);
  472. }
  473. }
  474. if (gc_tenderFiles.length > 0) {
  475. for (let i = 0, len = gc_tenderFiles.length; i < len; i++) {
  476. let gc_t = gc_tenderFiles[i];
  477. let theProj = _projs[prefix + gc_t.ParentID] || null;
  478. if(!theProj){
  479. let tempProjs = await ProjectsData.getProjectsByIds(userID, compilatoinId, [gc_t.ParentID]);
  480. if(tempProjs.length > 0 && tempProjs[0].projType === projType.project){
  481. theProj = _projs[prefix + gc_t.ParentID] = tempProjs[0]._doc;
  482. buildProj(theProj);
  483. }
  484. }
  485. if(theProj) {
  486. theProj.children.push(gc_t);
  487. }
  488. }
  489. }
  490. for (let i in _projs) {
  491. rst.push(_projs[i]);
  492. }
  493. function buildProj(proj) {
  494. proj.children = [];
  495. proj.unitPriceFiles = [];
  496. proj.feeRateFiles = [];
  497. }
  498. callback(request, response, 0, 'success', rst);
  499. }
  500. catch (error) {
  501. callback(request, response, true, error, null);
  502. }
  503. },
  504. recGC: function (request, response) {
  505. let userID = request.session.sessionUser.id,
  506. compilationId = request.session.sessionCompilation._id;
  507. let data = JSON.parse(request.body.data);
  508. let nodes = data.nodes;
  509. ProjectsData.recGC(userID, compilationId, nodes, function (err, msg, data) {
  510. callback(request, response, err, msg, data);
  511. });
  512. },
  513. delGC: async function (request, response) {
  514. let data = JSON.parse(request.body.data);
  515. let delDatas = data.delDatas;
  516. let bulkProjs = [], bulkUFs = [], bulkFFs = [];
  517. try {
  518. for (let data of delDatas) {
  519. if (data.updateType === 'Project') {
  520. bulkProjs.push({ updateOne: { filter: { ID: data.ID }, update: { 'deleteInfo.completeDeleted': true } } });
  521. }
  522. else if (data.updateType === fileType.unitPriceFile) {
  523. bulkUFs.push({ updateOne: { filter: { id: data.ID }, update: { 'deleteInfo.completeDeleted': true } } });
  524. }
  525. else {
  526. bulkFFs.push({ updateOne: { filter: { ID: data.ID }, update: { 'deleteInfo.completeDeleted': true } } });
  527. }
  528. }
  529. if (bulkProjs.length > 0) {
  530. await projectModel.bulkWrite(bulkProjs);
  531. }
  532. if (bulkUFs.length > 0) {
  533. await unitPriceFileModel.bulkWrite(bulkUFs);
  534. }
  535. if (bulkFFs.length > 0) {
  536. await feeRateFileModel.bulkWrite(bulkFFs);
  537. }
  538. callback(request, response, 0, 'success', null);
  539. } catch (err) {
  540. callback(request, response, 1, err, null);
  541. }
  542. },
  543. moveProject: async function (req, res) {
  544. let result = {
  545. error: 0
  546. };
  547. try {
  548. let data = req.body.data;
  549. let rdata = await pm_facade.moveProject(data);
  550. result.data = rdata;
  551. } catch (err) {
  552. console.log(err);
  553. result.error = 1;
  554. result.message = err.message;
  555. }
  556. res.json(result);
  557. },
  558. copyProjects: async function (req, res) {
  559. let result = {
  560. error: 0
  561. };
  562. try {
  563. let data = { dataString: req.body.data, userID: req.session.sessionUser.id, compilationID: req.session.sessionCompilation._id };
  564. result = await redirectToImportServer(data, "copyProject", req);
  565. } catch (err) {
  566. console.log(err);
  567. result.error = 1;
  568. result.message = err.message;
  569. }
  570. res.json(result);
  571. },
  572. projectShareInfo: async function (req, res) {
  573. try {
  574. const data = JSON.parse(req.body.data);
  575. const shareList = await pm_facade.getShareList({ projectID: data.projectID });
  576. const shareInfoMap = await pm_facade.getShareInfoMap(null, shareList);
  577. const shareInfo = shareInfoMap[data.projectID] || [];
  578. callback(req, res, 0, 'success', shareInfo);
  579. }
  580. catch (err) {
  581. callback(req, res, 1, err, null);
  582. }
  583. },
  584. getRecentShareInfo: async function (req, res) {
  585. try {
  586. const { count } = JSON.parse(req.body.data);
  587. const userID = req.session.sessionUser.id;
  588. const recentUsers = await pm_facade.getRecentShareList(userID, count);
  589. const contacts = await userModelObj.getContacts(userID);
  590. callback(req, res, 0, 'success', { recentUsers, contacts });
  591. } catch (err) {
  592. console.log(err);
  593. callback(req, res, 1, err.message, null);
  594. }
  595. },
  596. getInitialShareData: async function (req, res) {
  597. try {
  598. const { count, projectID } = JSON.parse(req.body.data);
  599. // 分享建设项目,仅提供给专业版用户
  600. /* const proShareProjType = [projType.folder, projType.project];
  601. const project = await projectModel.findOne({ ID: projectID }, 'projType');
  602. if (project && proShareProjType.indexOf(project.projType) >= 0) {
  603. const isFree = userModelObj.isFreeFromSession(req.session.compilationVersion);
  604. if (isFree) {
  605. callback(req, res, 0, 'success', { isFree });
  606. return;
  607. }
  608. } */
  609. const userID = req.session.sessionUser.id;
  610. // 最近分享
  611. const recentUsers = await pm_facade.getRecentShareList(userID, count);
  612. // 联系人
  613. const contacts = await userModelObj.getContacts(userID);
  614. // 分享过的人
  615. const sharedUsers = await pm_facade.getProjectShareList(projectID);
  616. callback(req, res, 0, 'success', { recentUsers, contacts, sharedUsers });
  617. } catch (err) {
  618. console.log(err);
  619. callback(req, res, 1, err.message, null);
  620. }
  621. },
  622. getReceiveLibList: async function (req, res) {
  623. try {
  624. const { libType } = JSON.parse(req.body.data);
  625. const userID = req.session.sessionUser.id;
  626. const compilationID = req.session.sessionCompilation._id;
  627. const list = await pm_facade.getReceiveLibList(userID, compilationID, libType);
  628. callback(req, res, 0, 'success', list);
  629. } catch (err) {
  630. callback(req, res, 1, err.message, null);
  631. }
  632. },
  633. getInitialShareLibData: async function (req, res) {
  634. try {
  635. const { libType, count } = JSON.parse(req.body.data);
  636. const userID = req.session.sessionUser.id;
  637. const compilationID = req.session.sessionCompilation._id;
  638. // 最近分享
  639. const recentUsers = await pm_facade.getRecentShareList(userID, count);
  640. // 联系人
  641. const contacts = await userModelObj.getContacts(userID);
  642. // 分享过的人
  643. const sharedUsers = await pm_facade.getLibShareList(userID, compilationID, libType, count);
  644. callback(req, res, 0, 'success', { recentUsers, contacts, sharedUsers });
  645. } catch (err) {
  646. console.log(err);
  647. callback(req, res, 1, err.message, null);
  648. }
  649. },
  650. shareLib: async function (req, res) {
  651. try {
  652. const { type, libType, shareData, count } = JSON.parse(req.body.data);
  653. const owner = req.session.sessionUser.id;
  654. const compilationID = req.session.sessionCompilation._id;
  655. const shareDate = moment(Date.now()).format('YYYY-MM-DD HH:mm:ss');
  656. shareData.forEach(item => item.shareDate = shareDate);
  657. const task = [];
  658. // 是否只是单纯的更新分享选项,如果不是,需要重新获取最近分享和联系人
  659. let isSimpleUpdate = true;
  660. if (type === 'create') {
  661. isSimpleUpdate = false;
  662. // 生成分享记录
  663. const docs = shareData.map(item => ({
  664. compilationID,
  665. owner,
  666. libType,
  667. ID: uuidV1(),
  668. receiver: item.receiver,
  669. allowCooperate: false,
  670. shareDate: item.shareDate,
  671. updateDate: item.shareDate
  672. }));
  673. task.push(pm_facade.addShareList(docs, true));
  674. // 分享即互相添加为联系人
  675. task.push(userModelObj.addContact(docs[0].owner, docs[0].receiver));
  676. } else if (type === 'cancel') { // 取消分享
  677. const cancelReceivers = shareData.map(item => item.receiver);
  678. task.push(pm_facade.deleteShareList({ owner, libType, compilationID, receiver: { $in: cancelReceivers } }, true));
  679. }
  680. await Promise.all(task);
  681. const rst = {};
  682. if (!isSimpleUpdate) {
  683. const rstTask = [
  684. pm_facade.getRecentShareList(owner, count),
  685. userModelObj.getContacts(owner)
  686. ];
  687. const [recentUsers, contacts] = await Promise.all(rstTask);
  688. Object.assign(rst, { recentUsers, contacts });
  689. }
  690. callback(req, res, 0, 'success', rst);
  691. } catch (err) {
  692. console.log(err);
  693. logger.info(err);
  694. callback(req, res, 1, err, null);
  695. }
  696. },
  697. share: async function (req, res) {
  698. try {
  699. const data = JSON.parse(req.body.data);
  700. const { type, permissionType, shareData, projectID, count } = data;
  701. const userID = req.session.sessionUser.id;
  702. const shareDate = moment(Date.now()).format('YYYY-MM-DD HH:mm:ss');
  703. shareData.forEach(item => item.shareDate = shareDate);
  704. const task = [];
  705. // 是否只是单纯的更新分享选项,如果不是,需要重新获取最近分享和联系人
  706. let isSimpleUpdate = true;
  707. if (type === 'create') {
  708. isSimpleUpdate = false;
  709. // 生成分享记录
  710. const docs = shareData.map(item => ({
  711. ID: uuidV1(),
  712. projectID,
  713. owner: userID,
  714. receiver: item.userID,
  715. allowCooperate: item.allowCooperate,
  716. allowCopy: item.allowCopy,
  717. shareDate: item.shareDate,
  718. updateDate: item.shareDate
  719. }));
  720. task.push(pm_facade.addShareList(docs));
  721. // 分享即互相添加为联系人
  722. task.push(userModelObj.addContact(docs[0].owner, docs[0].receiver));
  723. } else if (type === 'update') {
  724. // 取消分享(以前项目管理界面可一次进行更新和取消)
  725. const cancelReceivers = shareData
  726. .filter(item => item.isCancel)
  727. .map(item => item.userID);
  728. if (cancelReceivers.length) {
  729. isSimpleUpdate = false;
  730. task.push(pm_facade.deleteShareList({ projectID, receiver: { $in: cancelReceivers } }));
  731. }
  732. // 更新分享选项
  733. const updateData = shareData
  734. .filter(item => !item.isCancel)
  735. .map(item => {
  736. const update = { updateDate: shareDate };
  737. if (commonUtil.isDef(item.allowCopy)) {
  738. update.allowCopy = item.allowCopy;
  739. }
  740. if (commonUtil.isDef(item.allowCooperate)) {
  741. update.allowCooperate = item.allowCooperate;
  742. }
  743. return {
  744. query: {
  745. projectID,
  746. receiver: item.userID
  747. },
  748. update
  749. };
  750. });
  751. if (updateData.length) {
  752. task.push(pm_facade.updateShareList(updateData))
  753. }
  754. } else { // 取消分享
  755. const cancelReceivers = shareData.map(item => item.userID);
  756. task.push(pm_facade.deleteShareList({ projectID, receiver: { $in: cancelReceivers } }));
  757. }
  758. await Promise.all(task);
  759. // 获取需要广播推送的单位工程
  760. // shareData数组的形式是以前需求需要,现在的需求下,shareData数组必定只有一个元素
  761. const emitTenders = await pm_facade.getShareInfoAfterChangePermission(permissionType, shareData[0].userID, projectID);
  762. let rst = { emitTenders };
  763. if (!isSimpleUpdate) {
  764. const rstTask = [
  765. pm_facade.getRecentShareList(userID, count),
  766. userModelObj.getContacts(userID)
  767. ];
  768. const [recentUsers, contacts] = await Promise.all(rstTask);
  769. Object.assign(rst, { recentUsers, contacts });
  770. }
  771. callback(req, res, 0, 'success', rst);
  772. }
  773. catch (err) {
  774. console.log(err);
  775. callback(req, res, 1, String(err), null);
  776. }
  777. },
  778. receiveProjects: async function (req, res) {
  779. try {
  780. let rst = { grouped: [], ungrouped: [], summaryInfo: null };
  781. let userID = req.session.sessionUser.id;
  782. const shareList = await pm_facade.getShareList({ receiver: userID });
  783. const receiveProjectIDs = shareList.map(item => item.projectID);
  784. const compilation = req.session.sessionCompilation._id;
  785. const notDeleted = [{ deleteInfo: null }, { 'deleteInfo.deleted': false }];
  786. const receiveProjects = await projectModel.find({ ID: { $in: receiveProjectIDs }, compilation, $or: notDeleted }, '-_id').lean();
  787. //设置原项目用户信息
  788. const shareInfoMap = await pm_facade.getShareInfoMap(null, shareList);
  789. if (receiveProjects.length > 0) {
  790. let orgUserIDs = [];
  791. for (let proj of receiveProjects) {
  792. orgUserIDs.push(proj.userID);
  793. if (proj.projType === projType.tender) {
  794. // 设置项目类别
  795. proj.valuationType = proj.property.valuationType === 'bill' ? '预算' : '工程量清单';
  796. proj._valuationType = proj.property.valuationType;
  797. //设置工程专业
  798. proj.feeStandardName = proj.property.feeStandardName || '';
  799. //设置计税方法
  800. proj.taxType = proj.property.taxType;
  801. }
  802. delete proj.property;
  803. }
  804. orgUserIDs = Array.from(new Set(orgUserIDs));
  805. let userObjIDs = [];
  806. for (let uID of orgUserIDs) {
  807. userObjIDs.push(mongoose.Types.ObjectId(uID));
  808. }
  809. let orgUsersInfo = await userModel.find({ _id: { $in: userObjIDs } });
  810. //建设项目
  811. let consProjIDs = [],
  812. ungroupedTenders = [];
  813. for (let proj of receiveProjects) {
  814. // 设置分享信息
  815. proj.shareInfo = shareInfoMap[proj.ID] || [];
  816. if (proj.projType === projType.project) {
  817. consProjIDs.push(proj.ID);
  818. }
  819. //获取分享项目子项
  820. if (proj.projType !== projType.tender) {
  821. proj.children = await pm_facade.getPosterityProjects([proj.ID]);
  822. for (let projC of proj.children) {
  823. // 设置分享信息
  824. projC.shareInfo = shareInfoMap[projC.ID] || [];
  825. if (projC.projType === projType.project) {
  826. consProjIDs.push(projC.ID);
  827. } else if (projC.projType === projType.tender) {
  828. // 设置项目类别
  829. projC.valuationType = projC.property.valuationType === 'bill' ? '预算' : '工程量清单';
  830. projC._valuationType = projC.property.valuationType;
  831. //设置工程专业
  832. projC.feeStandardName = projC.property.feeStandardName || '';
  833. }
  834. delete projC.property;
  835. }
  836. } else {//未分类的单位工程不进行汇总,只取价格信息
  837. ungroupedTenders.push(proj);
  838. }
  839. //设置分组,单位工程及单项工程分到未分组那
  840. if (proj.projType === projType.tender || proj.projType === projType.engineering) {
  841. rst.ungrouped.push(proj);
  842. } else {
  843. rst.grouped.push(proj);
  844. }
  845. //设置项目类型为来自别人分享
  846. proj.shareType = 'receive';
  847. for (let userData of orgUsersInfo) {
  848. if (proj.userID == userData._id.toString()) {
  849. let userInfo = { name: userData.real_name, mobile: userData.mobile, company: userData.company, email: userData.email };
  850. proj.userInfo = userInfo;
  851. }
  852. }
  853. }
  854. consProjIDs = Array.from(new Set(consProjIDs));
  855. let summaryInfo = await pm_facade.getSummaryInfo(consProjIDs);
  856. let tendersFeeInfo = await pm_facade.getTendersFeeInfo(ungroupedTenders);
  857. rst.summaryInfo = { grouped: summaryInfo, ungrouped: tendersFeeInfo };
  858. }
  859. callback(req, res, 0, 'success', rst);
  860. }
  861. catch (err) {
  862. console.log(err);
  863. callback(req, res, 1, err, null);
  864. }
  865. },
  866. getProjectsByQuery: async function (req, res) {
  867. try {
  868. let data = JSON.parse(req.body.data);
  869. let compilation = req.session.sessionCompilation._id;
  870. let query = data.query;
  871. query.compilation = compilation;
  872. let options = data.options;
  873. let projects = await projectModel.find(query, options);
  874. callback(req, res, 0, 'success', projects);
  875. }
  876. catch (err) {
  877. callback(req, res, 1, err, null);
  878. }
  879. },
  880. getSummaryInfo: async function (req, res) {
  881. try {
  882. let data = JSON.parse(req.body.data);
  883. let summaryInfo = await pm_facade.getSummaryInfo(data.projectIDs);
  884. callback(req, res, 0, 'success', summaryInfo);
  885. }
  886. catch (err) {
  887. callback(req, res, 1, err, null);
  888. }
  889. },
  890. changeFile: async function (req, res) {
  891. try {
  892. let data = JSON.parse(req.body.data);
  893. console.log(data);
  894. await pm_facade.changeFile(data.projects, data.user_id, data.fileID, data.name, data.from, data.type);
  895. callback(req, res, 0, 'success', []);
  896. }
  897. catch (err) {
  898. console.log(err);
  899. callback(req, res, 1, err, null);
  900. }
  901. },
  902. exportProject: async function (req, res) {
  903. let result = {
  904. error: 0
  905. };
  906. try {
  907. let data = { dataString: req.body.data, userID: req.session.sessionUser.id };
  908. result = await redirectToImportServer(data, "exportProject", req);
  909. } catch (err) {
  910. console.log(err);
  911. result.error = 1;
  912. result.message = err.message;
  913. }
  914. res.json(result);
  915. },
  916. importProject: async function (req, res) {
  917. let data = JSON.parse(req.body.data);
  918. let result = {
  919. error: 0
  920. };
  921. try {
  922. data.session = req.session;
  923. result = await redirectToImportServer(data,"importProject",req);
  924. } catch (err) {
  925. console.log(err);
  926. result.error = 1;
  927. result.message = err.message;
  928. }
  929. res.json(result);
  930. },
  931. copyConstructionProject: async function (req, res) {
  932. let data = JSON.parse(req.body.data);
  933. let result = {
  934. error: 0
  935. };
  936. try {
  937. data.session = req.session;
  938. result.data = await redirectToImportServer(data, "copyConstructionProject", req);
  939. } catch (err) {
  940. console.log(err);
  941. result.error = 1;
  942. result.message = err.message;
  943. }
  944. res.json(result);
  945. },
  946. importProcessChecking: async function (req, res) {
  947. let result = {
  948. error: 0
  949. };
  950. try {
  951. let data = JSON.parse(req.body.data);
  952. data.userID = req.session.sessionUser.id;
  953. data.compilationID = req.session.sessionCompilation._id;
  954. result.data = await pm_facade.importProcessChecking(data);
  955. } catch (err) {
  956. console.log(err);
  957. result.error = 1;
  958. result.message = err.message;
  959. }
  960. res.json(result);
  961. },
  962. getUploadToken: function (req, res) {
  963. let result = {
  964. error: 0
  965. };
  966. try {
  967. result = pm_facade.uploadToken();
  968. } catch (err) {
  969. console.log(err);
  970. result.error = 1;
  971. result.message = err.message;
  972. }
  973. res.json(result);
  974. },
  975. getProjectByGranularity: async function (req, res) {
  976. try {
  977. const data = JSON.parse(req.body.data);
  978. const userID = req.session.sessionUser.id;
  979. const version = req.session.compilationVersion;
  980. const projData = await pm_facade.getProjectByGranularity(data.tenderID, data.granularity, data.requestForSummaryInfo, userID, version);
  981. callback(req, res, 0, 'success', projData);
  982. } catch (err) {
  983. callback(req, res, 1, err, null);
  984. }
  985. },
  986. getImportTemplateData: async function (req, res) {
  987. try {
  988. const data = JSON.parse(req.body.data);
  989. const templateData = await pm_facade.getImportTemplateData(req.session.sessionCompilation._id, data.feeName, data.valuationID, data.projectCount);
  990. callback(req, res, 0, 'success', templateData);
  991. } catch (err) {
  992. callback(req, res, 1, err, null);
  993. }
  994. },
  995. importInterface: async function (req, res) {
  996. const data = JSON.parse(req.body.data);
  997. let result = {
  998. error: 0
  999. };
  1000. try {
  1001. data.session = req.session;
  1002. result = await redirectToImportServer(data, "importInterface", req);
  1003. } catch (err) {
  1004. console.log(err);
  1005. result.error = 1;
  1006. result.message = err.message;
  1007. }
  1008. res.json(result);
  1009. },
  1010. };
  1011. async function redirectToImportServer(data, action, req) {
  1012. let importURL = config.getImportURL(process.env.NODE_ENV, req.headers.origin);
  1013. let options = {
  1014. method: 'POST',
  1015. uri: `http://${importURL}/import/${action}`,
  1016. body: data,
  1017. timeout: 220000,
  1018. json: true
  1019. };
  1020. console.log("post import data to:" + options.uri);
  1021. return await rp.post(options);
  1022. }