pm_controller.js 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884
  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 renderData = {
  314. isFirst: isFirst,
  315. userAccount: request.session.userAccount,
  316. userID: request.session.sessionUser.id,
  317. compilationData: JSON.stringify(sessionCompilation),
  318. overWriteUrl: overWriteUrl,
  319. billValuation: JSON.stringify(billValuation.reverse()), // 按最新排序
  320. rationValuation: JSON.stringify(rationValuation),
  321. engineeringList: JSON.stringify(engineering.List),
  322. compilationName: sessionCompilation.name,
  323. versionName: request.session.compilationVersion,
  324. LicenseKey:config.getLicenseKey(process.env.NODE_ENV)
  325. };
  326. response.render('building_saas/pm/html/project-management.html', renderData);
  327. },
  328. //第一次进入该费用定额时准备的初始数据
  329. prepareInitialData: async function(request, response) {
  330. try {
  331. let sessionCompilation = request.session.sessionCompilation;
  332. await pm_facade.prepareInitialData(request.session.sessionUser.id, sessionCompilation._id, sessionCompilation.example);
  333. callback(request, response, 0, 'success', null);
  334. } catch(err) {
  335. callback(request, response, 1, err, null);
  336. }
  337. },
  338. // 获取单价文件列表
  339. getUnitFileList: async function(request, response) {
  340. let data = request.body.data;
  341. try {
  342. data = JSON.parse(data);
  343. let projectId = data.parentID !== undefined ? data.parentID : 0;
  344. if (isNaN(projectId) && projectId <= 0) {
  345. throw {msg: 'id数据有误!', err: 1};
  346. }
  347. /*// 获取对应建设项目下所有的单位工程id
  348. let idList = await ProjectsData.getTenderByProjectId(projectId);
  349. if (idList.length <= 0) {
  350. throw {msg: '不存在对应单位工程', err: 0};
  351. }*/
  352. // 获取对应的单价文件
  353. let unitPriceFileModel = new UnitPriceFileModel();
  354. let unitPriceFileData = await unitPriceFileModel.getDataByRootProject(projectId);
  355. if (unitPriceFileData === null) {
  356. throw {msg: '不存在对应单价文件', err: 0};
  357. }
  358. // 整理数据
  359. let unitPriceFileList = [];
  360. for (let unitPriceFile of unitPriceFileData) {
  361. let tmp = {
  362. name: unitPriceFile.name,
  363. id: unitPriceFile.id
  364. };
  365. unitPriceFileList.push(tmp);
  366. }
  367. callback(request, response, 0, '', unitPriceFileList);
  368. } catch (error) {
  369. console.log(error);
  370. let responseData = error.err === 1 ? null : [];
  371. callback(request, response, error.err, error.msg, responseData);
  372. }
  373. },
  374. getFeeRateFileList:async function(request, response) {
  375. let data = request.body.data;
  376. try {
  377. data = JSON.parse(data);
  378. let projectId = data.parentID !== undefined ? data.parentID : 0;
  379. if (isNaN(projectId) && projectId <= 0) {
  380. throw {msg: 'id数据有误!', err: 1};
  381. }
  382. // 获取对应建设项目下所有的单位工程id
  383. let feeRateFileList = await fee_rate_facade.getFeeRatesByProject(projectId);
  384. callback(request, response, 0, '',feeRateFileList );
  385. } catch (error) {
  386. console.log(error);
  387. let responseData = error.err === 1 ? null : [];
  388. callback(request, response, error.err, error.msg, responseData);
  389. }
  390. },
  391. getGCDatas: async function(request, response) {
  392. let userID = request.session.sessionUser.id;
  393. let compilatoinId = request.session.sessionCompilation._id;
  394. let rst = [];
  395. let _projs = Object.create(null), _engs = Object.create(null), prefix = 'ID_';
  396. try{
  397. let gc_unitPriceFiles = await ProjectsData.getGCFiles(fileType.unitPriceFile, userID);
  398. let gc_feeRateFiles = await ProjectsData.getGCFiles(fileType.feeRateFile, userID);
  399. let gc_tenderFiles = await ProjectsData.getGCFiles(projType.tender, userID);
  400. for(let i = 0, len = gc_unitPriceFiles.length; i < len; i++){
  401. let gc_uf = gc_unitPriceFiles[i];
  402. let theProj = _projs[prefix + gc_uf.root_project_id] || null;
  403. if(!theProj){
  404. let tempProj = await ProjectsData.getProjectsByIds(userID, compilatoinId, [gc_uf.root_project_id]);
  405. if(tempProj.length > 0 && tempProj[0].projType !== projType.folder){
  406. theProj = _projs[prefix + gc_uf.root_project_id] = tempProj[0]._doc;
  407. buildProj(theProj);
  408. }
  409. }
  410. if(theProj){
  411. theProj.unitPriceFiles.push(gc_uf);
  412. }
  413. }
  414. for(let i = 0, len = gc_feeRateFiles.length; i < len; i++){
  415. let gc_ff = gc_feeRateFiles[i];
  416. let theProj = _projs[prefix + gc_ff.rootProjectID] || null;
  417. if(!theProj){
  418. let tempProj = await ProjectsData.getProjectsByIds(userID, compilatoinId, [gc_ff.rootProjectID]);
  419. if(tempProj.length > 0 && tempProj[0].projType !== projType.folder){
  420. theProj = _projs[prefix + gc_ff.rootProjectID] = tempProj[0]._doc;
  421. buildProj(theProj);
  422. }
  423. }
  424. if(theProj) {
  425. theProj.feeRateFiles.push(gc_ff);
  426. }
  427. }
  428. if(gc_tenderFiles.length > 0){
  429. for(let i = 0, len = gc_tenderFiles.length; i < len; i++){
  430. let gc_t = gc_tenderFiles[i];
  431. let theEng = _engs[prefix + gc_t.ParentID] || null;
  432. if(!theEng){
  433. let tempEngs = await ProjectsData.getProjectsByIds(userID, compilatoinId, [gc_t.ParentID]);
  434. if(tempEngs.length > 0 && tempEngs[0].projType === projType.engineering){
  435. theEng = _engs[prefix + gc_t.ParentID] = tempEngs[0]._doc;
  436. theEng.children = [];
  437. }
  438. }
  439. if(theEng) {
  440. theEng.children.push(gc_t);
  441. let theProj = _projs[prefix + theEng.ParentID] || null;
  442. if(!theProj){
  443. let tempProj = await ProjectsData.getProjectsByIds(userID, compilatoinId, [theEng.ParentID]);
  444. if(tempProj.length > 0 && tempProj[0].projType === projType.project){
  445. theProj = _projs[prefix + theEng.ParentID] = tempProj[0]._doc;
  446. buildProj(theProj);
  447. }
  448. }
  449. if(theProj) {
  450. let isExist = false;
  451. for(let j = 0, jLen = theProj.children.length; j < jLen; j++){
  452. if(theProj.children[j].ID === theEng.ID){
  453. isExist = true;
  454. break;
  455. }
  456. }
  457. if(!isExist){
  458. theProj.children.push(theEng);
  459. }
  460. }
  461. }
  462. }
  463. }
  464. for(let i in _projs){
  465. rst.push(_projs[i]);
  466. }
  467. function buildProj(proj){
  468. proj.children = [];
  469. proj.unitPriceFiles = [];
  470. proj.feeRateFiles = [];
  471. }
  472. callback(request, response, 0, 'success', rst);
  473. }
  474. catch (error){
  475. callback(request, response, true, error, null);
  476. }
  477. },
  478. recGC: function(request, response){
  479. let userID = request.session.sessionUser.id,
  480. compilationId = request.session.sessionCompilation._id;
  481. let data = JSON.parse(request.body.data);
  482. let nodes = data.nodes;
  483. ProjectsData.recGC(userID, compilationId, nodes, function (err, msg, data) {
  484. callback(request, response, err, msg, data);
  485. });
  486. },
  487. delGC: async function(request, response){
  488. let data = JSON.parse(request.body.data);
  489. let delDatas = data.delDatas;
  490. let bulkProjs = [], bulkUFs = [], bulkFFs = [];
  491. try{
  492. for(let data of delDatas){
  493. if(data.updateType === 'Project'){
  494. bulkProjs.push({updateOne: {filter: {ID: data.ID}, update: {'deleteInfo.completeDeleted': true}}});
  495. }
  496. else if(data.updateType === fileType.unitPriceFile){
  497. bulkUFs.push({updateOne: {filter: {id: data.ID}, update: {'deleteInfo.completeDeleted': true}}});
  498. }
  499. else{
  500. bulkFFs.push({updateOne: {filter: {ID: data.ID}, update: {'deleteInfo.completeDeleted': true}}});
  501. }
  502. }
  503. if(bulkProjs.length > 0){
  504. await projectModel.bulkWrite(bulkProjs);
  505. }
  506. if(bulkUFs.length > 0){
  507. await unitPriceFileModel.bulkWrite(bulkUFs);
  508. }
  509. if(bulkFFs.length > 0){
  510. await feeRateFileModel.bulkWrite(bulkFFs);
  511. }
  512. callback(request, response, 0, 'success', null);
  513. } catch(err){
  514. callback(request, response, 1, err, null);
  515. }
  516. },
  517. moveProject:async function(req,res){
  518. let result={
  519. error:0
  520. };
  521. try {
  522. let data = req.body.data;
  523. let rdata= await pm_facade.moveProject(data);
  524. result.data= rdata;
  525. }catch (err){
  526. console.log(err);
  527. result.error=1;
  528. result.message = err.message;
  529. }
  530. res.json(result);
  531. },
  532. copyProjects:async function (req, res) {
  533. let result={
  534. error:0
  535. };
  536. try {
  537. let data = {dataString:req.body.data,userID:req.session.sessionUser.id,compilationID:req.session.sessionCompilation._id};
  538. result = await redirectToImportServer(data,"copyProject",req);
  539. }catch (err){
  540. console.log(err);
  541. result.error=1;
  542. result.message = err.message;
  543. }
  544. res.json(result);
  545. },
  546. projectShareInfo: async function(req, res){
  547. try{
  548. let data = JSON.parse(req.body.data);
  549. let shareInfo = await projectModel.findOne({ID: data.projectID, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]}, '-_id shareInfo');
  550. callback(req, res, 0, 'success', shareInfo);
  551. }
  552. catch (err){
  553. callback(req, res, 1, err, null);
  554. }
  555. },
  556. share: async function(req, res){
  557. try{
  558. let data = JSON.parse(req.body.data);
  559. let shareDate = moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'),
  560. shareUserIDs = [];
  561. for (let data of data.shareData) {
  562. shareUserIDs.push(data.userID);
  563. data.shareDate = shareDate;
  564. }
  565. //添加分享
  566. if(data.type === 'create'){
  567. //新增
  568. for (let sData of data.shareData) {
  569. await projectModel.update({ID: data.projectID, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]}, {$addToSet: {shareInfo: sData}});
  570. }
  571. } else if (data.type === 'update') {
  572. await projectModel.update({ID: data.projectID, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]}, {$set: {shareInfo: data.shareData}});
  573. }
  574. //取消分享
  575. else {
  576. await projectModel.update({ID: data.projectID, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]}, {$pull: {shareInfo: {userID: {$in: shareUserIDs}}}});
  577. }
  578. callback(req, res, 0, 'success', data.shareData);
  579. }
  580. catch (err){
  581. callback(req, res, 1, err, null);
  582. }
  583. },
  584. receiveProjects: async function(req, res) {
  585. try {
  586. let rst = {grouped: [], ungrouped: [], summaryInfo: null};
  587. let userID = req.session.sessionUser.id;
  588. let receiveProjects = await projectModel.find({
  589. $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}], compilation: req.session.sessionCompilation._id, 'shareInfo.userID': userID}, '-_id');
  590. //设置原项目用户信息
  591. if(receiveProjects.length > 0){
  592. let orgUserIDs = [];
  593. for(let proj of receiveProjects){
  594. orgUserIDs.push(proj.userID);
  595. if (proj.projType === projType.tender) {
  596. //设置工程专业
  597. proj._doc.feeStandardName = proj.property.feeStandardName || '';
  598. //设置计税方法
  599. proj._doc.taxType = proj.property.taxType;
  600. }
  601. delete proj._doc.property;
  602. }
  603. orgUserIDs = Array.from(new Set(orgUserIDs));
  604. let userObjIDs = [];
  605. for(let uID of orgUserIDs){
  606. userObjIDs.push(mongoose.Types.ObjectId(uID));
  607. }
  608. let orgUsersInfo = await userModel.find({_id: {$in : userObjIDs}});
  609. //建设项目
  610. let consProjIDs = [],
  611. ungroupedTenders = [];
  612. for(let proj of receiveProjects){
  613. if (proj.projType === projType.project) {
  614. consProjIDs.push(proj.ID);
  615. }
  616. //获取分享项目子项
  617. if (proj.projType !== projType.tender) {
  618. proj._doc.children = await pm_facade.getPosterityProjects([proj.ID]);
  619. for (let projC of proj._doc.children) {
  620. if (projC.projType === projType.project) {
  621. consProjIDs.push(projC.ID);
  622. } else if (projC.projType === projType.tender) {
  623. //设置工程专业
  624. projC._doc.feeStandardName = projC.property.feeStandardName || '';
  625. //设置计税方法
  626. projC._doc.taxType = projC.property.taxType;
  627. if (proj.projType === projType.engineering) {
  628. ungroupedTenders.push(projC._doc);
  629. }
  630. }
  631. delete projC._doc.property;
  632. }
  633. } else {//未分类的单位工程不进行汇总,只取价格信息
  634. ungroupedTenders.push(proj._doc);
  635. }
  636. //设置分组,单位工程及单项工程分到未分组那
  637. if (proj.projType === projType.tender || proj.projType === projType.engineering) {
  638. rst.ungrouped.push(proj);
  639. } else {
  640. rst.grouped.push(proj);
  641. }
  642. //设置项目类型为来自别人分享
  643. proj._doc.shareType = 'receive';
  644. for(let userData of orgUsersInfo){
  645. if(proj.userID == userData._id.toString()){
  646. let userInfo = {name: userData.real_name, mobile: userData.mobile, company: userData.company, email: userData.email};
  647. proj._doc.userInfo = userInfo;
  648. }
  649. }
  650. }
  651. consProjIDs = Array.from(new Set(consProjIDs));
  652. let summaryInfo = await pm_facade.getSummaryInfo(consProjIDs);
  653. let tendersFeeInfo = await pm_facade.getTendersFeeInfo(ungroupedTenders);
  654. rst.summaryInfo = {grouped: summaryInfo, ungrouped: tendersFeeInfo};
  655. }
  656. callback(req, res, 0, 'success', rst);
  657. }
  658. catch (err){
  659. console.log(err);
  660. callback(req, res, 1, err, null);
  661. }
  662. },
  663. getProjectsByQuery: async function (req, res) {
  664. try{
  665. let data = JSON.parse(req.body.data);
  666. let compilation = req.session.sessionCompilation._id;
  667. let query = data.query;
  668. query.compilation = compilation;
  669. let options = data.options;
  670. let projects = await projectModel.find(query, options);
  671. callback(req, res, 0, 'success', projects);
  672. }
  673. catch (err){
  674. callback(req, res, 1, err, null);
  675. }
  676. },
  677. getSummaryInfo: async function(req, res){
  678. try{
  679. let data = JSON.parse(req.body.data);
  680. let summaryInfo = await pm_facade.getSummaryInfo(data.projectIDs);
  681. callback(req, res, 0, 'success', summaryInfo);
  682. }
  683. catch (err){
  684. callback(req, res, 1, err, null);
  685. }
  686. },
  687. changeFile:async function(req,res){
  688. try{
  689. let data = JSON.parse(req.body.data);
  690. console.log(data);
  691. await pm_facade.changeFile(data.projects,data.user_id,data.fileID,data.name,data.from,data.type);
  692. callback(req, res, 0, 'success', []);
  693. }
  694. catch (err){
  695. console.log(err);
  696. callback(req, res, 1, err, null);
  697. }
  698. },
  699. exportProject:async function(req,res){
  700. let result={
  701. error:0
  702. };
  703. try {
  704. let data = {dataString:req.body.data,userID:req.session.sessionUser.id};
  705. result = await redirectToImportServer(data,"exportProject",req);
  706. }catch (err){
  707. console.log(err);
  708. result.error=1;
  709. result.message = err.message;
  710. }
  711. res.json(result);
  712. },
  713. importProject:async function(req,res){
  714. let data = JSON.parse(req.body.data);
  715. let result={
  716. error:0
  717. };
  718. try {
  719. data.session = req.session;
  720. result = await redirectToImportServer(data,"importProject",req);
  721. }catch (err){
  722. console.log(err);
  723. result.error=1;
  724. result.message = err.message;
  725. }
  726. res.json(result);
  727. },
  728. importProcessChecking:async function (req,res) {
  729. let result={
  730. error:0
  731. };
  732. try{
  733. let data = JSON.parse(req.body.data);
  734. result.data = await pm_facade.importProcessChecking(data);
  735. } catch (err){
  736. console.log(err);
  737. result.error=1;
  738. result.message = err.message;
  739. }
  740. res.json(result);
  741. },
  742. getUploadToken:function (req,res) {
  743. let result={
  744. error:0
  745. };
  746. try {
  747. result =pm_facade.uploadToken();
  748. }catch (err){
  749. console.log(err);
  750. result.error=1;
  751. result.message = err.message;
  752. }
  753. res.json(result);
  754. },
  755. getBasicInfo: async function(req, res) {
  756. try {
  757. let data = JSON.parse(req.body.data);
  758. let infoLib = await pm_facade.getBasicInfo(req.session.sessionCompilation._id, data.fileKind);
  759. callback(req, res, 0, 'success', infoLib ? infoLib.info : []);
  760. } catch (err) {
  761. console.log(err);
  762. callback(req, res, 1, err, []);
  763. }
  764. },
  765. getProjectFeature: async function(req, res) {
  766. try {
  767. let data = JSON.parse(req.body.data);
  768. let featureLib = await pm_facade.getProjectFeature(data.valuationID, data.engineeringName, data.feeName);
  769. //工程专业设置为费用标准名称
  770. if (featureLib) {
  771. let engData = featureLib.feature.find(function (d) {
  772. return d.key === 'engineering';
  773. });
  774. if (engData) {
  775. engData.value = data.feeName;
  776. }
  777. }
  778. callback(req, res, 0, 'success', featureLib ? featureLib.feature : []);
  779. } catch (err) {
  780. console.log(err);
  781. callback(req, res, 1, err, []);
  782. }
  783. },
  784. getProjectByGranularity: async function(req, res) {
  785. try {
  786. let data = JSON.parse(req.body.data);
  787. let projData = await pm_facade.getProjectByGranularity(data.tenderID, data.granularity, req.session.sessionUser.id, req.session.compilationVersion);
  788. callback(req, res, 0, 'success', projData);
  789. } catch (err) {
  790. callback(req, res, 1, err, null);
  791. }
  792. },
  793. getProjectPlaceholder: async function(req, res) {
  794. let data = JSON.parse(req.body.data);
  795. try {
  796. let countRst = await pm_facade.getProjectPlaceholder(data);
  797. callback(req, res, 0, 'succes', countRst);
  798. } catch (err) {
  799. console.log(err);
  800. callback(req, res, 1, err, null);
  801. }
  802. },
  803. /* importInterface: async function(req, res) {
  804. logger.info(`${req.ip} importInterface`);
  805. const uploadOption = {
  806. uploadDir: './public'
  807. };
  808. let uploadFullName = '';
  809. const form = new multiparty.Form(uploadOption);
  810. form.parse(req, async function(err, fields, files) {
  811. try {
  812. let file = files.file && files.file.length ? files.file[0] : null;
  813. if (!file) {
  814. throw '无有效数据';
  815. }
  816. uploadFullName = file.path;
  817. //获取源数据
  818. let srcStr = fs.readFileSync(file.path, 'utf8');
  819. if (!srcStr) {
  820. throw '无有效数据'
  821. }
  822. let importData = JSON.parse(srcStr);
  823. fs.unlinkSync(file.path);
  824. let projectData = await pm_facade.importProject(importData, req.session.sessionUser.id, req.session.sessionCompilation._id);
  825. callback(req, res, 0, '', projectData);
  826. } catch (err) {
  827. console.log(err);
  828. if(uploadFullName && fs.existsSync(uploadFullName)){
  829. fs.unlinkSync(uploadFullName);
  830. }
  831. callback(req, res, 1, err, null);
  832. }
  833. });
  834. } */
  835. importInterface: async function (req, res) {
  836. const data = JSON.parse(req.body.data);
  837. let result={
  838. error:0
  839. };
  840. try {
  841. data.session = req.session;
  842. result = await redirectToImportServer(data,"importInterface",req);
  843. } catch (err) {
  844. console.log(err);
  845. result.error=1;
  846. result.message = err.message;
  847. }
  848. res.json(result);
  849. },
  850. redirectToImportServer: redirectToImportServer
  851. };
  852. async function redirectToImportServer(data,action,req) {
  853. let importURL = config.getImportURL(process.env.NODE_ENV,req.headers.origin);
  854. let options = {
  855. method: 'POST',
  856. uri: `http://${importURL}/import/${action}`,
  857. body: data,
  858. timeout:220000,
  859. json: true
  860. };
  861. console.log("post import data to:"+options.uri);
  862. return await rp.post(options);
  863. }