pm_controller.js 42 KB

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