pm_controller.js 45 KB

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