pm_controller.js 43 KB

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