pm_controller.js 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717
  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. let mongoose = require('mongoose');
  8. let ProjectsData = require('../models/project_model').project;
  9. let labourCoe = require('../../main/facade/labour_coe_facade');
  10. let projType = require('../models/project_model').projType;
  11. let fileType = require('../models/project_model').fileType;
  12. const engineering = require("../../common/const/engineering");
  13. let EngineeringLibModel = require("../../users/models/engineering_lib_model");
  14. let fee_rate_facade = require("../../fee_rates/facade/fee_rates_facade");
  15. let billsModel = require('../../main/models/bills').model;
  16. let rationsModel = require('../../main/models/ration').model;
  17. let projectModel = mongoose.model('projects');
  18. let unitPriceFileModel = mongoose.model('unit_price_file');
  19. let feeRateFileModel = mongoose.model('fee_rate_file');
  20. let asyncTool = require('async');
  21. let pm_facade = require('../facade/pm_facade');
  22. const userModel = mongoose.model('user');
  23. let config = require("../../../config/config.js");
  24. const optionModel = mongoose.model('options');
  25. const stdBillsGuidanceLibModel = mongoose.model('std_billsGuidance_lib');
  26. const fs = require('fs');
  27. const _ = require('lodash');
  28. import SectionTreeDao from '../../complementary_ration_lib/models/sectionTreeModel';
  29. let sectionTreeDao = new SectionTreeDao();
  30. let consts = require('../../main/models/project_consts');
  31. import multiparty from 'multiparty';
  32. //统一回调函数
  33. let callback = function(req, res, err, message, data){
  34. res.json({error: err, message: message, data: data});
  35. };
  36. module.exports = {
  37. checkRight: function (req, res) {
  38. if(typeof req.body.data === 'object'){
  39. req.body.data = JSON.stringify(req.body.data);
  40. }
  41. let data = JSON.parse(req.body.data);
  42. if (data.user_id) {
  43. return data.user_id === req.session.sessionUser.id;
  44. } else {
  45. return false;
  46. }
  47. },
  48. checkProjectRight: function (userId, projectId, callback) {
  49. ProjectsData.getProject(projectId).then(async function (result) {
  50. /**
  51. * result._doc.userID(Number): MongoDB
  52. * userId(String): Session.userID
  53. */
  54. let shareInfo = null;
  55. //判断是否是打开分享的项目,分享项目shareInfo不为null
  56. if(userId !== result.userID){
  57. shareInfo = await pm_facade.getShareInfo(userId, result);
  58. }
  59. if ((userId === result.userID || shareInfo) && result._doc.projType === projType.tender) {
  60. callback(true, result, shareInfo);
  61. } else {
  62. callback(false);
  63. }
  64. }).catch(function (err) {
  65. callback(false);
  66. });
  67. },
  68. getProjects: async function(req, res){
  69. await ProjectsData.getUserProjects(req.session.sessionUser.id, req.session.sessionCompilation._id, function(err, message, projects){
  70. if (projects) {
  71. callback(req, res, err, message, projects);
  72. } else {
  73. callback(req, res, err, message, null);
  74. }
  75. });
  76. },
  77. updateProjects: async function (req, res) {
  78. let data = JSON.parse(req.body.data);
  79. await ProjectsData.updateUserProjects(req.session.sessionUser.id, req.session.sessionCompilation._id, req.session.sessionCompilation, data.updateData, function (err, message, data) {
  80. if (err === 0) {
  81. callback(req, res, err, message, data);
  82. } else {
  83. callback(req, res, err, message, null);
  84. }
  85. });
  86. },
  87. // CSL, 2017-12-14 该方法用于项目属性:提交保存混合型数据,这些数据来自不同的表,包括projects.property、ration、bills、labour_coes.
  88. updateMixDatas: async function(req, res){
  89. let datas = JSON.parse(req.body.data).mixDataArr;
  90. let functions = [];
  91. function updateFunc(model, cod, doc) {
  92. return function (cb) {
  93. model.update(cod, doc, cb);
  94. }
  95. };
  96. function updateLC(){
  97. return function (cb) {
  98. datas.labourCoes.updateData.projectID = datas.projectID;
  99. labourCoe.save(datas.labourCoes.updateData, cb);
  100. }
  101. };
  102. // 项目属性
  103. if (Object.keys(datas.properties).length > 0){
  104. //基本信息特殊处理,更新建设项目
  105. if(datas.properties['property.basicInformation']){
  106. let constructionProject = await pm_facade.getConstructionProject(datas.projectID);
  107. if(constructionProject){
  108. functions.push(updateFunc(projectModel, {ID: constructionProject.ID}, {'property.basicInformation': datas.properties['property.basicInformation']}));
  109. }
  110. delete datas.properties['property.basicInformation'];
  111. }
  112. functions.push(updateFunc(projectModel, {ID: datas.projectID}, datas.properties));
  113. };
  114. //选项
  115. if(datas.options && datas.options.updateData){
  116. functions.push(updateFunc(optionModel, {user_id: req.session.sessionUser.id, compilation_id: req.session.sessionCompilation._id}, {'options.GENERALOPTS': datas.options.updateData}));
  117. }
  118. // 人工系数
  119. if (datas.labourCoes&&datas.labourCoes.updateData){
  120. functions.push(updateLC());
  121. };
  122. // 清单:每文档doc只存储一条清单,每条清单都必须定位一次文档,无法合并处理
  123. if (datas.bills.length > 0){
  124. for (let bill of datas.bills){
  125. functions.push(updateFunc(billsModel, {projectID: datas.projectID, ID: bill.ID, deleteInfo: null}, bill));
  126. };
  127. };
  128. // 定额:每文档doc只存储一条定额,每条定额都必须定位一次文档,无法合并处理
  129. if (datas.rations.length > 0){
  130. for (let ration of datas.rations){
  131. functions.push(updateFunc(rationsModel, {projectID: datas.projectID, ID: ration.ID, deleteInfo: null}, ration));
  132. };
  133. };
  134. asyncTool.parallel(functions, function(err, result){
  135. {
  136. if (!err) {
  137. res.json({error: 0, message: err, data: result});
  138. } else {
  139. res.json({error: 1, message: err, data: null});
  140. }
  141. }
  142. });
  143. },
  144. updateFiles: async function(req, res){
  145. let data = JSON.parse(req.body.data);
  146. let updateDatas = data.updateDatas;
  147. await ProjectsData.udpateUserFiles(req.session.sessionUser.id, updateDatas, function (err, message, data) {
  148. callback(req, res, err, message, data);
  149. });
  150. },
  151. defaultSettings: async function(req, res){
  152. try{
  153. let data = JSON.parse(req.body.data);
  154. let projectID = data.projectID;
  155. let defaultSettingSc = await ProjectsData.defaultSettings(req.session.sessionUser.id, req.session.sessionCompilation._id, projectID);
  156. if(!defaultSettingSc){
  157. throw '恢复失败';
  158. }
  159. res.json({error: 0, message: '恢复成功', data: null});
  160. }
  161. catch(error){
  162. console.log(error);
  163. res.json({error: 1, message: error, data: null});
  164. }
  165. },
  166. /* copyProjects: function (req, res) {
  167. let data = JSON.parse(req.body.data);
  168. ProjectsData.copyUserProjects(req.session.sessionUser.id, req.session.sessionCompilation._id, data.updateData, function (err, message, data) {
  169. if (err === 0) {
  170. callback(req, res, err, message, data);
  171. } else {
  172. callback(req, res, err, message, null);
  173. }
  174. });
  175. },*/
  176. rename: function (req, res) {
  177. let data = JSON.parse(req.body.data);
  178. ProjectsData.rename(req.session.sessionUser.id, req.session.sessionCompilation._id, data, function (err, message) {
  179. callback(req, res, err, message, null);
  180. });
  181. },
  182. //project getData接口
  183. getData: function(projectID, callback) {
  184. projectModel.findOne({$or: [{deleteInfo: null}, {'deleteInfo.deleted': false}], ID: projectID}, '-_id').then(async function (project) {
  185. if (!project) {
  186. callback('', consts.projectConst.PROJECT_INFO, {});
  187. }
  188. let engineeringLibModel = new EngineeringLibModel();
  189. let engineeringInfo = project !== null && project.property.engineering_id !== undefined ?
  190. await engineeringLibModel.getEngineering(project.property.engineering_id) : null;
  191. let projInfo = project._doc;
  192. if (engineeringInfo !== null) {
  193. if(engineeringInfo.billsGuidance_lib){
  194. for(let billsGuidanceLib of engineeringInfo.billsGuidance_lib){
  195. let stdBillsGuidanceLib = await stdBillsGuidanceLibModel.findOne({ID: billsGuidanceLib.id});
  196. if(stdBillsGuidanceLib){
  197. billsGuidanceLib.type = stdBillsGuidanceLib.type ? stdBillsGuidanceLib.type : 1;
  198. }
  199. }
  200. }
  201. projInfo.engineeringInfo = engineeringInfo;
  202. }
  203. //读取建设项目的基本信息
  204. let basicInfo = await ProjectsData.getBasicInfo(projectID);
  205. if(basicInfo !== null){
  206. projInfo.property.basicInformation = basicInfo;
  207. }
  208. //获取单位工程完整目录结构
  209. let fullPath = await pm_facade.getFullPath(projectID);
  210. projInfo.fullPath = fullPath;
  211. callback('', consts.projectConst.PROJECT_INFO, project);
  212. }, function (err) {
  213. callback(err, consts.projectConst.PROJECT_INFO, {});
  214. });
  215. },
  216. getProject: function(req, res){
  217. let data = JSON.parse(req.body.data);
  218. let projectID = data.proj_id;
  219. ProjectsData.getUserProject(req.session.sessionUser.id, data.proj_id, async function(err, message, data){
  220. if (err === 0) {
  221. let engineeringLibModel = new EngineeringLibModel();
  222. let engineeringInfo = data !== null && data.property.engineering_id !== undefined ?
  223. await engineeringLibModel.getEngineering(data.property.engineering_id) : null;
  224. let strData = JSON.stringify(data);
  225. let projInfo = JSON.parse(strData);
  226. if (engineeringInfo !== null) {
  227. if(engineeringInfo.billsGuidance_lib){
  228. for(let billsGuidanceLib of engineeringInfo.billsGuidance_lib){
  229. let stdBillsGuidanceLib = await stdBillsGuidanceLibModel.findOne({ID: billsGuidanceLib.id});
  230. if(stdBillsGuidanceLib){
  231. billsGuidanceLib.type = stdBillsGuidanceLib.type ? stdBillsGuidanceLib.type : 1;
  232. }
  233. }
  234. }
  235. projInfo.engineeringInfo = engineeringInfo;
  236. }
  237. //读取建设项目的基本信息
  238. let basicInfo = await ProjectsData.getBasicInfo(projectID);
  239. if(basicInfo !== null){
  240. projInfo.property.basicInformation = basicInfo;
  241. }
  242. //获取单位工程完整目录结构
  243. let fullPath = await pm_facade.getFullPath(projectID);
  244. projInfo.fullPath = fullPath;
  245. callback(req, res, err, message, projInfo);
  246. } else {
  247. callback(req, res, err, message, null);
  248. }
  249. });
  250. },
  251. beforeOpenProject: function (req, res) {
  252. let data = JSON.parse(req.body.data);
  253. ProjectsData.beforeOpenProject(req.session.sessionUser.id, data.proj_id, data.updateData, function (err, message, data) {
  254. callback(req, res, err, message, data);
  255. });
  256. },
  257. getNewProjectID: function (req, res) {
  258. let data = JSON.parse(req.body.data);
  259. ProjectsData.getNewProjectID(data.count, function (err, message, data) {
  260. callback(req, res, err, message, data);
  261. });
  262. },
  263. // 项目管理首页
  264. index: async function(request, response) {
  265. // 获取编办信息
  266. let sessionCompilation = request.session.sessionCompilation;
  267. if (sessionCompilation === undefined ||sessionCompilation ===null) {
  268. return response.redirect('/logout');
  269. }
  270. let compilationModel = new CompilationModel();
  271. //更新编办信息
  272. let compilationData = await compilationModel.getCompilationById(sessionCompilation._id);
  273. request.session.sessionCompilation = compilationData;
  274. sessionCompilation = request.session.sessionCompilation;
  275. //更新用户的使用过的费用定额列表
  276. //是否第一次进入该费用定额
  277. let isFirst = await pm_facade.isFirst(request.session.sessionUser.id, compilationData._id.toString());
  278. // 清单计价
  279. let billValuation = sessionCompilation.bill_valuation !== undefined ?
  280. sessionCompilation.bill_valuation : [];
  281. // 获取标准库数据
  282. let engineeringLibModel = new EngineeringLibModel();
  283. billValuation = await engineeringLibModel.getLib(billValuation);
  284. // 定额计价
  285. let rationValuation = sessionCompilation.ration_valuation !== undefined ?
  286. sessionCompilation.ration_valuation : [];
  287. rationValuation = await engineeringLibModel.getLib(rationValuation);
  288. let absoluteUrl = compilationData.overWriteUrl ? request.app.locals.rootDir + compilationData.overWriteUrl : request.app.locals.rootDir;
  289. let overWriteUrl = fs.existsSync(absoluteUrl) && fs.statSync(absoluteUrl).isFile()? compilationData.overWriteUrl : null;
  290. let renderData = {
  291. isFirst: isFirst,
  292. userAccount: request.session.userAccount,
  293. userID: request.session.sessionUser.id,
  294. compilationData: JSON.stringify(sessionCompilation),
  295. overWriteUrl: overWriteUrl,
  296. billValuation: JSON.stringify(billValuation),
  297. rationValuation: JSON.stringify(rationValuation),
  298. engineeringList: JSON.stringify(engineering.List),
  299. compilationName: sessionCompilation.name,
  300. versionName: request.session.compilationVersion,
  301. LicenseKey:config.getLicenseKey(process.env.NODE_ENV)
  302. };
  303. response.render('building_saas/pm/html/project-management.html', renderData);
  304. },
  305. //第一次进入该费用定额时准备的初始数据
  306. prepareInitialData: async function(request, response) {
  307. try {
  308. let sessionCompilation = request.session.sessionCompilation;
  309. await pm_facade.prepareInitialData(request.session.sessionUser.id, sessionCompilation._id, sessionCompilation.example);
  310. callback(request, response, 0, 'success', null);
  311. } catch(err) {
  312. callback(request, response, 1, err, null);
  313. }
  314. },
  315. // 获取单价文件列表
  316. getUnitFileList: async function(request, response) {
  317. let data = request.body.data;
  318. try {
  319. data = JSON.parse(data);
  320. let projectId = data.parentID !== undefined ? data.parentID : 0;
  321. if (isNaN(projectId) && projectId <= 0) {
  322. throw {msg: 'id数据有误!', err: 1};
  323. }
  324. /*// 获取对应建设项目下所有的单位工程id
  325. let idList = await ProjectsData.getTenderByProjectId(projectId);
  326. if (idList.length <= 0) {
  327. throw {msg: '不存在对应单位工程', err: 0};
  328. }*/
  329. // 获取对应的单价文件
  330. let unitPriceFileModel = new UnitPriceFileModel();
  331. let unitPriceFileData = await unitPriceFileModel.getDataByRootProject(projectId);
  332. if (unitPriceFileData === null) {
  333. throw {msg: '不存在对应单价文件', err: 0};
  334. }
  335. // 整理数据
  336. let unitPriceFileList = [];
  337. for (let unitPriceFile of unitPriceFileData) {
  338. let tmp = {
  339. name: unitPriceFile.name,
  340. id: unitPriceFile.id
  341. };
  342. unitPriceFileList.push(tmp);
  343. }
  344. callback(request, response, 0, '', unitPriceFileList);
  345. } catch (error) {
  346. console.log(error);
  347. let responseData = error.err === 1 ? null : [];
  348. callback(request, response, error.err, error.msg, responseData);
  349. }
  350. },
  351. getFeeRateFileList:async function(request, response) {
  352. let data = request.body.data;
  353. try {
  354. data = JSON.parse(data);
  355. let projectId = data.parentID !== undefined ? data.parentID : 0;
  356. if (isNaN(projectId) && projectId <= 0) {
  357. throw {msg: 'id数据有误!', err: 1};
  358. }
  359. // 获取对应建设项目下所有的单位工程id
  360. let feeRateFileList = await fee_rate_facade.getFeeRatesByProject(projectId);
  361. callback(request, response, 0, '',feeRateFileList );
  362. } catch (error) {
  363. console.log(error);
  364. let responseData = error.err === 1 ? null : [];
  365. callback(request, response, error.err, error.msg, responseData);
  366. }
  367. },
  368. getGCDatas: async function(request, response) {
  369. let userID = request.session.sessionUser.id;
  370. let compilatoinId = request.session.sessionCompilation._id;
  371. let rst = [];
  372. let _projs = Object.create(null), _engs = Object.create(null), prefix = 'ID_';
  373. try{
  374. let gc_unitPriceFiles = await ProjectsData.getGCFiles(fileType.unitPriceFile, userID);
  375. let gc_feeRateFiles = await ProjectsData.getGCFiles(fileType.feeRateFile, userID);
  376. let gc_tenderFiles = await ProjectsData.getGCFiles(projType.tender, userID);
  377. for(let i = 0, len = gc_unitPriceFiles.length; i < len; i++){
  378. let gc_uf = gc_unitPriceFiles[i];
  379. let theProj = _projs[prefix + gc_uf.root_project_id] || null;
  380. if(!theProj){
  381. let tempProj = await ProjectsData.getProjectsByIds(userID, compilatoinId, [gc_uf.root_project_id]);
  382. if(tempProj.length > 0 && tempProj[0].projType !== projType.folder){
  383. theProj = _projs[prefix + gc_uf.root_project_id] = tempProj[0]._doc;
  384. buildProj(theProj);
  385. }
  386. }
  387. if(theProj){
  388. theProj.unitPriceFiles.push(gc_uf);
  389. }
  390. }
  391. for(let i = 0, len = gc_feeRateFiles.length; i < len; i++){
  392. let gc_ff = gc_feeRateFiles[i];
  393. let theProj = _projs[prefix + gc_ff.rootProjectID] || null;
  394. if(!theProj){
  395. let tempProj = await ProjectsData.getProjectsByIds(userID, compilatoinId, [gc_ff.rootProjectID]);
  396. if(tempProj.length > 0 && tempProj[0].projType !== projType.folder){
  397. theProj = _projs[prefix + gc_ff.rootProjectID] = tempProj[0]._doc;
  398. buildProj(theProj);
  399. }
  400. }
  401. if(theProj) {
  402. theProj.feeRateFiles.push(gc_ff);
  403. }
  404. }
  405. if(gc_tenderFiles.length > 0){
  406. for(let i = 0, len = gc_tenderFiles.length; i < len; i++){
  407. let gc_t = gc_tenderFiles[i];
  408. let theProj = _projs[prefix + gc_t.ParentID] || null;
  409. if(!theProj){
  410. let tempProjs = await ProjectsData.getProjectsByIds(userID, compilatoinId, [gc_t.ParentID]);
  411. if(tempProjs.length > 0 && tempProjs[0].projType === projType.project){
  412. theProj = _projs[prefix + gc_t.ParentID] = tempProjs[0]._doc;
  413. buildProj(theProj);
  414. }
  415. }
  416. if(theProj) {
  417. theProj.children.push(gc_t);
  418. }
  419. }
  420. }
  421. for(let i in _projs){
  422. rst.push(_projs[i]);
  423. }
  424. function buildProj(proj){
  425. proj.children = [];
  426. proj.unitPriceFiles = [];
  427. proj.feeRateFiles = [];
  428. }
  429. callback(request, response, 0, 'success', rst);
  430. }
  431. catch (error){
  432. callback(request, response, true, error, null);
  433. }
  434. },
  435. recGC: function(request, response){
  436. let userID = request.session.sessionUser.id;
  437. let data = JSON.parse(request.body.data);
  438. let nodes = data.nodes;
  439. ProjectsData.recGC(userID, nodes, function (err, msg, data) {
  440. callback(request, response, err, msg, data);
  441. });
  442. },
  443. delGC: async function(request, response){
  444. let data = JSON.parse(request.body.data);
  445. let delDatas = data.delDatas;
  446. let bulkProjs = [], bulkUFs = [], bulkFFs = [];
  447. try{
  448. for(let data of delDatas){
  449. if(data.updateType === 'Project'){
  450. bulkProjs.push({updateOne: {filter: {ID: data.ID}, update: {'deleteInfo.completeDeleted': true}}});
  451. }
  452. else if(data.updateType === fileType.unitPriceFile){
  453. bulkUFs.push({updateOne: {filter: {id: data.ID}, update: {'deleteInfo.completeDeleted': true}}});
  454. }
  455. else{
  456. bulkFFs.push({updateOne: {filter: {ID: data.ID}, update: {'deleteInfo.completeDeleted': true}}});
  457. }
  458. }
  459. if(bulkProjs.length > 0){
  460. await projectModel.bulkWrite(bulkProjs);
  461. }
  462. if(bulkUFs.length > 0){
  463. await unitPriceFileModel.bulkWrite(bulkUFs);
  464. }
  465. if(bulkFFs.length > 0){
  466. await feeRateFileModel.bulkWrite(bulkFFs);
  467. }
  468. callback(request, response, 0, 'success', null);
  469. } catch(err){
  470. callback(request, response, 1, err, null);
  471. }
  472. },
  473. moveProject:async function(req,res){
  474. let result={
  475. error:0
  476. };
  477. try {
  478. let data = req.body.data;
  479. let rdata= await pm_facade.moveProject(data);
  480. result.data= rdata;
  481. }catch (err){
  482. console.log(err);
  483. result.error=1;
  484. result.message = err.message;
  485. }
  486. res.json(result);
  487. },
  488. copyProjects:async function (req, res) {
  489. let result={
  490. error:0
  491. };
  492. try {
  493. let data = JSON.parse(req.body.data);
  494. result.data = await pm_facade.copyProject(req.session.sessionUser.id, req.session.sessionCompilation._id,data);
  495. }catch (err){
  496. console.log(err);
  497. result.error=1;
  498. result.message = err.message;
  499. }
  500. res.json(result);
  501. },
  502. projectShareInfo: async function(req, res){
  503. try{
  504. let data = JSON.parse(req.body.data);
  505. let shareInfo = await projectModel.findOne({ID: data.projectID, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]}, '-_id shareInfo');
  506. callback(req, res, 0, 'success', shareInfo);
  507. }
  508. catch (err){
  509. callback(req, res, 1, err, null);
  510. }
  511. },
  512. share: async function(req, res){
  513. try{
  514. let data = JSON.parse(req.body.data);
  515. let shareDate = moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'),
  516. shareUserIDs = [];
  517. for (let data of data.shareData) {
  518. shareUserIDs.push(data.userID);
  519. data.shareDate = shareDate;
  520. }
  521. //添加分享
  522. if(data.type === 'create'){
  523. //新增
  524. for (let sData of data.shareData) {
  525. await projectModel.update({ID: data.projectID, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]}, {$addToSet: {shareInfo: sData}});
  526. }
  527. } else if (data.type === 'update') {
  528. await projectModel.update({ID: data.projectID, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]}, {$set: {shareInfo: data.shareData}});
  529. }
  530. //取消分享
  531. else {
  532. await projectModel.update({ID: data.projectID, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]}, {$pull: {shareInfo: {userID: {$in: shareUserIDs}}}});
  533. }
  534. callback(req, res, 0, 'success', data.shareData);
  535. }
  536. catch (err){
  537. callback(req, res, 1, err, null);
  538. }
  539. },
  540. receiveProjects: async function(req, res) {
  541. try {
  542. let rst = {grouped: [], ungrouped: [], summaryInfo: null};
  543. let userID = req.session.sessionUser.id;
  544. let receiveProjects = await projectModel.find({
  545. $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}], compilation: req.session.sessionCompilation._id, 'shareInfo.userID': userID}, '-_id');
  546. //设置原项目用户信息
  547. if(receiveProjects.length > 0){
  548. let orgUserIDs = [];
  549. for(let proj of receiveProjects){
  550. orgUserIDs.push(proj.userID);
  551. if (proj.projType === projType.tender) {
  552. //设置工程专业
  553. proj._doc.feeStandardName = proj.property.feeStandardName || '';
  554. //设置项目类别
  555. proj._doc.valuationType = proj.property.valuationType === 'bill' ? '预算' : '工程清单';
  556. }
  557. delete proj._doc.property;
  558. }
  559. orgUserIDs = Array.from(new Set(orgUserIDs));
  560. let userObjIDs = [];
  561. for(let uID of orgUserIDs){
  562. userObjIDs.push(mongoose.Types.ObjectId(uID));
  563. }
  564. let orgUsersInfo = await userModel.find({_id: {$in : userObjIDs}});
  565. //建设项目
  566. let consProjIDs = [],
  567. ungroupedTenders = [];
  568. for(let proj of receiveProjects){
  569. if (proj.projType === projType.project) {
  570. consProjIDs.push(proj.ID);
  571. }
  572. //获取分享项目子项
  573. if (proj.projType !== projType.tender) {
  574. proj._doc.children = await pm_facade.getPosterityProjects([proj.ID]);
  575. for (let projC of proj._doc.children) {
  576. if (projC.projType === projType.project) {
  577. consProjIDs.push(projC.ID);
  578. } else if (projC.projType === projType.tender) {
  579. //设置工程专业
  580. projC._doc.feeStandardName = projC.property.feeStandardName || '';
  581. }
  582. delete projC._doc.property;
  583. }
  584. } else {//未分类的单位工程不进行汇总,只取价格信息
  585. ungroupedTenders.push(proj._doc);
  586. }
  587. //设置分组,单位工程及单项工程分到未分组那
  588. if (proj.projType === projType.tender || proj.projType === projType.engineering) {
  589. rst.ungrouped.push(proj);
  590. } else {
  591. rst.grouped.push(proj);
  592. }
  593. //设置项目类型为来自别人分享
  594. proj._doc.shareType = 'receive';
  595. for(let userData of orgUsersInfo){
  596. if(proj.userID == userData._id.toString()){
  597. let userInfo = {name: userData.real_name, mobile: userData.mobile, company: userData.company, email: userData.email};
  598. proj._doc.userInfo = userInfo;
  599. }
  600. }
  601. }
  602. consProjIDs = Array.from(new Set(consProjIDs));
  603. let summaryInfo = await pm_facade.getSummaryInfo(consProjIDs);
  604. let tendersFeeInfo = await pm_facade.getTendersFeeInfo(ungroupedTenders);
  605. rst.summaryInfo = {grouped: summaryInfo, ungrouped: tendersFeeInfo};
  606. }
  607. callback(req, res, 0, 'success', rst);
  608. }
  609. catch (err){
  610. console.log(err);
  611. callback(req, res, 1, err, null);
  612. }
  613. },
  614. getProjectsByQuery: async function (req, res) {
  615. try{
  616. let data = JSON.parse(req.body.data);
  617. let compilation = req.session.sessionCompilation._id;
  618. let query = data.query;
  619. query.compilation = compilation;
  620. let options = data.options;
  621. let projects = await projectModel.find(query, options);
  622. callback(req, res, 0, 'success', projects);
  623. }
  624. catch (err){
  625. callback(req, res, 1, err, null);
  626. }
  627. },
  628. getSummaryInfo: async function(req, res){
  629. try{
  630. let data = JSON.parse(req.body.data);
  631. let summaryInfo = await pm_facade.getSummaryInfo(data.projectIDs);
  632. callback(req, res, 0, 'success', summaryInfo);
  633. }
  634. catch (err){
  635. callback(req, res, 1, err, null);
  636. }
  637. },
  638. changeFile:async function(req,res){
  639. try{
  640. let data = JSON.parse(req.body.data);
  641. console.log(data);
  642. await pm_facade.changeFile(data.projects,data.user_id,data.fileID,data.name,data.from,data.type);
  643. callback(req, res, 0, 'success', []);
  644. }
  645. catch (err){
  646. console.log(err);
  647. callback(req, res, 1, err, null);
  648. }
  649. },
  650. exportProject:async function(req,res){
  651. let result={
  652. error:0
  653. };
  654. try {
  655. let data = JSON.parse(req.body.data);
  656. result.data = await pm_facade.exportProject(req.session.sessionUser.id, data);
  657. }catch (err){
  658. console.log(err);
  659. result.error=1;
  660. result.message = err.message;
  661. }
  662. res.json(result);
  663. },
  664. importProject:async function(req,res){
  665. let form = new multiparty.Form({uploadDir: './public'});
  666. let uploadFullName;
  667. form.parse(req, async function (err, fields, files) {
  668. try {
  669. const file = typeof files.file !== 'undefined' ? files.file[0] : null;
  670. if (err || !file) {
  671. throw '上传失败。';
  672. }
  673. console.log(file);
  674. let data = fs.readFileSync(file.path,'utf-8');
  675. console.log(data);
  676. }catch (e){
  677. }
  678. res.json({error:0})
  679. })
  680. /*let result={
  681. error:0
  682. };
  683. try {
  684. console.log(req.files[0]);
  685. /!* let data = JSON.parse(req.body.data);
  686. result.data = await pm_facade.exportProject(req.session.sessionUser.id, data);*!/
  687. }catch (err){
  688. console.log(err);
  689. result.error=1;
  690. result.message = err.message;
  691. }
  692. res.json(result);*/
  693. }
  694. };