pm_controller.js 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125
  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. if (false && isFree && config.prod_sc.title !== '纵横公路云造价') {
  329. let renderData = {
  330. userAccount: request.session.userAccount,
  331. userID: request.session.sessionUser.id,
  332. compilationName: sessionCompilation.name,
  333. versionName: request.session.compilationVersion,
  334. title:getTitle(request.headers.host)
  335. };
  336. response.render('building_saas/pm/html/blank-project.html', renderData);
  337. } else {
  338. let compilationModel = new CompilationModel();
  339. //更新编办信息
  340. let compilationData = await compilationModel.getCompilationById(sessionCompilation._id);
  341. request.session.sessionCompilation = compilationData;
  342. sessionCompilation = request.session.sessionCompilation;
  343. //更新用户的使用过的费用定额列表
  344. let isFirst = await pm_facade.isFirst(request.session.sessionUser.id, compilationData._id.toString());
  345. let engineeringLibModel = new EngineeringLibModel();
  346. // 建议估算
  347. let suggestionValuation = sessionCompilation.suggestion_valuation !== undefined ?
  348. sessionCompilation.suggestion_valuation : [];
  349. suggestionValuation = await engineeringLibModel.getLib(suggestionValuation);
  350. // 可行性估算
  351. let feasibilityValuation = sessionCompilation.feasibility_valuation !== undefined ?
  352. sessionCompilation.feasibility_valuation : [];
  353. feasibilityValuation = await engineeringLibModel.getLib(feasibilityValuation);
  354. // 估算
  355. let estimationValuation = sessionCompilation.estimation_valuation !== undefined ?
  356. sessionCompilation.estimation_valuation : [];
  357. estimationValuation = await engineeringLibModel.getLib(estimationValuation);
  358. // 概算
  359. let roughValuation = sessionCompilation.rough_valuation !== undefined ?
  360. sessionCompilation.rough_valuation : [];
  361. roughValuation = await engineeringLibModel.getLib(roughValuation);
  362. // 清单计价
  363. let billValuation = sessionCompilation.bill_valuation !== undefined ?
  364. sessionCompilation.bill_valuation : [];
  365. billValuation = await engineeringLibModel.getLib(billValuation);
  366. // 定额计价
  367. let rationValuation = sessionCompilation.ration_valuation !== undefined ?
  368. sessionCompilation.ration_valuation : [];
  369. rationValuation = await engineeringLibModel.getLib(rationValuation);
  370. if (sessionCompilation.name === '四川养护(2013)' || sessionCompilation.name === '部颁2018计价标准') {
  371. billValuation = rationValuation;
  372. }
  373. let absoluteUrl = compilationData.overWriteUrl ? request.app.locals.rootDir + compilationData.overWriteUrl : request.app.locals.rootDir;
  374. let overWriteUrl = fs.existsSync(absoluteUrl) && fs.statSync(absoluteUrl).isFile() ? compilationData.overWriteUrl : null;
  375. //欢迎页显示控制
  376. let [isShow,context,showTime] = await pm_facade.getWelcomeInfo(sessionCompilation._id,request.session.sessionUser,request.session.compilationVersion.includes('学习'));
  377. const unreadShareList = await pm_facade.getUnreadShareListByCompilation(request.session.sessionUser.id, sessionCompilation._id);
  378. let renderData = {
  379. unreadShareList: JSON.stringify(unreadShareList),
  380. isFirst: isFirst,
  381. isShow:isShow,
  382. context:context,
  383. showTime:showTime,
  384. userAccount: request.session.userAccount,
  385. userID: request.session.sessionUser.id,
  386. isFree,
  387. compilationData: JSON.stringify(sessionCompilation),
  388. overWriteUrl: overWriteUrl,
  389. suggestionValuation: JSON.stringify(suggestionValuation),
  390. feasibilityValuation: JSON.stringify(feasibilityValuation),
  391. estimationValuation: JSON.stringify(estimationValuation),
  392. roughValuation: JSON.stringify(roughValuation),
  393. billValuation: JSON.stringify(billValuation),
  394. rationValuation: JSON.stringify(rationValuation),
  395. engineeringList: JSON.stringify(engineering.List),
  396. adminLevelType: JSON.stringify(AdminLevelType),
  397. compilationName: sessionCompilation.name,
  398. versionName: request.session.compilationVersion,
  399. socketPort:config[process.env.NODE_ENV].socketPort?config[process.env.NODE_ENV].socketPort:5500,
  400. LicenseKey:config.getLicenseKey(process.env.NODE_ENV),
  401. cloudTitle: config.prod_sc.title,
  402. title:getTitle(request.headers.host)
  403. };
  404. response.render('building_saas/pm/html/project-management.html', renderData);
  405. }
  406. },
  407. //第一次进入该费用定额时准备的初始数据
  408. prepareInitialData: async function (request, response) {
  409. try {
  410. const data = {
  411. userID: request.session.sessionUser.id,
  412. compilationID: request.session.sessionCompilation._id,
  413. example: request.session.sessionCompilation.example
  414. };
  415. await redirectToImportServer(data, 'prepareInitialData', request);
  416. callback(request, response, 0, 'success', null);
  417. } catch (err) {
  418. console.log(err);
  419. callback(request, response, 1, err.toString(), null);
  420. }
  421. },
  422. // 获取单价文件列表
  423. getUnitFileList: async function (request, response) {
  424. let data = request.body.data;
  425. try {
  426. data = JSON.parse(data);
  427. let projectId = data.parentID !== undefined ? data.parentID : 0;
  428. if (isNaN(projectId) && projectId <= 0) {
  429. throw { msg: 'id数据有误!', err: 1 };
  430. }
  431. /*// 获取对应建设项目下所有的单位工程id
  432. let idList = await ProjectsData.getTenderByProjectId(projectId);
  433. if (idList.length <= 0) {
  434. throw {msg: '不存在对应单位工程', err: 0};
  435. }*/
  436. // 获取对应的单价文件
  437. let unitPriceFileModel = new UnitPriceFileModel();
  438. let unitPriceFileData = await unitPriceFileModel.getDataByRootProject(projectId);
  439. if (unitPriceFileData === null) {
  440. throw { msg: '不存在对应单价文件', err: 0 };
  441. }
  442. // 整理数据
  443. let unitPriceFileList = [];
  444. for (let unitPriceFile of unitPriceFileData) {
  445. let tmp = {
  446. name: unitPriceFile.name,
  447. id: unitPriceFile.id
  448. };
  449. unitPriceFileList.push(tmp);
  450. }
  451. callback(request, response, 0, '', unitPriceFileList);
  452. } catch (error) {
  453. console.log(error);
  454. let responseData = error.err === 1 ? null : [];
  455. callback(request, response, error.err, error.msg, responseData);
  456. }
  457. },
  458. getFeeRateFileList: async function (request, response) {
  459. let data = request.body.data;
  460. try {
  461. data = JSON.parse(data);
  462. let projectId = data.parentID !== undefined ? data.parentID : 0;
  463. if (isNaN(projectId) && projectId <= 0) {
  464. throw { msg: 'id数据有误!', err: 1 };
  465. }
  466. // 获取对应建设项目下所有的单位工程id
  467. let feeRateFileList = await fee_rate_facade.getFeeRatesByProject(projectId);
  468. callback(request, response, 0, '', feeRateFileList);
  469. } catch (error) {
  470. console.log(error);
  471. let responseData = error.err === 1 ? null : [];
  472. callback(request, response, error.err, error.msg, responseData);
  473. }
  474. },
  475. getGC: async function(req, res) {
  476. const userID = req.session.sessionUser.id;
  477. const compilationId = req.session.sessionCompilation._id;
  478. try {
  479. const rst = [];
  480. const priceFilesTask = ProjectsData.getGCFiles(fileType.unitPriceFile, userID);
  481. const feeRateFilesTask = ProjectsData.getGCFiles(fileType.feeRateFile, userID);
  482. const tendersTask = ProjectsData.getGCFiles(projType.tender, userID);
  483. const [priceFiles, rateFiles, tenders] = await Promise.all([priceFilesTask, feeRateFilesTask, tendersTask]);
  484. // 建设项目
  485. let projectIDs = tenders.reduce((acc, cur) => {
  486. acc.push(cur.ParentID);
  487. return acc;
  488. }, []);
  489. projectIDs = [...new Set(projectIDs)];
  490. const projects = await ProjectsData.getProjectsByIds(userID, compilationId, projectIDs);
  491. projects.forEach(project => {
  492. const projectDoc = project._doc;
  493. const relTenders = tenders.filter(tender => tender.ParentID === projectDoc.ID);
  494. const unitPriceFiles = priceFiles.filter(file => relTenders.find(tender => tender.property.unitPriceFile.id === file.id));
  495. const feeRateFiles = rateFiles.filter(file => relTenders.find(tender => tender.property.feeFile.id === file.ID));
  496. projectDoc.children = relTenders;
  497. projectDoc.unitPriceFiles = unitPriceFiles;
  498. projectDoc.feeRateFiles = feeRateFiles;
  499. rst.push(projectDoc);
  500. });
  501. callback(req, res, 0, 'success', rst);
  502. } catch (err) {
  503. console.log(err);
  504. callback(req, res, true, err.message, null);
  505. }
  506. },
  507. getGCDatas: async function (request, response) {
  508. let userID = request.session.sessionUser.id;
  509. let compilatoinId = request.session.sessionCompilation._id;
  510. let rst = [];
  511. let _projs = Object.create(null), _engs = Object.create(null), prefix = 'ID_';
  512. try {
  513. let gc_unitPriceFiles = await ProjectsData.getGCFiles(fileType.unitPriceFile, userID);
  514. let gc_feeRateFiles = await ProjectsData.getGCFiles(fileType.feeRateFile, userID);
  515. let gc_tenderFiles = await ProjectsData.getGCFiles(projType.tender, userID);
  516. for (let i = 0, len = gc_unitPriceFiles.length; i < len; i++) {
  517. let gc_uf = gc_unitPriceFiles[i];
  518. let theProj = _projs[prefix + gc_uf.root_project_id] || null;
  519. if (!theProj) {
  520. let tempProj = await ProjectsData.getProjectsByIds(userID, compilatoinId, [gc_uf.root_project_id]);
  521. if (tempProj.length > 0 && tempProj[0].projType !== projType.folder) {
  522. theProj = _projs[prefix + gc_uf.root_project_id] = tempProj[0]._doc;
  523. buildProj(theProj);
  524. }
  525. }
  526. if (theProj) {
  527. theProj.unitPriceFiles.push(gc_uf);
  528. }
  529. }
  530. for (let i = 0, len = gc_feeRateFiles.length; i < len; i++) {
  531. let gc_ff = gc_feeRateFiles[i];
  532. let theProj = _projs[prefix + gc_ff.rootProjectID] || null;
  533. if (!theProj) {
  534. let tempProj = await ProjectsData.getProjectsByIds(userID, compilatoinId, [gc_ff.rootProjectID]);
  535. if (tempProj.length > 0 && tempProj[0].projType !== projType.folder) {
  536. theProj = _projs[prefix + gc_ff.rootProjectID] = tempProj[0]._doc;
  537. buildProj(theProj);
  538. }
  539. }
  540. if (theProj) {
  541. theProj.feeRateFiles.push(gc_ff);
  542. }
  543. }
  544. if (gc_tenderFiles.length > 0) {
  545. for (let i = 0, len = gc_tenderFiles.length; i < len; i++) {
  546. let gc_t = gc_tenderFiles[i];
  547. let theProj = _projs[prefix + gc_t.ParentID] || null;
  548. if(!theProj){
  549. let tempProjs = await ProjectsData.getProjectsByIds(userID, compilatoinId, [gc_t.ParentID]);
  550. if(tempProjs.length > 0 && tempProjs[0].projType === projType.project){
  551. theProj = _projs[prefix + gc_t.ParentID] = tempProjs[0]._doc;
  552. buildProj(theProj);
  553. }
  554. }
  555. if(theProj) {
  556. theProj.children.push(gc_t);
  557. }
  558. }
  559. }
  560. for (let i in _projs) {
  561. rst.push(_projs[i]);
  562. }
  563. function buildProj(proj) {
  564. proj.children = [];
  565. proj.unitPriceFiles = [];
  566. proj.feeRateFiles = [];
  567. }
  568. callback(request, response, 0, 'success', rst);
  569. }
  570. catch (error) {
  571. callback(request, response, true, error, null);
  572. }
  573. },
  574. recGC: function (request, response) {
  575. let userID = request.session.sessionUser.id,
  576. compilationId = request.session.sessionCompilation._id;
  577. let data = JSON.parse(request.body.data);
  578. let nodes = data.nodes;
  579. ProjectsData.recGC(userID, compilationId, nodes, function (err, msg, data) {
  580. callback(request, response, err, msg, data);
  581. });
  582. },
  583. delGC: async function (request, response) {
  584. let data = JSON.parse(request.body.data);
  585. let delDatas = data.delDatas;
  586. let bulkProjs = [], bulkUFs = [], bulkFFs = [];
  587. try {
  588. for (let data of delDatas) {
  589. if (data.updateType === 'Project') {
  590. bulkProjs.push({ updateOne: { filter: { ID: data.ID }, update: { 'deleteInfo.completeDeleted': true } } });
  591. }
  592. else if (data.updateType === fileType.unitPriceFile) {
  593. bulkUFs.push({ updateOne: { filter: { id: data.ID }, update: { 'deleteInfo.completeDeleted': true } } });
  594. }
  595. else {
  596. bulkFFs.push({ updateOne: { filter: { ID: data.ID }, update: { 'deleteInfo.completeDeleted': true } } });
  597. }
  598. }
  599. if (bulkProjs.length > 0) {
  600. await projectModel.bulkWrite(bulkProjs);
  601. }
  602. if (bulkUFs.length > 0) {
  603. await unitPriceFileModel.bulkWrite(bulkUFs);
  604. }
  605. if (bulkFFs.length > 0) {
  606. await feeRateFileModel.bulkWrite(bulkFFs);
  607. }
  608. callback(request, response, 0, 'success', null);
  609. } catch (err) {
  610. callback(request, response, 1, err, null);
  611. }
  612. },
  613. moveProject: async function (req, res) {
  614. let result = {
  615. error: 0
  616. };
  617. try {
  618. let data = req.body.data;
  619. let rdata = await pm_facade.moveProject(data);
  620. result.data = rdata;
  621. } catch (err) {
  622. console.log(err);
  623. result.error = 1;
  624. result.message = err.message;
  625. }
  626. res.json(result);
  627. },
  628. copyProjects: async function (req, res) {
  629. let result = {
  630. error: 0
  631. };
  632. try {
  633. let data = { dataString: req.body.data, userID: req.session.sessionUser.id, compilationID: req.session.sessionCompilation._id };
  634. result = await redirectToImportServer(data, "copyProject", req);
  635. } catch (err) {
  636. console.log(err);
  637. result.error = 1;
  638. result.message = err.message;
  639. }
  640. res.json(result);
  641. },
  642. projectShareInfo: async function (req, res) {
  643. try {
  644. const data = JSON.parse(req.body.data);
  645. const shareList = await pm_facade.getShareList({ projectID: data.projectID });
  646. const shareInfoMap = await pm_facade.getShareInfoMap(null, shareList);
  647. const shareInfo = shareInfoMap[data.projectID] || [];
  648. callback(req, res, 0, 'success', shareInfo);
  649. }
  650. catch (err) {
  651. callback(req, res, 1, err, null);
  652. }
  653. },
  654. getRecentShareInfo: async function (req, res) {
  655. try {
  656. const { count } = JSON.parse(req.body.data);
  657. const userID = req.session.sessionUser.id;
  658. const recentUsers = await pm_facade.getRecentShareList(userID, count);
  659. const contacts = await userModelObj.getContacts(userID);
  660. callback(req, res, 0, 'success', { recentUsers, contacts });
  661. } catch (err) {
  662. console.log(err);
  663. callback(req, res, 1, err.message, null);
  664. }
  665. },
  666. getInitialShareData: async function (req, res) {
  667. try {
  668. const { count, projectID } = JSON.parse(req.body.data);
  669. // 分享建设项目,仅提供给专业版用户
  670. /* const proShareProjType = [projType.folder, projType.project];
  671. const project = await projectModel.findOne({ ID: projectID }, 'projType');
  672. if (project && proShareProjType.indexOf(project.projType) >= 0) {
  673. const isFree = userModelObj.isFreeFromSession(req.session.compilationVersion);
  674. if (isFree) {
  675. callback(req, res, 0, 'success', { isFree });
  676. return;
  677. }
  678. } */
  679. const userID = req.session.sessionUser.id;
  680. // 最近分享
  681. const recentUsers = await pm_facade.getRecentShareList(userID, count);
  682. // 联系人
  683. const contacts = await userModelObj.getContacts(userID);
  684. // 分享过的人
  685. const sharedUsers = await pm_facade.getProjectShareList(projectID);
  686. callback(req, res, 0, 'success', { recentUsers, contacts, sharedUsers });
  687. } catch (err) {
  688. console.log(err);
  689. callback(req, res, 1, err.message, null);
  690. }
  691. },
  692. getReceiveLibList: async function (req, res) {
  693. try {
  694. const { libType } = JSON.parse(req.body.data);
  695. const userID = req.session.sessionUser.id;
  696. const compilationID = req.session.sessionCompilation._id;
  697. const list = await pm_facade.getReceiveLibList(userID, compilationID, libType);
  698. callback(req, res, 0, 'success', list);
  699. } catch (err) {
  700. callback(req, res, 1, err.message, null);
  701. }
  702. },
  703. getInitialShareLibData: async function (req, res) {
  704. try {
  705. const { libType, count } = JSON.parse(req.body.data);
  706. const userID = req.session.sessionUser.id;
  707. const compilationID = req.session.sessionCompilation._id;
  708. // 最近分享
  709. const recentUsers = await pm_facade.getRecentShareList(userID, count);
  710. // 联系人
  711. const contacts = await userModelObj.getContacts(userID);
  712. // 分享过的人
  713. const sharedUsers = await pm_facade.getLibShareList(userID, compilationID, libType, count);
  714. callback(req, res, 0, 'success', { recentUsers, contacts, sharedUsers });
  715. } catch (err) {
  716. console.log(err);
  717. callback(req, res, 1, err.message, null);
  718. }
  719. },
  720. shareLib: async function (req, res) {
  721. try {
  722. const { type, libType, shareData, count } = JSON.parse(req.body.data);
  723. const owner = req.session.sessionUser.id;
  724. const compilationID = req.session.sessionCompilation._id;
  725. const shareDate = moment(Date.now()).format('YYYY-MM-DD HH:mm:ss');
  726. shareData.forEach(item => item.shareDate = shareDate);
  727. const task = [];
  728. // 是否只是单纯的更新分享选项,如果不是,需要重新获取最近分享和联系人
  729. let isSimpleUpdate = true;
  730. if (type === 'create') {
  731. isSimpleUpdate = false;
  732. // 生成分享记录
  733. const docs = shareData.map(item => ({
  734. compilationID,
  735. owner,
  736. libType,
  737. ID: uuidV1(),
  738. receiver: item.receiver,
  739. allowCooperate: false,
  740. shareDate: item.shareDate,
  741. updateDate: item.shareDate
  742. }));
  743. task.push(pm_facade.addShareList(docs, true));
  744. // 分享即互相添加为联系人
  745. task.push(userModelObj.addContact(docs[0].owner, docs[0].receiver));
  746. } else if (type === 'cancel') { // 取消分享
  747. const cancelReceivers = shareData.map(item => item.receiver);
  748. task.push(pm_facade.deleteShareList({ owner, libType, compilationID, receiver: { $in: cancelReceivers } }, true));
  749. }
  750. await Promise.all(task);
  751. const rst = {};
  752. if (!isSimpleUpdate) {
  753. const rstTask = [
  754. pm_facade.getRecentShareList(owner, count),
  755. userModelObj.getContacts(owner)
  756. ];
  757. const [recentUsers, contacts] = await Promise.all(rstTask);
  758. Object.assign(rst, { recentUsers, contacts });
  759. }
  760. callback(req, res, 0, 'success', rst);
  761. } catch (err) {
  762. console.log(err);
  763. logger.info(err);
  764. callback(req, res, 1, err, null);
  765. }
  766. },
  767. share: async function (req, res) {
  768. try {
  769. const data = JSON.parse(req.body.data);
  770. const { type, permissionType, shareData, projectID, count } = data;
  771. const userID = req.session.sessionUser.id;
  772. const shareDate = moment(Date.now()).format('YYYY-MM-DD HH:mm:ss');
  773. shareData.forEach(item => item.shareDate = shareDate);
  774. const task = [];
  775. // 是否只是单纯的更新分享选项,如果不是,需要重新获取最近分享和联系人
  776. let isSimpleUpdate = true;
  777. if (type === 'create') {
  778. isSimpleUpdate = false;
  779. // 生成分享记录
  780. const docs = shareData.map(item => ({
  781. ID: uuidV1(),
  782. projectID,
  783. owner: userID,
  784. receiver: item.userID,
  785. allowCooperate: item.allowCooperate,
  786. allowCopy: item.allowCopy,
  787. shareDate: item.shareDate,
  788. updateDate: item.shareDate
  789. }));
  790. task.push(pm_facade.addShareList(docs));
  791. // 分享即互相添加为联系人
  792. task.push(userModelObj.addContact(docs[0].owner, docs[0].receiver));
  793. } else if (type === 'update') {
  794. // 取消分享(以前项目管理界面可一次进行更新和取消)
  795. const cancelReceivers = shareData
  796. .filter(item => item.isCancel)
  797. .map(item => item.userID);
  798. if (cancelReceivers.length) {
  799. isSimpleUpdate = false;
  800. task.push(pm_facade.deleteShareList({ projectID, receiver: { $in: cancelReceivers } }));
  801. }
  802. // 更新分享选项
  803. const updateData = shareData
  804. .filter(item => !item.isCancel)
  805. .map(item => {
  806. const update = { updateDate: shareDate };
  807. if (commonUtil.isDef(item.allowCopy)) {
  808. update.allowCopy = item.allowCopy;
  809. }
  810. if (commonUtil.isDef(item.allowCooperate)) {
  811. update.allowCooperate = item.allowCooperate;
  812. }
  813. return {
  814. query: {
  815. projectID,
  816. receiver: item.userID
  817. },
  818. update
  819. };
  820. });
  821. if (updateData.length) {
  822. task.push(pm_facade.updateShareList(updateData))
  823. }
  824. } else { // 取消分享
  825. const cancelReceivers = shareData.map(item => item.userID);
  826. task.push(pm_facade.deleteShareList({ projectID, receiver: { $in: cancelReceivers } }));
  827. }
  828. await Promise.all(task);
  829. // 获取需要广播推送的单位工程
  830. // shareData数组的形式是以前需求需要,现在的需求下,shareData数组必定只有一个元素
  831. const emitTenders = await pm_facade.getShareInfoAfterChangePermission(permissionType, shareData[0].userID, projectID);
  832. let rst = { emitTenders };
  833. if (!isSimpleUpdate) {
  834. const rstTask = [
  835. pm_facade.getRecentShareList(userID, count),
  836. userModelObj.getContacts(userID)
  837. ];
  838. const [recentUsers, contacts] = await Promise.all(rstTask);
  839. Object.assign(rst, { recentUsers, contacts });
  840. }
  841. callback(req, res, 0, 'success', rst);
  842. }
  843. catch (err) {
  844. console.log(err);
  845. callback(req, res, 1, String(err), null);
  846. }
  847. },
  848. receiveProjects: async function (req, res) {
  849. try {
  850. let rst = { grouped: [], ungrouped: [], summaryInfo: null };
  851. let userID = req.session.sessionUser.id;
  852. const shareList = await pm_facade.getShareList({ receiver: userID });
  853. const receiveProjectIDs = shareList.map(item => item.projectID);
  854. const compilation = req.session.sessionCompilation._id;
  855. const notDeleted = [{ deleteInfo: null }, { 'deleteInfo.deleted': false }];
  856. const receiveProjects = await projectModel.find({ ID: { $in: receiveProjectIDs }, compilation, $or: notDeleted }, '-_id').lean();
  857. //设置原项目用户信息
  858. const shareInfoMap = await pm_facade.getShareInfoMap(null, shareList);
  859. if (receiveProjects.length > 0) {
  860. let orgUserIDs = [];
  861. for (let proj of receiveProjects) {
  862. orgUserIDs.push(proj.userID);
  863. if (proj.projType === projType.tender) {
  864. // 设置项目类别
  865. proj.valuationType = ValuationText[proj.property.valuationType] || '';
  866. proj._valuationType = proj.property.valuationType;
  867. //设置工程专业
  868. proj.feeStandardName = proj.property.feeStandardName || '';
  869. //设置计税方法
  870. proj.taxType = proj.property.taxType;
  871. }
  872. delete proj.property;
  873. }
  874. orgUserIDs = Array.from(new Set(orgUserIDs));
  875. let userObjIDs = [];
  876. for (let uID of orgUserIDs) {
  877. userObjIDs.push(mongoose.Types.ObjectId(uID));
  878. }
  879. let orgUsersInfo = await userModel.find({ _id: { $in: userObjIDs } });
  880. //建设项目
  881. let consProjIDs = [],
  882. ungroupedTenders = [];
  883. for (let proj of receiveProjects) {
  884. // 设置分享信息
  885. proj.shareInfo = shareInfoMap[proj.ID] || [];
  886. if (proj.projType === projType.project) {
  887. consProjIDs.push(proj.ID);
  888. }
  889. //获取分享项目子项
  890. if (proj.projType !== projType.tender) {
  891. proj.children = await pm_facade.getPosterityProjects([proj.ID]);
  892. for (let projC of proj.children) {
  893. // 设置分享信息
  894. projC.shareInfo = shareInfoMap[projC.ID] || [];
  895. if (projC.projType === projType.project) {
  896. consProjIDs.push(projC.ID);
  897. } else if (projC.projType === projType.tender) {
  898. // 设置项目类别
  899. projC.valuationType = ValuationText[projC.property.valuationType] || '';
  900. projC._valuationType = projC.property.valuationType;
  901. //设置工程专业
  902. projC.feeStandardName = projC.property.feeStandardName || '';
  903. }
  904. delete projC.property;
  905. }
  906. } else {//未分类的单位工程不进行汇总,只取价格信息
  907. ungroupedTenders.push(proj);
  908. }
  909. //设置分组,单位工程及单项工程分到未分组那
  910. if (proj.projType === projType.tender || proj.projType === projType.engineering) {
  911. rst.ungrouped.push(proj);
  912. } else {
  913. rst.grouped.push(proj);
  914. }
  915. //设置项目类型为来自别人分享
  916. proj.shareType = 'receive';
  917. for (let userData of orgUsersInfo) {
  918. if (proj.userID == userData._id.toString()) {
  919. let userInfo = { name: userData.real_name, mobile: userData.mobile, company: userData.company, email: userData.email };
  920. proj.userInfo = userInfo;
  921. }
  922. }
  923. }
  924. consProjIDs = Array.from(new Set(consProjIDs));
  925. let summaryInfo = await pm_facade.getSummaryInfo(consProjIDs);
  926. let tendersFeeInfo = await pm_facade.getTendersFeeInfo(ungroupedTenders);
  927. rst.summaryInfo = { grouped: summaryInfo, ungrouped: tendersFeeInfo };
  928. }
  929. callback(req, res, 0, 'success', rst);
  930. }
  931. catch (err) {
  932. console.log(err);
  933. callback(req, res, 1, err, null);
  934. }
  935. },
  936. getProjectsByQuery: async function (req, res) {
  937. try {
  938. let data = JSON.parse(req.body.data);
  939. let compilation = req.session.sessionCompilation._id;
  940. let query = data.query;
  941. query.compilation = compilation;
  942. let options = data.options;
  943. let projects = await projectModel.find(query, options);
  944. callback(req, res, 0, 'success', projects);
  945. }
  946. catch (err) {
  947. callback(req, res, 1, err, null);
  948. }
  949. },
  950. getSummaryInfo: async function (req, res) {
  951. try {
  952. let data = JSON.parse(req.body.data);
  953. let summaryInfo = await pm_facade.getSummaryInfo(data.projectIDs);
  954. callback(req, res, 0, 'success', summaryInfo);
  955. }
  956. catch (err) {
  957. callback(req, res, 1, err, null);
  958. }
  959. },
  960. changeFile: async function (req, res) {
  961. try {
  962. let data = JSON.parse(req.body.data);
  963. console.log(data);
  964. await pm_facade.changeFile(data.projects, data.user_id, data.fileID, data.name, data.from, data.type);
  965. callback(req, res, 0, 'success', []);
  966. }
  967. catch (err) {
  968. console.log(err);
  969. callback(req, res, 1, err, null);
  970. }
  971. },
  972. exportProject: async function (req, res) {
  973. let result = {
  974. error: 0
  975. };
  976. try {
  977. let data = { dataString: req.body.data, userID: req.session.sessionUser.id };
  978. result = await redirectToImportServer(data, "exportProject", req);
  979. } catch (err) {
  980. console.log(err);
  981. result.error = 1;
  982. result.message = err.message;
  983. }
  984. res.json(result);
  985. },
  986. importProject: async function (req, res) {
  987. let data = JSON.parse(req.body.data);
  988. let result = {
  989. error: 0
  990. };
  991. try {
  992. data.session = req.session;
  993. result = await redirectToImportServer(data,"importProject",req);
  994. } catch (err) {
  995. console.log(err);
  996. result.error = 1;
  997. result.message = err.message;
  998. }
  999. res.json(result);
  1000. },
  1001. copyConstructionProject: async function (req, res) {
  1002. let data = JSON.parse(req.body.data);
  1003. let result = {
  1004. error: 0
  1005. };
  1006. try {
  1007. data.session = req.session;
  1008. result.data = await redirectToImportServer(data, "copyConstructionProject", req);
  1009. } catch (err) {
  1010. console.log(err);
  1011. result.error = 1;
  1012. result.message = err.message;
  1013. }
  1014. res.json(result);
  1015. },
  1016. importProcessChecking: async function (req, res) {
  1017. let result = {
  1018. error: 0
  1019. };
  1020. try {
  1021. let data = JSON.parse(req.body.data);
  1022. data.userID = req.session.sessionUser.id;
  1023. data.compilationID = req.session.sessionCompilation._id;
  1024. result.data = await pm_facade.importProcessChecking(data);
  1025. } catch (err) {
  1026. console.log(err);
  1027. result.error = 1;
  1028. result.message = err.message;
  1029. }
  1030. res.json(result);
  1031. },
  1032. getUploadToken: function (req, res) {
  1033. let result = {
  1034. error: 0
  1035. };
  1036. try {
  1037. result = pm_facade.uploadToken();
  1038. } catch (err) {
  1039. console.log(err);
  1040. result.error = 1;
  1041. result.message = err.message;
  1042. }
  1043. res.json(result);
  1044. },
  1045. getProjectByGranularity: async function (req, res) {
  1046. try {
  1047. const data = JSON.parse(req.body.data);
  1048. const userID = req.session.sessionUser.id;
  1049. const version = req.session.compilationVersion;
  1050. const projData = await pm_facade.getProjectByGranularity(data.tenderID, data.granularity, data.requestForSummaryInfo, userID, version);
  1051. callback(req, res, 0, 'success', projData);
  1052. } catch (err) {
  1053. callback(req, res, 1, err, null);
  1054. }
  1055. },
  1056. getImportTemplateData: async function (req, res) {
  1057. try {
  1058. const data = JSON.parse(req.body.data);
  1059. const templateData = await pm_facade.getImportTemplateData(req.session.sessionCompilation._id, data.valuationID, data.engineeringID, data.projectCount);
  1060. callback(req, res, 0, 'success', templateData);
  1061. } catch (err) {
  1062. callback(req, res, 1, err, null);
  1063. }
  1064. },
  1065. importInterface: async function (req, res) {
  1066. const data = JSON.parse(req.body.data);
  1067. let result = {
  1068. error: 0
  1069. };
  1070. try {
  1071. data.session = req.session;
  1072. result = await redirectToImportServer(data, "importInterface", req);
  1073. } catch (err) {
  1074. console.log(err);
  1075. result.error = 1;
  1076. result.message = err.message;
  1077. }
  1078. res.json(result);
  1079. },
  1080. };
  1081. async function redirectToImportServer(data, action, req) {
  1082. let importURL = config.getImportURL(process.env.NODE_ENV, req.headers.origin);
  1083. let options = {
  1084. method: 'POST',
  1085. uri: `http://${importURL}/import/${action}`,
  1086. body: data,
  1087. timeout: 220000,
  1088. json: true
  1089. };
  1090. console.log("post import data to:" + options.uri);
  1091. return await rp.post(options);
  1092. }