pm_controller.js 43 KB

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