pm_controller.js 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855
  1. /**
  2. * Created by Mai on 2017/1/18.
  3. */
  4. import UnitPriceFileModel from "../../glj/models/unit_price_file_model";
  5. import moment from 'moment';
  6. import CompilationModel from "../../users/models/compilation_model";
  7. let mongoose = require('mongoose');
  8. let ProjectsData = require('../models/project_model').project;
  9. let labourCoe = require('../../main/facade/labour_coe_facade');
  10. let projType = require('../models/project_model').projType;
  11. let fileType = require('../models/project_model').fileType;
  12. const engineering = require("../../common/const/engineering");
  13. let EngineeringLibModel = require("../../users/models/engineering_lib_model");
  14. let fee_rate_facade = require("../../fee_rates/facade/fee_rates_facade");
  15. let billsModel = require('../../main/models/bills').model;
  16. let rationsModel = require('../../main/models/ration').model;
  17. let projectModel = mongoose.model('projects');
  18. let unitPriceFileModel = mongoose.model('unit_price_file');
  19. let feeRateFileModel = mongoose.model('fee_rate_file');
  20. let asyncTool = require('async');
  21. let pm_facade = require('../facade/pm_facade');
  22. const userModel = mongoose.model('user');
  23. let config = require("../../../config/config.js");
  24. const optionModel = mongoose.model('options');
  25. const stdBillsGuidanceLibModel = mongoose.model('std_billsGuidance_lib');
  26. const fs = require('fs');
  27. const _ = require('lodash');
  28. import SectionTreeDao from '../../complementary_ration_lib/models/sectionTreeModel';
  29. let sectionTreeDao = new SectionTreeDao();
  30. let consts = require('../../main/models/project_consts');
  31. const rationLibModel = mongoose.model('std_ration_lib_map');
  32. const multiparty = require("multiparty");
  33. let logger = require("../../../logs/log_helper").logger;
  34. let rp = require('request-promise');
  35. //统一回调函数
  36. let callback = function(req, res, err, message, data){
  37. res.json({error: err, message: message, data: data});
  38. };
  39. module.exports = {
  40. checkRight: function (req, res) {
  41. if(typeof req.body.data === 'object'){
  42. req.body.data = JSON.stringify(req.body.data);
  43. }
  44. let data = JSON.parse(req.body.data);
  45. if (data.user_id) {
  46. return data.user_id === req.session.sessionUser.id;
  47. } else {
  48. return false;
  49. }
  50. },
  51. checkProjectRight: function (userId, projectId, callback) {
  52. ProjectsData.getProject(projectId).then(async function (result) {
  53. /**
  54. * result._doc.userID(Number): MongoDB
  55. * userId(String): Session.userID
  56. */
  57. let shareInfo = null;
  58. //判断是否是打开分享的项目,分享项目shareInfo不为null
  59. if(userId !== result.userID){
  60. shareInfo = await pm_facade.getShareInfo(userId, result);
  61. }
  62. if ((userId === result.userID || shareInfo) && result._doc.projType === projType.tender) {
  63. callback(true, result, shareInfo);
  64. } else {
  65. callback(false);
  66. }
  67. }).catch(function (err) {
  68. callback(false);
  69. });
  70. },
  71. getProjects: async function(req, res){
  72. await ProjectsData.getUserProjects(req.session.sessionUser.id, req.session.sessionCompilation._id, function(err, message, projects){
  73. if (projects) {
  74. callback(req, res, err, message, projects);
  75. } else {
  76. callback(req, res, err, message, null);
  77. }
  78. });
  79. },
  80. updateProjects: async function (req, res) {
  81. let data = JSON.parse(req.body.data);
  82. await ProjectsData.updateUserProjects(req.session.sessionUser.id, req.session.sessionCompilation._id, req.session.sessionCompilation.name,req.session.sessionCompilation.overWriteUrl, data.updateData, function (err, message, data) {
  83. if (err === 0) {
  84. callback(req, res, err, message, data);
  85. } else {
  86. callback(req, res, err, message, null);
  87. }
  88. });
  89. },
  90. // CSL, 2017-12-14 该方法用于项目属性:提交保存混合型数据,这些数据来自不同的表,包括projects.property、ration、bills、labour_coes.
  91. updateMixDatas: async function(req, res){
  92. let datas = JSON.parse(req.body.data).mixDataArr;
  93. let functions = [];
  94. function updateFunc(model, cod, doc) {
  95. return function (cb) {
  96. model.update(cod, doc, cb);
  97. }
  98. };
  99. function updateLC(){
  100. return function (cb) {
  101. datas.labourCoes.updateData.projectID = datas.projectID;
  102. labourCoe.save(datas.labourCoes.updateData, cb);
  103. }
  104. };
  105. // 项目属性
  106. if (Object.keys(datas.properties).length > 0){
  107. //基本信息特殊处理,更新建设项目
  108. if(datas.properties['property.basicInformation']){
  109. let constructionProject = await pm_facade.getConstructionProject(datas.projectID);
  110. if(constructionProject){
  111. functions.push(updateFunc(projectModel, {ID: constructionProject.ID}, {'property.basicInformation': datas.properties['property.basicInformation']}));
  112. }
  113. delete datas.properties['property.basicInformation'];
  114. }
  115. //建设项目-编制说明,更新建设项目
  116. if (datas.properties['property.compilationIllustrationProject']) {
  117. let constructionProject = await pm_facade.getConstructionProject(datas.projectID);
  118. if (constructionProject) {
  119. functions.push(updateFunc(projectModel, {ID: constructionProject.ID}, {'property.compilationIllustration': datas.properties['property.compilationIllustrationProject']}));
  120. }
  121. delete datas.properties['property.compilationIllustrationProject'];
  122. }
  123. functions.push(updateFunc(projectModel, {ID: datas.projectID}, datas.properties));
  124. };
  125. //选项
  126. if(datas.options && datas.options.updateData){
  127. functions.push(updateFunc(optionModel, {user_id: req.session.sessionUser.id, compilation_id: req.session.sessionCompilation._id}, {'options.GENERALOPTS': datas.options.updateData}));
  128. }
  129. // 人工系数
  130. if (datas.labourCoes&&datas.labourCoes.updateData){
  131. functions.push(updateLC());
  132. };
  133. // 清单:每文档doc只存储一条清单,每条清单都必须定位一次文档,无法合并处理
  134. if (datas.bills && datas.bills.length > 0){
  135. for (let bill of datas.bills){
  136. functions.push(updateFunc(billsModel, {projectID: datas.projectID, ID: bill.ID, deleteInfo: null}, bill));
  137. };
  138. };
  139. // 定额:每文档doc只存储一条定额,每条定额都必须定位一次文档,无法合并处理
  140. if (datas.rations&& datas.rations.length > 0){
  141. for (let ration of datas.rations){
  142. functions.push(updateFunc(rationsModel, {projectID: datas.projectID, ID: ration.ID, deleteInfo: null}, ration));
  143. };
  144. };
  145. asyncTool.parallel(functions, function(err, result){
  146. {
  147. if (!err) {
  148. res.json({error: 0, message: err, data: result});
  149. } else {
  150. res.json({error: 1, message: err, data: null});
  151. }
  152. }
  153. });
  154. },
  155. updateFiles: async function(req, res){
  156. let data = JSON.parse(req.body.data);
  157. let updateDatas = data.updateDatas;
  158. await ProjectsData.udpateUserFiles(req.session.sessionUser.id, updateDatas, function (err, message, data) {
  159. callback(req, res, err, message, data);
  160. });
  161. },
  162. defaultSettings: async function(req, res){
  163. try{
  164. let data = JSON.parse(req.body.data);
  165. let projectID = data.projectID;
  166. let defaultSettingSc = await ProjectsData.defaultSettings(req.session.sessionUser.id, req.session.sessionCompilation._id, projectID);
  167. if(!defaultSettingSc){
  168. throw '恢复失败';
  169. }
  170. res.json({error: 0, message: '恢复成功', data: null});
  171. }
  172. catch(error){
  173. console.log(error);
  174. res.json({error: 1, message: error, data: null});
  175. }
  176. },
  177. /* copyProjects: function (req, res) {
  178. let data = JSON.parse(req.body.data);
  179. ProjectsData.copyUserProjects(req.session.sessionUser.id, req.session.sessionCompilation._id, data.updateData, function (err, message, data) {
  180. if (err === 0) {
  181. callback(req, res, err, message, data);
  182. } else {
  183. callback(req, res, err, message, null);
  184. }
  185. });
  186. },*/
  187. rename: function (req, res) {
  188. let data = JSON.parse(req.body.data);
  189. ProjectsData.rename(req.session.sessionUser.id, req.session.sessionCompilation._id, data, function (err, message) {
  190. callback(req, res, err, message, null);
  191. });
  192. },
  193. //project getData接口
  194. getData: function(projectID, callback) {
  195. projectModel.findOne({$or: [{deleteInfo: null}, {'deleteInfo.deleted': false}], ID: projectID}, '-_id').then(async function (project) {
  196. if (!project) {
  197. callback('', consts.projectConst.PROJECT_INFO, {});
  198. }
  199. let engineeringLibModel = new EngineeringLibModel();
  200. let engineeringInfo = project !== null && project.property.engineering_id !== undefined ?
  201. await engineeringLibModel.getEngineering(project.property.engineering_id) : null;
  202. //查找定额库的定额库编码
  203. if (Array.isArray(engineeringInfo.ration_lib)) {
  204. let rationLibIDs = engineeringInfo.ration_lib.map(data => data.id);
  205. let rationLibs = await rationLibModel.find({ID: {$in: rationLibIDs}}, 'ID libCode');
  206. for (let rationLib of rationLibs) {
  207. let lib = engineeringInfo.ration_lib.find(data => data.id == rationLib.ID);
  208. lib.libCode = rationLib.libCode;
  209. }
  210. }
  211. let projInfo = project._doc;
  212. if (engineeringInfo !== null) {
  213. if(engineeringInfo.billsGuidance_lib){
  214. for(let billsGuidanceLib of engineeringInfo.billsGuidance_lib){
  215. let stdBillsGuidanceLib = await stdBillsGuidanceLibModel.findOne({ID: billsGuidanceLib.id});
  216. if(stdBillsGuidanceLib){
  217. billsGuidanceLib.type = stdBillsGuidanceLib.type ? stdBillsGuidanceLib.type : 1;
  218. }
  219. }
  220. }
  221. projInfo.engineeringInfo = engineeringInfo;
  222. }
  223. //读取建设项目的项目属性
  224. let constructionProperty = await ProjectsData.getConstructionProperty(projectID);
  225. //基本信息
  226. projInfo.property.basicInformation = constructionProperty && constructionProperty.basicInformation ? constructionProperty.basicInformation : [];
  227. //编制说明
  228. projInfo.property.compilationIllustrationProject = constructionProperty && constructionProperty.compilationIllustration ? constructionProperty.compilationIllustration : '';
  229. //获取单位工程完整目录结构
  230. let fullPath = await pm_facade.getFullPath(projectID);
  231. projInfo.fullPath = fullPath;
  232. callback('', consts.projectConst.PROJECT_INFO, project);
  233. }, function (err) {
  234. callback(err, consts.projectConst.PROJECT_INFO, {});
  235. });
  236. },
  237. getProject: function(req, res){
  238. let data = JSON.parse(req.body.data);
  239. let projectID = data.proj_id;
  240. ProjectsData.getUserProject(req.session.sessionUser.id, data.proj_id, async function(err, message, data){
  241. if (err === 0) {
  242. let engineeringLibModel = new EngineeringLibModel();
  243. let engineeringInfo = data !== null && data.property.engineering_id !== undefined ?
  244. await engineeringLibModel.getEngineering(data.property.engineering_id) : null;
  245. let strData = JSON.stringify(data);
  246. let projInfo = JSON.parse(strData);
  247. if (engineeringInfo !== null) {
  248. if(engineeringInfo.billsGuidance_lib){
  249. for(let billsGuidanceLib of engineeringInfo.billsGuidance_lib){
  250. let stdBillsGuidanceLib = await stdBillsGuidanceLibModel.findOne({ID: billsGuidanceLib.id});
  251. if(stdBillsGuidanceLib){
  252. billsGuidanceLib.type = stdBillsGuidanceLib.type ? stdBillsGuidanceLib.type : 1;
  253. }
  254. }
  255. }
  256. projInfo.engineeringInfo = engineeringInfo;
  257. }
  258. //读取建设项目的项目属性
  259. let constructionProperty = await ProjectsData.getConstructionProperty(projectID);
  260. console.log(projectID);
  261. console.log(constructionProperty);
  262. //基本信息
  263. projInfo.property.basicInformation = constructionProperty && constructionProperty.basicInformation ? constructionProperty.basicInformation : [];
  264. //编制说明
  265. projInfo.property.compilationIllustrationProject = constructionProperty && constructionProperty.compilationIllustration ? constructionProperty.compilationIllustration : '';
  266. //获取单位工程完整目录结构
  267. let fullPath = await pm_facade.getFullPath(projectID);
  268. projInfo.fullPath = fullPath;
  269. callback(req, res, err, message, projInfo);
  270. } else {
  271. callback(req, res, err, message, null);
  272. }
  273. });
  274. },
  275. beforeOpenProject: function (req, res) {
  276. let data = JSON.parse(req.body.data);
  277. ProjectsData.beforeOpenProject(req.session.sessionUser.id, data.proj_id, data.updateData, function (err, message, data) {
  278. callback(req, res, err, message, data);
  279. });
  280. },
  281. getNewProjectID: function (req, res) {
  282. let data = JSON.parse(req.body.data);
  283. ProjectsData.getNewProjectID(data.count, function (err, message, data) {
  284. callback(req, res, err, message, data);
  285. });
  286. },
  287. // 项目管理首页
  288. index: async function(request, response) {
  289. // 获取编办信息
  290. let sessionCompilation = request.session.sessionCompilation;
  291. if (sessionCompilation === undefined ||sessionCompilation ===null) {
  292. return response.redirect('/logout');
  293. }
  294. let compilationModel = new CompilationModel();
  295. //更新编办信息
  296. let compilationData = await compilationModel.getCompilationById(sessionCompilation._id);
  297. request.session.sessionCompilation = compilationData;
  298. sessionCompilation = request.session.sessionCompilation;
  299. //更新用户的使用过的费用定额列表
  300. let isFirst = await pm_facade.isFirst(request.session.sessionUser.id, compilationData._id.toString());
  301. // 清单计价
  302. let billValuation = sessionCompilation.bill_valuation !== undefined ?
  303. sessionCompilation.bill_valuation : [];
  304. // 获取标准库数据
  305. let engineeringLibModel = new EngineeringLibModel();
  306. billValuation = await engineeringLibModel.getLib(billValuation);
  307. // 定额计价
  308. let rationValuation = sessionCompilation.ration_valuation !== undefined ?
  309. sessionCompilation.ration_valuation : [];
  310. rationValuation = await engineeringLibModel.getLib(rationValuation);
  311. let absoluteUrl = compilationData.overWriteUrl ? request.app.locals.rootDir + compilationData.overWriteUrl : request.app.locals.rootDir;
  312. let overWriteUrl = fs.existsSync(absoluteUrl) && fs.statSync(absoluteUrl).isFile()? compilationData.overWriteUrl : null;
  313. //let valuationOpts = billValuation.map(data => {return {name: data.name, id: data.id}}).reverse();
  314. //欢迎页显示控制
  315. let [isShow,context] = await pm_facade.getWelcomeInfo(sessionCompilation._id,request.session.sessionUser);
  316. let renderData = {
  317. isFirst: isFirst,
  318. isShow:isShow,
  319. context:context,
  320. userAccount: request.session.userAccount,
  321. userID: request.session.sessionUser.id,
  322. compilationData: JSON.stringify(sessionCompilation),
  323. overWriteUrl: overWriteUrl,
  324. billValuation: JSON.stringify(billValuation.reverse()), // 按最新排序
  325. rationValuation: JSON.stringify(rationValuation),
  326. engineeringList: JSON.stringify(engineering.List),
  327. compilationName: sessionCompilation.name,
  328. versionName: request.session.compilationVersion,
  329. LicenseKey:config.getLicenseKey(process.env.NODE_ENV)
  330. };
  331. response.render('building_saas/pm/html/project-management.html', renderData);
  332. },
  333. //第一次进入该费用定额时准备的初始数据
  334. prepareInitialData: async function(request, response) {
  335. try {
  336. let sessionCompilation = request.session.sessionCompilation;
  337. await pm_facade.prepareInitialData(request.session.sessionUser.id, sessionCompilation._id, sessionCompilation.example);
  338. callback(request, response, 0, 'success', null);
  339. } catch(err) {
  340. callback(request, response, 1, err, null);
  341. }
  342. },
  343. // 获取单价文件列表
  344. getUnitFileList: async function(request, response) {
  345. let data = request.body.data;
  346. try {
  347. data = JSON.parse(data);
  348. let projectId = data.parentID !== undefined ? data.parentID : 0;
  349. if (isNaN(projectId) && projectId <= 0) {
  350. throw {msg: 'id数据有误!', err: 1};
  351. }
  352. /*// 获取对应建设项目下所有的单位工程id
  353. let idList = await ProjectsData.getTenderByProjectId(projectId);
  354. if (idList.length <= 0) {
  355. throw {msg: '不存在对应单位工程', err: 0};
  356. }*/
  357. // 获取对应的单价文件
  358. let unitPriceFileModel = new UnitPriceFileModel();
  359. let unitPriceFileData = await unitPriceFileModel.getDataByRootProject(projectId);
  360. if (unitPriceFileData === null) {
  361. throw {msg: '不存在对应单价文件', err: 0};
  362. }
  363. // 整理数据
  364. let unitPriceFileList = [];
  365. for (let unitPriceFile of unitPriceFileData) {
  366. let tmp = {
  367. name: unitPriceFile.name,
  368. id: unitPriceFile.id
  369. };
  370. unitPriceFileList.push(tmp);
  371. }
  372. callback(request, response, 0, '', unitPriceFileList);
  373. } catch (error) {
  374. console.log(error);
  375. let responseData = error.err === 1 ? null : [];
  376. callback(request, response, error.err, error.msg, responseData);
  377. }
  378. },
  379. getFeeRateFileList:async function(request, response) {
  380. let data = request.body.data;
  381. try {
  382. data = JSON.parse(data);
  383. let projectId = data.parentID !== undefined ? data.parentID : 0;
  384. if (isNaN(projectId) && projectId <= 0) {
  385. throw {msg: 'id数据有误!', err: 1};
  386. }
  387. // 获取对应建设项目下所有的单位工程id
  388. let feeRateFileList = await fee_rate_facade.getFeeRatesByProject(projectId);
  389. callback(request, response, 0, '',feeRateFileList );
  390. } catch (error) {
  391. console.log(error);
  392. let responseData = error.err === 1 ? null : [];
  393. callback(request, response, error.err, error.msg, responseData);
  394. }
  395. },
  396. getGCDatas: async function(request, response) {
  397. let userID = request.session.sessionUser.id;
  398. let compilatoinId = request.session.sessionCompilation._id;
  399. let rst = [];
  400. let _projs = Object.create(null), _engs = Object.create(null), prefix = 'ID_';
  401. try{
  402. let gc_unitPriceFiles = await ProjectsData.getGCFiles(fileType.unitPriceFile, userID);
  403. let gc_feeRateFiles = await ProjectsData.getGCFiles(fileType.feeRateFile, userID);
  404. let gc_tenderFiles = await ProjectsData.getGCFiles(projType.tender, userID);
  405. for(let i = 0, len = gc_unitPriceFiles.length; i < len; i++){
  406. let gc_uf = gc_unitPriceFiles[i];
  407. let theProj = _projs[prefix + gc_uf.root_project_id] || null;
  408. if(!theProj){
  409. let tempProj = await ProjectsData.getProjectsByIds(userID, compilatoinId, [gc_uf.root_project_id]);
  410. if(tempProj.length > 0 && tempProj[0].projType !== projType.folder){
  411. theProj = _projs[prefix + gc_uf.root_project_id] = tempProj[0]._doc;
  412. buildProj(theProj);
  413. }
  414. }
  415. if(theProj){
  416. theProj.unitPriceFiles.push(gc_uf);
  417. }
  418. }
  419. for(let i = 0, len = gc_feeRateFiles.length; i < len; i++){
  420. let gc_ff = gc_feeRateFiles[i];
  421. let theProj = _projs[prefix + gc_ff.rootProjectID] || null;
  422. if(!theProj){
  423. let tempProj = await ProjectsData.getProjectsByIds(userID, compilatoinId, [gc_ff.rootProjectID]);
  424. if(tempProj.length > 0 && tempProj[0].projType !== projType.folder){
  425. theProj = _projs[prefix + gc_ff.rootProjectID] = tempProj[0]._doc;
  426. buildProj(theProj);
  427. }
  428. }
  429. if(theProj) {
  430. theProj.feeRateFiles.push(gc_ff);
  431. }
  432. }
  433. if(gc_tenderFiles.length > 0){
  434. for(let i = 0, len = gc_tenderFiles.length; i < len; i++){
  435. let gc_t = gc_tenderFiles[i];
  436. let theEng = _engs[prefix + gc_t.ParentID] || null;
  437. if(!theEng){
  438. let tempEngs = await ProjectsData.getProjectsByIds(userID, compilatoinId, [gc_t.ParentID]);
  439. if(tempEngs.length > 0 && tempEngs[0].projType === projType.engineering){
  440. theEng = _engs[prefix + gc_t.ParentID] = tempEngs[0]._doc;
  441. theEng.children = [];
  442. }
  443. }
  444. if(theEng) {
  445. theEng.children.push(gc_t);
  446. let theProj = _projs[prefix + theEng.ParentID] || null;
  447. if(!theProj){
  448. let tempProj = await ProjectsData.getProjectsByIds(userID, compilatoinId, [theEng.ParentID]);
  449. if(tempProj.length > 0 && tempProj[0].projType === projType.project){
  450. theProj = _projs[prefix + theEng.ParentID] = tempProj[0]._doc;
  451. buildProj(theProj);
  452. }
  453. }
  454. if(theProj) {
  455. let isExist = false;
  456. for(let j = 0, jLen = theProj.children.length; j < jLen; j++){
  457. if(theProj.children[j].ID === theEng.ID){
  458. isExist = true;
  459. break;
  460. }
  461. }
  462. if(!isExist){
  463. theProj.children.push(theEng);
  464. }
  465. }
  466. }
  467. }
  468. }
  469. for(let i in _projs){
  470. rst.push(_projs[i]);
  471. }
  472. function buildProj(proj){
  473. proj.children = [];
  474. proj.unitPriceFiles = [];
  475. proj.feeRateFiles = [];
  476. }
  477. callback(request, response, 0, 'success', rst);
  478. }
  479. catch (error){
  480. callback(request, response, true, error, null);
  481. }
  482. },
  483. recGC: function(request, response){
  484. let userID = request.session.sessionUser.id,
  485. compilationId = request.session.sessionCompilation._id;
  486. let data = JSON.parse(request.body.data);
  487. let nodes = data.nodes;
  488. ProjectsData.recGC(userID, compilationId, nodes, function (err, msg, data) {
  489. callback(request, response, err, msg, data);
  490. });
  491. },
  492. delGC: async function(request, response){
  493. let data = JSON.parse(request.body.data);
  494. let delDatas = data.delDatas;
  495. let bulkProjs = [], bulkUFs = [], bulkFFs = [];
  496. try{
  497. for(let data of delDatas){
  498. if(data.updateType === 'Project'){
  499. bulkProjs.push({updateOne: {filter: {ID: data.ID}, update: {'deleteInfo.completeDeleted': true}}});
  500. }
  501. else if(data.updateType === fileType.unitPriceFile){
  502. bulkUFs.push({updateOne: {filter: {id: data.ID}, update: {'deleteInfo.completeDeleted': true}}});
  503. }
  504. else{
  505. bulkFFs.push({updateOne: {filter: {ID: data.ID}, update: {'deleteInfo.completeDeleted': true}}});
  506. }
  507. }
  508. if(bulkProjs.length > 0){
  509. await projectModel.bulkWrite(bulkProjs);
  510. }
  511. if(bulkUFs.length > 0){
  512. await unitPriceFileModel.bulkWrite(bulkUFs);
  513. }
  514. if(bulkFFs.length > 0){
  515. await feeRateFileModel.bulkWrite(bulkFFs);
  516. }
  517. callback(request, response, 0, 'success', null);
  518. } catch(err){
  519. callback(request, response, 1, err, null);
  520. }
  521. },
  522. moveProject:async function(req,res){
  523. let result={
  524. error:0
  525. };
  526. try {
  527. let data = req.body.data;
  528. let rdata= await pm_facade.moveProject(data);
  529. result.data= rdata;
  530. }catch (err){
  531. console.log(err);
  532. result.error=1;
  533. result.message = err.message;
  534. }
  535. res.json(result);
  536. },
  537. copyProjects:async function (req, res) {
  538. let result={
  539. error:0
  540. };
  541. try {
  542. let data = {dataString:req.body.data,userID:req.session.sessionUser.id,compilationID:req.session.sessionCompilation._id};
  543. result = await redirectToImportServer(data,"copyProject",req);
  544. }catch (err){
  545. console.log(err);
  546. result.error=1;
  547. result.message = err.message;
  548. }
  549. res.json(result);
  550. },
  551. projectShareInfo: async function(req, res){
  552. try{
  553. let data = JSON.parse(req.body.data);
  554. let shareInfo = await projectModel.findOne({ID: data.projectID, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]}, '-_id shareInfo');
  555. callback(req, res, 0, 'success', shareInfo);
  556. }
  557. catch (err){
  558. callback(req, res, 1, err, null);
  559. }
  560. },
  561. share: async function(req, res){
  562. try{
  563. let data = JSON.parse(req.body.data);
  564. let shareDate = moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'),
  565. shareUserIDs = [];
  566. for (let data of data.shareData) {
  567. shareUserIDs.push(data.userID);
  568. data.shareDate = shareDate;
  569. }
  570. //添加分享
  571. if(data.type === 'create'){
  572. //新增
  573. for (let sData of data.shareData) {
  574. await projectModel.update({ID: data.projectID, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]}, {$addToSet: {shareInfo: sData}});
  575. }
  576. } else if (data.type === 'update') {
  577. await projectModel.update({ID: data.projectID, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]}, {$set: {shareInfo: data.shareData}});
  578. }
  579. //取消分享
  580. else {
  581. await projectModel.update({ID: data.projectID, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]}, {$pull: {shareInfo: {userID: {$in: shareUserIDs}}}});
  582. }
  583. callback(req, res, 0, 'success', data.shareData);
  584. }
  585. catch (err){
  586. callback(req, res, 1, err, null);
  587. }
  588. },
  589. receiveProjects: async function(req, res) {
  590. try {
  591. let rst = {grouped: [], ungrouped: [], summaryInfo: null};
  592. let userID = req.session.sessionUser.id;
  593. let receiveProjects = await projectModel.find({
  594. $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}], compilation: req.session.sessionCompilation._id, 'shareInfo.userID': userID}, '-_id');
  595. //设置原项目用户信息
  596. if(receiveProjects.length > 0){
  597. let orgUserIDs = [];
  598. for(let proj of receiveProjects){
  599. orgUserIDs.push(proj.userID);
  600. if (proj.projType === projType.tender) {
  601. //设置工程专业
  602. proj._doc.feeStandardName = proj.property.feeStandardName || '';
  603. //设置计税方法
  604. proj._doc.taxType = proj.property.taxType;
  605. }
  606. delete proj._doc.property;
  607. }
  608. orgUserIDs = Array.from(new Set(orgUserIDs));
  609. let userObjIDs = [];
  610. for(let uID of orgUserIDs){
  611. userObjIDs.push(mongoose.Types.ObjectId(uID));
  612. }
  613. let orgUsersInfo = await userModel.find({_id: {$in : userObjIDs}});
  614. //建设项目
  615. let consProjIDs = [],
  616. ungroupedTenders = [];
  617. for(let proj of receiveProjects){
  618. if (proj.projType === projType.project) {
  619. consProjIDs.push(proj.ID);
  620. }
  621. //获取分享项目子项
  622. if (proj.projType !== projType.tender) {
  623. proj._doc.children = await pm_facade.getPosterityProjects([proj.ID]);
  624. for (let projC of proj._doc.children) {
  625. if (projC.projType === projType.project) {
  626. consProjIDs.push(projC.ID);
  627. } else if (projC.projType === projType.tender) {
  628. //设置工程专业
  629. projC._doc.feeStandardName = projC.property.feeStandardName || '';
  630. //设置计税方法
  631. projC._doc.taxType = projC.property.taxType;
  632. if (proj.projType === projType.engineering) {
  633. ungroupedTenders.push(projC._doc);
  634. }
  635. }
  636. delete projC._doc.property;
  637. }
  638. } else {//未分类的单位工程不进行汇总,只取价格信息
  639. ungroupedTenders.push(proj._doc);
  640. }
  641. //设置分组,单位工程及单项工程分到未分组那
  642. if (proj.projType === projType.tender || proj.projType === projType.engineering) {
  643. rst.ungrouped.push(proj);
  644. } else {
  645. rst.grouped.push(proj);
  646. }
  647. //设置项目类型为来自别人分享
  648. proj._doc.shareType = 'receive';
  649. for(let userData of orgUsersInfo){
  650. if(proj.userID == userData._id.toString()){
  651. let userInfo = {name: userData.real_name, mobile: userData.mobile, company: userData.company, email: userData.email};
  652. proj._doc.userInfo = userInfo;
  653. }
  654. }
  655. }
  656. consProjIDs = Array.from(new Set(consProjIDs));
  657. let summaryInfo = await pm_facade.getSummaryInfo(consProjIDs);
  658. let tendersFeeInfo = await pm_facade.getTendersFeeInfo(ungroupedTenders);
  659. rst.summaryInfo = {grouped: summaryInfo, ungrouped: tendersFeeInfo};
  660. }
  661. callback(req, res, 0, 'success', rst);
  662. }
  663. catch (err){
  664. console.log(err);
  665. callback(req, res, 1, err, null);
  666. }
  667. },
  668. getProjectsByQuery: async function (req, res) {
  669. try{
  670. let data = JSON.parse(req.body.data);
  671. let compilation = req.session.sessionCompilation._id;
  672. let query = data.query;
  673. query.compilation = compilation;
  674. let options = data.options;
  675. let projects = await projectModel.find(query, options);
  676. callback(req, res, 0, 'success', projects);
  677. }
  678. catch (err){
  679. callback(req, res, 1, err, null);
  680. }
  681. },
  682. getSummaryInfo: async function(req, res){
  683. try{
  684. let data = JSON.parse(req.body.data);
  685. let summaryInfo = await pm_facade.getSummaryInfo(data.projectIDs);
  686. callback(req, res, 0, 'success', summaryInfo);
  687. }
  688. catch (err){
  689. callback(req, res, 1, err, null);
  690. }
  691. },
  692. changeFile:async function(req,res){
  693. try{
  694. let data = JSON.parse(req.body.data);
  695. console.log(data);
  696. await pm_facade.changeFile(data.projects,data.user_id,data.fileID,data.name,data.from,data.type);
  697. callback(req, res, 0, 'success', []);
  698. }
  699. catch (err){
  700. console.log(err);
  701. callback(req, res, 1, err, null);
  702. }
  703. },
  704. exportProject:async function(req,res){
  705. let result={
  706. error:0
  707. };
  708. try {
  709. let data = {dataString:req.body.data,userID:req.session.sessionUser.id};
  710. result = await redirectToImportServer(data,"exportProject",req);
  711. }catch (err){
  712. console.log(err);
  713. result.error=1;
  714. result.message = err.message;
  715. }
  716. res.json(result);
  717. },
  718. importProject:async function(req,res){
  719. let form = new multiparty.Form({uploadDir: './tmp'});
  720. let path = "";
  721. form.parse(req, async function (err, fields, files) {
  722. try {
  723. console.log(fields);
  724. const file = typeof files.file !== 'undefined' ? files.file[0] : null;
  725. if (err || !file) {
  726. throw '上传失败。';
  727. };
  728. path = file.path;
  729. let data = fs.readFileSync(file.path,'utf-8');
  730. let body = {data: data, fields:fields, session:req.session};
  731. let result = await redirectToImportServer(body,"importProject",req);
  732. res.json(result);
  733. }catch (e){
  734. console.log(e);
  735. res.json({error:1,msg:"导入失败请检查文件!"})
  736. }finally {
  737. fs.unlinkSync(path);
  738. }
  739. })
  740. },
  741. getBasicInfo: async function(req, res) {
  742. try {
  743. let data = JSON.parse(req.body.data);
  744. let infoLib = await pm_facade.getBasicInfo(req.session.sessionCompilation._id, data.fileKind);
  745. callback(req, res, 0, 'success', infoLib ? infoLib.info : []);
  746. } catch (err) {
  747. console.log(err);
  748. callback(req, res, 1, err, []);
  749. }
  750. },
  751. getProjectFeature: async function(req, res) {
  752. try {
  753. let data = JSON.parse(req.body.data);
  754. let featureLib = await pm_facade.getProjectFeature(data.valuationID, data.engineeringName, data.feeName);
  755. //工程专业设置为费用标准名称
  756. if (featureLib) {
  757. let engData = featureLib.feature.find(function (d) {
  758. return d.key === 'engineering';
  759. });
  760. if (engData) {
  761. engData.value = data.feeName;
  762. }
  763. }
  764. callback(req, res, 0, 'success', featureLib ? featureLib.feature : []);
  765. } catch (err) {
  766. console.log(err);
  767. callback(req, res, 1, err, []);
  768. }
  769. },
  770. getProjectByGranularity: async function(req, res) {
  771. try {
  772. let data = JSON.parse(req.body.data);
  773. let projData = await pm_facade.getProjectByGranularity(data.tenderID, data.granularity, req.session.sessionUser.id, req.session.compilationVersion);
  774. callback(req, res, 0, 'success', projData);
  775. } catch (err) {
  776. callback(req, res, 1, err, null);
  777. }
  778. },
  779. getProjectPlaceholder: async function(req, res) {
  780. let data = JSON.parse(req.body.data);
  781. try {
  782. let countRst = await pm_facade.getProjectPlaceholder(data);
  783. callback(req, res, 0, 'succes', countRst);
  784. } catch (err) {
  785. console.log(err);
  786. callback(req, res, 1, err, null);
  787. }
  788. },
  789. importInterface: async function(req, res) {
  790. logger.info(`${req.ip} importInterface`);
  791. const uploadOption = {
  792. uploadDir: './public'
  793. };
  794. let uploadFullName = '';
  795. const form = new multiparty.Form(uploadOption);
  796. form.parse(req, async function(err, fields, files) {
  797. try {
  798. let file = files.file && files.file.length ? files.file[0] : null;
  799. if (!file) {
  800. throw '无有效数据';
  801. }
  802. uploadFullName = file.path;
  803. //获取源数据
  804. let srcStr = fs.readFileSync(file.path, 'utf8');
  805. if (!srcStr) {
  806. throw '无有效数据'
  807. }
  808. let importData = JSON.parse(srcStr);
  809. fs.unlinkSync(file.path);
  810. let projectData = await pm_facade.importProject(importData, req.session.sessionUser.id, req.session.sessionCompilation._id);
  811. callback(req, res, 0, '', projectData);
  812. } catch (err) {
  813. console.log(err);
  814. if(uploadFullName && fs.existsSync(uploadFullName)){
  815. fs.unlinkSync(uploadFullName);
  816. }
  817. callback(req, res, 1, err, null);
  818. }
  819. });
  820. }
  821. };
  822. async function redirectToImportServer(data,action,req) {
  823. let importURL = config.getImportURL(process.env.NODE_ENV,req.headers.origin);
  824. let options = {
  825. method: 'POST',
  826. uri: `http://${importURL}/import/${action}`,
  827. body: data,
  828. timeout:220000,
  829. json: true
  830. };
  831. console.log("post import data to:"+options.uri);
  832. return await rp.post(options);
  833. }