pm_controller.js 38 KB

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