pm_controller.js 52 KB

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