pm_controller.js 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795
  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.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.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}});
  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),
  320. valuationOpts: valuationOpts,
  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. let data = JSON.parse(request.body.data);
  482. let nodes = data.nodes;
  483. ProjectsData.recGC(userID, 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. if (proj.projType === projType.engineering) {
  626. ungroupedTenders.push(projC._doc);
  627. }
  628. }
  629. delete projC._doc.property;
  630. }
  631. } else {//未分类的单位工程不进行汇总,只取价格信息
  632. ungroupedTenders.push(proj._doc);
  633. }
  634. //设置分组,单位工程及单项工程分到未分组那
  635. if (proj.projType === projType.tender || proj.projType === projType.engineering) {
  636. rst.ungrouped.push(proj);
  637. } else {
  638. rst.grouped.push(proj);
  639. }
  640. //设置项目类型为来自别人分享
  641. proj._doc.shareType = 'receive';
  642. for(let userData of orgUsersInfo){
  643. if(proj.userID == userData._id.toString()){
  644. let userInfo = {name: userData.real_name, mobile: userData.mobile, company: userData.company, email: userData.email};
  645. proj._doc.userInfo = userInfo;
  646. }
  647. }
  648. }
  649. consProjIDs = Array.from(new Set(consProjIDs));
  650. let summaryInfo = await pm_facade.getSummaryInfo(consProjIDs);
  651. let tendersFeeInfo = await pm_facade.getTendersFeeInfo(ungroupedTenders);
  652. rst.summaryInfo = {grouped: summaryInfo, ungrouped: tendersFeeInfo};
  653. }
  654. callback(req, res, 0, 'success', rst);
  655. }
  656. catch (err){
  657. console.log(err);
  658. callback(req, res, 1, err, null);
  659. }
  660. },
  661. getProjectsByQuery: async function (req, res) {
  662. try{
  663. let data = JSON.parse(req.body.data);
  664. let compilation = req.session.sessionCompilation._id;
  665. let query = data.query;
  666. query.compilation = compilation;
  667. let options = data.options;
  668. let projects = await projectModel.find(query, options);
  669. callback(req, res, 0, 'success', projects);
  670. }
  671. catch (err){
  672. callback(req, res, 1, err, null);
  673. }
  674. },
  675. getSummaryInfo: async function(req, res){
  676. try{
  677. let data = JSON.parse(req.body.data);
  678. let summaryInfo = await pm_facade.getSummaryInfo(data.projectIDs);
  679. callback(req, res, 0, 'success', summaryInfo);
  680. }
  681. catch (err){
  682. callback(req, res, 1, err, null);
  683. }
  684. },
  685. changeFile:async function(req,res){
  686. try{
  687. let data = JSON.parse(req.body.data);
  688. console.log(data);
  689. await pm_facade.changeFile(data.projects,data.user_id,data.fileID,data.name,data.from,data.type);
  690. callback(req, res, 0, 'success', []);
  691. }
  692. catch (err){
  693. console.log(err);
  694. callback(req, res, 1, err, null);
  695. }
  696. },
  697. getBasicInfo: async function(req, res) {
  698. try {
  699. let infoLib = await pm_facade.getBasicInfo(req.session.sessionCompilation._id);
  700. callback(req, res, 0, 'success', infoLib ? infoLib.info : []);
  701. } catch (err) {
  702. console.log(err);
  703. callback(req, res, 1, err, []);
  704. }
  705. },
  706. getProjectFeature: async function(req, res) {
  707. try {
  708. let data = JSON.parse(req.body.data);
  709. let featureLib = await pm_facade.getProjectFeature(data.valuationID, data.engineeringName, data.feeName);
  710. //工程专业设置为费用标准名称
  711. if (featureLib) {
  712. let engData = featureLib.feature.find(function (d) {
  713. return d.key === 'engineering';
  714. });
  715. if (engData) {
  716. engData.value = data.feeName;
  717. }
  718. }
  719. callback(req, res, 0, 'success', featureLib ? featureLib.feature : []);
  720. } catch (err) {
  721. console.log(err);
  722. callback(req, res, 1, err, []);
  723. }
  724. },
  725. getProjectByGranularity: async function(req, res) {
  726. try {
  727. let data = JSON.parse(req.body.data);
  728. let projData = await pm_facade.getProjectByGranularity(data.tenderID, data.granularity, req.session.sessionUser.id, req.session.compilationVersion);
  729. callback(req, res, 0, 'success', projData);
  730. } catch (err) {
  731. callback(req, res, 1, err, null);
  732. }
  733. },
  734. getProjectPlaceholder: async function(req, res) {
  735. let data = JSON.parse(req.body.data);
  736. try {
  737. let countRst = await pm_facade.getProjectPlaceholder(data);
  738. callback(req, res, 0, 'succes', countRst);
  739. } catch (err) {
  740. console.log(err);
  741. callback(req, res, 1, err, null);
  742. }
  743. },
  744. importInterface: async function(req, res) {
  745. logger.info(`${req.ip} importInterface`);
  746. const uploadOption = {
  747. uploadDir: './public'
  748. };
  749. let uploadFullName = '';
  750. const form = new multiparty.Form(uploadOption);
  751. form.parse(req, async function(err, fields, files) {
  752. try {
  753. let file = files.file && files.file.length ? files.file[0] : null;
  754. if (!file) {
  755. throw '无有效数据';
  756. }
  757. uploadFullName = file.path;
  758. //获取源数据
  759. let srcStr = fs.readFileSync(file.path, 'utf8');
  760. if (!srcStr) {
  761. throw '无有效数据'
  762. }
  763. let importData = JSON.parse(srcStr);
  764. fs.unlinkSync(file.path);
  765. let projectData = await pm_facade.importProject(importData, req.session.sessionUser.id, req.session.sessionCompilation._id);
  766. callback(req, res, 0, '', projectData);
  767. } catch (err) {
  768. console.log(err);
  769. if(uploadFullName && fs.existsSync(uploadFullName)){
  770. fs.unlinkSync(uploadFullName);
  771. }
  772. callback(req, res, 1, err, null);
  773. }
  774. });
  775. }
  776. };