pm_controller.js 42 KB

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