pm_controller.js 42 KB

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