pm_controller.js 46 KB

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