pm_controller.js 51 KB

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