pm_controller.js 43 KB

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