pm_controller.js 38 KB

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