pm_controller.js 49 KB

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