pm_controller.js 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065
  1. /**
  2. * Created by Mai on 2017/1/18.
  3. */
  4. const UnitPriceFileModel = require("../../glj/models/unit_price_file_model");
  5. const moment = require('moment');
  6. const CompilationModel = require("../../users/models/compilation_model");
  7. const UserModel = require("../../users/models/user_model");
  8. const userModelObj = new UserModel();
  9. let mongoose = require('mongoose');
  10. let ProjectsData = require('../models/project_model').project;
  11. let labourCoe = require('../../main/facade/labour_coe_facade');
  12. let projType = require('../models/project_model').projType;
  13. let fileType = require('../models/project_model').fileType;
  14. const engineering = require("../../common/const/engineering");
  15. let EngineeringLibModel = require("../../users/models/engineering_lib_model");
  16. let fee_rate_facade = require("../../fee_rates/facade/fee_rates_facade");
  17. let billsModel = require('../../main/models/bills').model;
  18. let rationsModel = require('../../main/models/ration').model;
  19. let projectModel = mongoose.model('projects');
  20. let unitPriceFileModel = mongoose.model('unit_price_file');
  21. let feeRateFileModel = mongoose.model('fee_rate_file');
  22. let asyncTool = require('async');
  23. let pm_facade = require('../facade/pm_facade');
  24. const userModel = mongoose.model('user');
  25. let config = require("../../../config/config.js");
  26. const optionModel = mongoose.model('options');
  27. const stdBillsGuidanceLibModel = mongoose.model('std_billsGuidance_lib');
  28. const fs = require('fs');
  29. const _ = require('lodash');
  30. const SectionTreeDao = require('../../complementary_ration_lib/models/sectionTreeModel');
  31. const uuidV1 = require('uuid/v1');
  32. let sectionTreeDao = new SectionTreeDao();
  33. let consts = require('../../main/models/project_consts');
  34. let rp = require('request-promise');
  35. const commonUtil = require('../../../public/common_util');
  36. const { ValuationText } = require('../../../public/common_constants');
  37. //统一回调函数
  38. let callback = function (req, res, err, message, data) {
  39. res.json({ error: err, message: message, data: data });
  40. };
  41. module.exports = {
  42. redirectToImportServer,
  43. checkRight: function (req, res) {
  44. if (typeof req.body.data === 'object') {
  45. req.body.data = JSON.stringify(req.body.data);
  46. }
  47. let data = JSON.parse(req.body.data);
  48. if (data.user_id) {
  49. return data.user_id === req.session.sessionUser.id;
  50. } else {
  51. return false;
  52. }
  53. },
  54. checkProjectRight: function (userId, projectId, callback) {
  55. ProjectsData.getProject(projectId).then(async function (result) {
  56. /**
  57. * result._doc.userID(Number): MongoDB
  58. * userId(String): Session.userID
  59. */
  60. let shareInfo = null;
  61. let isOpenShareProject = false;
  62. //判断是否是打开分享的项目,分享项目shareInfo不为null
  63. if (userId !== result.userID) {
  64. shareInfo = await pm_facade.getShareInfo(userId, result.ID);
  65. isOpenShareProject = true;
  66. }
  67. if ((userId === result.userID || shareInfo) && result._doc.projType === projType.tender) {
  68. const allowCooperate = (shareInfo || {}).allowCooperate;
  69. callback(true, result, isOpenShareProject, allowCooperate);
  70. } else {
  71. callback(false);
  72. }
  73. }).catch(function (err) {
  74. callback(false);
  75. });
  76. },
  77. getProjects: async function (req, res) {
  78. await ProjectsData.getUserProjects(req.session.sessionUser.id, req.session.sessionCompilation._id, function(err, message, projects){
  79. if (projects) {
  80. callback(req, res, err, message, projects);
  81. } else {
  82. callback(req, res, err, message, null);
  83. }
  84. });
  85. },
  86. updateProjects: async function (req, res) {
  87. let data = JSON.parse(req.body.data);
  88. try {
  89. await ProjectsData.updateUserProjects(req.session.sessionUser.id, req.session.sessionCompilation._id, req.session.sessionCompilation, data.updateData, function (err, message, data) {
  90. if (err === 0) {
  91. callback(req, res, err, message, data);
  92. } else {
  93. callback(req, res, err, message, null);
  94. }
  95. });
  96. } catch (err) {
  97. console.log(err);
  98. callback(req, res, 1, String(err), null);
  99. }
  100. },
  101. // CSL, 2017-12-14 该方法用于项目属性:提交保存混合型数据,这些数据来自不同的表,包括projects.property、ration、bills、labour_coes.
  102. updateMixDatas: async function (req, res) {
  103. let datas = JSON.parse(req.body.data).mixDataArr;
  104. let functions = [];
  105. function updateFunc(model, cod, doc) {
  106. return function (cb) {
  107. model.update(cod, doc, cb);
  108. }
  109. };
  110. function updateLC() {
  111. return function (cb) {
  112. datas.labourCoes.updateData.projectID = datas.projectID;
  113. labourCoe.save(datas.labourCoes.updateData, cb);
  114. }
  115. };
  116. // 项目属性
  117. if (Object.keys(datas.properties).length > 0) {
  118. //基本信息特殊处理,更新建设项目
  119. if (datas.properties['property.basicInformation']) {
  120. let constructionProject = await pm_facade.getConstructionProject(datas.projectID);
  121. if (constructionProject) {
  122. functions.push(updateFunc(projectModel, { ID: constructionProject.ID }, { 'property.basicInformation': datas.properties['property.basicInformation'] }));
  123. }
  124. delete datas.properties['property.basicInformation'];
  125. }
  126. functions.push(updateFunc(projectModel, { ID: datas.projectID }, datas.properties));
  127. };
  128. //选项
  129. if (datas.options && datas.options.updateData) {
  130. functions.push(updateFunc(optionModel, { user_id: req.session.sessionUser.id, compilation_id: req.session.sessionCompilation._id }, { 'options.GENERALOPTS': datas.options.updateData }));
  131. }
  132. // 人工系数
  133. if (datas.labourCoes && datas.labourCoes.updateData) {
  134. functions.push(updateLC());
  135. };
  136. // 清单:每文档doc只存储一条清单,每条清单都必须定位一次文档,无法合并处理
  137. if (datas.bills && datas.bills.length > 0) {
  138. for (let bill of datas.bills) {
  139. functions.push(updateFunc(billsModel, { projectID: datas.projectID, ID: bill.ID, deleteInfo: null }, bill));
  140. };
  141. };
  142. // 定额:每文档doc只存储一条定额,每条定额都必须定位一次文档,无法合并处理
  143. if (datas.rations && datas.rations.length > 0) {
  144. for (let ration of datas.rations) {
  145. functions.push(updateFunc(rationsModel, { projectID: datas.projectID, ID: ration.ID, deleteInfo: null }, ration));
  146. };
  147. };
  148. asyncTool.parallel(functions, function (err, result) {
  149. {
  150. if (!err) {
  151. res.json({ error: 0, message: err, data: result });
  152. } else {
  153. res.json({ error: 1, message: err, data: null });
  154. }
  155. }
  156. });
  157. },
  158. updateFiles: async function (req, res) {
  159. let data = JSON.parse(req.body.data);
  160. let updateDatas = data.updateDatas;
  161. await ProjectsData.udpateUserFiles(req.session.sessionUser.id, updateDatas, function (err, message, data) {
  162. callback(req, res, err, message, data);
  163. });
  164. },
  165. defaultSettings: async function (req, res) {
  166. try {
  167. let data = JSON.parse(req.body.data);
  168. let projectID = data.projectID;
  169. let defaultSettingSc = await ProjectsData.defaultSettings(req.session.sessionUser.id, req.session.sessionCompilation, projectID);
  170. if (!defaultSettingSc) {
  171. throw '恢复失败';
  172. }
  173. res.json({ error: 0, message: '恢复成功', data: null });
  174. }
  175. catch (error) {
  176. console.log(error);
  177. res.json({ error: 1, message: error, data: null });
  178. }
  179. },
  180. /* copyProjects: function (req, res) {
  181. let data = JSON.parse(req.body.data);
  182. ProjectsData.copyUserProjects(req.session.sessionUser.id, req.session.sessionCompilation._id, data.updateData, function (err, message, data) {
  183. if (err === 0) {
  184. callback(req, res, err, message, data);
  185. } else {
  186. callback(req, res, err, message, null);
  187. }
  188. });
  189. },*/
  190. rename: function (req, res) {
  191. let data = JSON.parse(req.body.data);
  192. ProjectsData.rename(req.session.sessionUser.id, req.session.sessionCompilation._id, data, function (err, message) {
  193. callback(req, res, err, message, null);
  194. });
  195. },
  196. //project getData接口
  197. getData: function (projectID, callback, isReport, userID) {
  198. projectModel.findOne({ $or: [{ deleteInfo: null }, { 'deleteInfo.deleted': false }], ID: projectID }, '-_id').then(async function (project) {
  199. if (!project) {
  200. callback('', consts.projectConst.PROJECT_INFO, {});
  201. }
  202. let engineeringLibModel = new EngineeringLibModel();
  203. let engineeringInfo = project !== null && project.property.engineering_id !== undefined ?
  204. await engineeringLibModel.getEngineering(project.property.engineering_id) : null;
  205. let projInfo = project._doc;
  206. if (engineeringInfo !== null) {
  207. if (engineeringInfo.billsGuidance_lib) {
  208. for (let billsGuidanceLib of engineeringInfo.billsGuidance_lib) {
  209. let stdBillsGuidanceLib = await stdBillsGuidanceLibModel.findOne({ ID: billsGuidanceLib.id });
  210. if (stdBillsGuidanceLib) {
  211. billsGuidanceLib.type = stdBillsGuidanceLib.type ? stdBillsGuidanceLib.type : 1;
  212. }
  213. }
  214. }
  215. projInfo.engineeringInfo = engineeringInfo;
  216. }
  217. // 获取建设项目相关信息
  218. const constructionProject = await pm_facade.getConstructionProject(projectID);
  219. if (constructionProject) {
  220. projInfo.property.basicInformation = constructionProject.property && constructionProject.property.basicInformation || null;
  221. projInfo.property.projectValuationType = constructionProject.property && constructionProject.property.valuationType || null;
  222. }
  223. //获取单位工程完整目录结构
  224. let fullPath = await pm_facade.getFullPath(projectID);
  225. projInfo.fullPath = fullPath;
  226. // 获取分享的tip
  227. projInfo.shareTip = await pm_facade.getShareTip(projectID, 2);
  228. // 获取分享状态
  229. if (typeof userID === 'string') {
  230. projInfo.shareState = await pm_facade.getShareState(projectID, userID);
  231. }
  232. // 获取项目所属用户
  233. projInfo.owner = await userModel.findOne({_id: mongoose.Types.ObjectId(project.userID)}, 'real_name mobile').lean();
  234. projInfo.opener = await userModel.findOne({_id: mongoose.Types.ObjectId(userID)}, 'real_name mobile').lean();
  235. callback('', consts.projectConst.PROJECT_INFO, project);
  236. }, function (err) {
  237. callback(err, consts.projectConst.PROJECT_INFO, {});
  238. });
  239. },
  240. getProject: function (req, res) {
  241. let data = JSON.parse(req.body.data);
  242. let projectID = data.proj_id;
  243. ProjectsData.getUserProject(req.session.sessionUser.id, data.proj_id, async function (err, message, data) {
  244. if (err === 0) {
  245. let engineeringLibModel = new EngineeringLibModel();
  246. let engineeringInfo = data !== null && data.property.engineering_id !== undefined ?
  247. await engineeringLibModel.getEngineering(data.property.engineering_id) : null;
  248. let strData = JSON.stringify(data);
  249. let projInfo = JSON.parse(strData);
  250. if (engineeringInfo !== null) {
  251. if (engineeringInfo.billsGuidance_lib) {
  252. for (let billsGuidanceLib of engineeringInfo.billsGuidance_lib) {
  253. let stdBillsGuidanceLib = await stdBillsGuidanceLibModel.findOne({ ID: billsGuidanceLib.id });
  254. if (stdBillsGuidanceLib) {
  255. billsGuidanceLib.type = stdBillsGuidanceLib.type ? stdBillsGuidanceLib.type : 1;
  256. }
  257. }
  258. }
  259. projInfo.engineeringInfo = engineeringInfo;
  260. }
  261. //读取建设项目的基本信息
  262. let basicInfo = await ProjectsData.getBasicInfo(projectID);
  263. if(basicInfo !== null){
  264. projInfo.property.basicInformation = basicInfo;
  265. }
  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. //await pm_facade.prepareShareList();
  290. // 获取编办信息
  291. let sessionCompilation = request.session.sessionCompilation;
  292. if (sessionCompilation === undefined || sessionCompilation === null) {
  293. return response.redirect('/logout');
  294. }
  295. let compilationModel = new CompilationModel();
  296. //更新编办信息
  297. let compilationData = await compilationModel.getCompilationById(sessionCompilation._id);
  298. request.session.sessionCompilation = compilationData;
  299. sessionCompilation = request.session.sessionCompilation;
  300. //更新用户的使用过的费用定额列表
  301. let isFirst = await pm_facade.isFirst(request.session.sessionUser.id, compilationData._id.toString());
  302. let engineeringLibModel = new EngineeringLibModel();
  303. // 建议估算
  304. let suggestionValuation = sessionCompilation.suggestion_valuation !== undefined ?
  305. sessionCompilation.suggestion_valuation : [];
  306. suggestionValuation = await engineeringLibModel.getLib(suggestionValuation);
  307. // 可行性估算
  308. let feasibilityValuation = sessionCompilation.feasibility_valuation !== undefined ?
  309. sessionCompilation.feasibility_valuation : [];
  310. feasibilityValuation = await engineeringLibModel.getLib(feasibilityValuation);
  311. // 概算
  312. let roughValuation = sessionCompilation.rough_valuation !== undefined ?
  313. sessionCompilation.rough_valuation : [];
  314. roughValuation = await engineeringLibModel.getLib(roughValuation);
  315. // 清单计价
  316. let billValuation = sessionCompilation.bill_valuation !== undefined ?
  317. sessionCompilation.bill_valuation : [];
  318. billValuation = await engineeringLibModel.getLib(billValuation);
  319. // 定额计价
  320. let rationValuation = sessionCompilation.ration_valuation !== undefined ?
  321. sessionCompilation.ration_valuation : [];
  322. rationValuation = await engineeringLibModel.getLib(rationValuation);
  323. let absoluteUrl = compilationData.overWriteUrl ? request.app.locals.rootDir + compilationData.overWriteUrl : request.app.locals.rootDir;
  324. let overWriteUrl = fs.existsSync(absoluteUrl) && fs.statSync(absoluteUrl).isFile() ? compilationData.overWriteUrl : null;
  325. //欢迎页显示控制
  326. let [isShow,context,showTime] = await pm_facade.getWelcomeInfo(sessionCompilation._id,request.session.sessionUser,request.session.compilationVersion.includes('学习'));
  327. const unreadShareList = await pm_facade.getUnreadShareListByCompilation(request.session.sessionUser.id, sessionCompilation._id);
  328. let renderData = {
  329. unreadShareList: JSON.stringify(unreadShareList),
  330. isFirst: isFirst,
  331. isShow:isShow,
  332. context:context,
  333. showTime:showTime,
  334. userAccount: request.session.userAccount,
  335. userID: request.session.sessionUser.id,
  336. compilationData: JSON.stringify(sessionCompilation),
  337. overWriteUrl: overWriteUrl,
  338. suggestionValuation: JSON.stringify(suggestionValuation),
  339. feasibilityValuation: JSON.stringify(feasibilityValuation),
  340. roughValuation: JSON.stringify(roughValuation),
  341. billValuation: JSON.stringify(billValuation),
  342. rationValuation: JSON.stringify(rationValuation),
  343. engineeringList: JSON.stringify(engineering.List),
  344. compilationName: sessionCompilation.name,
  345. versionName: request.session.compilationVersion,
  346. socketPort:config[process.env.NODE_ENV].socketPort?config[process.env.NODE_ENV].socketPort:5500,
  347. LicenseKey:config.getLicenseKey(process.env.NODE_ENV),
  348. title:config[process.env.NODE_ENV].title?config[process.env.NODE_ENV].title:"纵横公路养护云造价"
  349. };
  350. response.render('building_saas/pm/html/project-management.html', renderData);
  351. },
  352. //第一次进入该费用定额时准备的初始数据
  353. prepareInitialData: async function (request, response) {
  354. try {
  355. const data = {
  356. userID: request.session.sessionUser.id,
  357. compilationID: request.session.sessionCompilation._id,
  358. example: request.session.sessionCompilation.example
  359. };
  360. await redirectToImportServer(data, 'prepareInitialData', request);
  361. callback(request, response, 0, 'success', null);
  362. } catch (err) {
  363. console.log(err);
  364. callback(request, response, 1, err.toString(), null);
  365. }
  366. },
  367. // 获取单价文件列表
  368. getUnitFileList: async function (request, response) {
  369. let data = request.body.data;
  370. try {
  371. data = JSON.parse(data);
  372. let projectId = data.parentID !== undefined ? data.parentID : 0;
  373. if (isNaN(projectId) && projectId <= 0) {
  374. throw { msg: 'id数据有误!', err: 1 };
  375. }
  376. /*// 获取对应建设项目下所有的单位工程id
  377. let idList = await ProjectsData.getTenderByProjectId(projectId);
  378. if (idList.length <= 0) {
  379. throw {msg: '不存在对应单位工程', err: 0};
  380. }*/
  381. // 获取对应的单价文件
  382. let unitPriceFileModel = new UnitPriceFileModel();
  383. let unitPriceFileData = await unitPriceFileModel.getDataByRootProject(projectId);
  384. if (unitPriceFileData === null) {
  385. throw { msg: '不存在对应单价文件', err: 0 };
  386. }
  387. // 整理数据
  388. let unitPriceFileList = [];
  389. for (let unitPriceFile of unitPriceFileData) {
  390. let tmp = {
  391. name: unitPriceFile.name,
  392. id: unitPriceFile.id
  393. };
  394. unitPriceFileList.push(tmp);
  395. }
  396. callback(request, response, 0, '', unitPriceFileList);
  397. } catch (error) {
  398. console.log(error);
  399. let responseData = error.err === 1 ? null : [];
  400. callback(request, response, error.err, error.msg, responseData);
  401. }
  402. },
  403. getFeeRateFileList: async function (request, response) {
  404. let data = request.body.data;
  405. try {
  406. data = JSON.parse(data);
  407. let projectId = data.parentID !== undefined ? data.parentID : 0;
  408. if (isNaN(projectId) && projectId <= 0) {
  409. throw { msg: 'id数据有误!', err: 1 };
  410. }
  411. // 获取对应建设项目下所有的单位工程id
  412. let feeRateFileList = await fee_rate_facade.getFeeRatesByProject(projectId);
  413. callback(request, response, 0, '', feeRateFileList);
  414. } catch (error) {
  415. console.log(error);
  416. let responseData = error.err === 1 ? null : [];
  417. callback(request, response, error.err, error.msg, responseData);
  418. }
  419. },
  420. getGC: async function(req, res) {
  421. const userID = req.session.sessionUser.id;
  422. const compilationId = req.session.sessionCompilation._id;
  423. try {
  424. const rst = [];
  425. const priceFilesTask = ProjectsData.getGCFiles(fileType.unitPriceFile, userID);
  426. const feeRateFilesTask = ProjectsData.getGCFiles(fileType.feeRateFile, userID);
  427. const tendersTask = ProjectsData.getGCFiles(projType.tender, userID);
  428. const [priceFiles, rateFiles, tenders] = await Promise.all([priceFilesTask, feeRateFilesTask, tendersTask]);
  429. // 建设项目
  430. let projectIDs = tenders.reduce((acc, cur) => {
  431. acc.push(cur.ParentID);
  432. return acc;
  433. }, []);
  434. projectIDs = [...new Set(projectIDs)];
  435. const projects = await ProjectsData.getProjectsByIds(userID, compilationId, projectIDs);
  436. projects.forEach(project => {
  437. const projectDoc = project._doc;
  438. const relTenders = tenders.filter(tender => tender.ParentID === projectDoc.ID);
  439. const unitPriceFiles = priceFiles.filter(file => relTenders.find(tender => tender.property.unitPriceFile.id === file.id));
  440. const feeRateFiles = rateFiles.filter(file => relTenders.find(tender => tender.property.feeFile.id === file.ID));
  441. projectDoc.children = relTenders;
  442. projectDoc.unitPriceFiles = unitPriceFiles;
  443. projectDoc.feeRateFiles = feeRateFiles;
  444. rst.push(projectDoc);
  445. });
  446. callback(req, res, 0, 'success', rst);
  447. } catch (err) {
  448. console.log(err);
  449. callback(req, res, true, err.message, null);
  450. }
  451. },
  452. getGCDatas: async function (request, response) {
  453. let userID = request.session.sessionUser.id;
  454. let compilatoinId = request.session.sessionCompilation._id;
  455. let rst = [];
  456. let _projs = Object.create(null), _engs = Object.create(null), prefix = 'ID_';
  457. try {
  458. let gc_unitPriceFiles = await ProjectsData.getGCFiles(fileType.unitPriceFile, userID);
  459. let gc_feeRateFiles = await ProjectsData.getGCFiles(fileType.feeRateFile, userID);
  460. let gc_tenderFiles = await ProjectsData.getGCFiles(projType.tender, userID);
  461. for (let i = 0, len = gc_unitPriceFiles.length; i < len; i++) {
  462. let gc_uf = gc_unitPriceFiles[i];
  463. let theProj = _projs[prefix + gc_uf.root_project_id] || null;
  464. if (!theProj) {
  465. let tempProj = await ProjectsData.getProjectsByIds(userID, compilatoinId, [gc_uf.root_project_id]);
  466. if (tempProj.length > 0 && tempProj[0].projType !== projType.folder) {
  467. theProj = _projs[prefix + gc_uf.root_project_id] = tempProj[0]._doc;
  468. buildProj(theProj);
  469. }
  470. }
  471. if (theProj) {
  472. theProj.unitPriceFiles.push(gc_uf);
  473. }
  474. }
  475. for (let i = 0, len = gc_feeRateFiles.length; i < len; i++) {
  476. let gc_ff = gc_feeRateFiles[i];
  477. let theProj = _projs[prefix + gc_ff.rootProjectID] || null;
  478. if (!theProj) {
  479. let tempProj = await ProjectsData.getProjectsByIds(userID, compilatoinId, [gc_ff.rootProjectID]);
  480. if (tempProj.length > 0 && tempProj[0].projType !== projType.folder) {
  481. theProj = _projs[prefix + gc_ff.rootProjectID] = tempProj[0]._doc;
  482. buildProj(theProj);
  483. }
  484. }
  485. if (theProj) {
  486. theProj.feeRateFiles.push(gc_ff);
  487. }
  488. }
  489. if (gc_tenderFiles.length > 0) {
  490. for (let i = 0, len = gc_tenderFiles.length; i < len; i++) {
  491. let gc_t = gc_tenderFiles[i];
  492. let theProj = _projs[prefix + gc_t.ParentID] || null;
  493. if(!theProj){
  494. let tempProjs = await ProjectsData.getProjectsByIds(userID, compilatoinId, [gc_t.ParentID]);
  495. if(tempProjs.length > 0 && tempProjs[0].projType === projType.project){
  496. theProj = _projs[prefix + gc_t.ParentID] = tempProjs[0]._doc;
  497. buildProj(theProj);
  498. }
  499. }
  500. if(theProj) {
  501. theProj.children.push(gc_t);
  502. }
  503. }
  504. }
  505. for (let i in _projs) {
  506. rst.push(_projs[i]);
  507. }
  508. function buildProj(proj) {
  509. proj.children = [];
  510. proj.unitPriceFiles = [];
  511. proj.feeRateFiles = [];
  512. }
  513. callback(request, response, 0, 'success', rst);
  514. }
  515. catch (error) {
  516. callback(request, response, true, error, null);
  517. }
  518. },
  519. recGC: function (request, response) {
  520. let userID = request.session.sessionUser.id,
  521. compilationId = request.session.sessionCompilation._id;
  522. let data = JSON.parse(request.body.data);
  523. let nodes = data.nodes;
  524. ProjectsData.recGC(userID, compilationId, nodes, function (err, msg, data) {
  525. callback(request, response, err, msg, data);
  526. });
  527. },
  528. delGC: async function (request, response) {
  529. let data = JSON.parse(request.body.data);
  530. let delDatas = data.delDatas;
  531. let bulkProjs = [], bulkUFs = [], bulkFFs = [];
  532. try {
  533. for (let data of delDatas) {
  534. if (data.updateType === 'Project') {
  535. bulkProjs.push({ updateOne: { filter: { ID: data.ID }, update: { 'deleteInfo.completeDeleted': true } } });
  536. }
  537. else if (data.updateType === fileType.unitPriceFile) {
  538. bulkUFs.push({ updateOne: { filter: { id: data.ID }, update: { 'deleteInfo.completeDeleted': true } } });
  539. }
  540. else {
  541. bulkFFs.push({ updateOne: { filter: { ID: data.ID }, update: { 'deleteInfo.completeDeleted': true } } });
  542. }
  543. }
  544. if (bulkProjs.length > 0) {
  545. await projectModel.bulkWrite(bulkProjs);
  546. }
  547. if (bulkUFs.length > 0) {
  548. await unitPriceFileModel.bulkWrite(bulkUFs);
  549. }
  550. if (bulkFFs.length > 0) {
  551. await feeRateFileModel.bulkWrite(bulkFFs);
  552. }
  553. callback(request, response, 0, 'success', null);
  554. } catch (err) {
  555. callback(request, response, 1, err, null);
  556. }
  557. },
  558. moveProject: async function (req, res) {
  559. let result = {
  560. error: 0
  561. };
  562. try {
  563. let data = req.body.data;
  564. let rdata = await pm_facade.moveProject(data);
  565. result.data = rdata;
  566. } catch (err) {
  567. console.log(err);
  568. result.error = 1;
  569. result.message = err.message;
  570. }
  571. res.json(result);
  572. },
  573. copyProjects: async function (req, res) {
  574. let result = {
  575. error: 0
  576. };
  577. try {
  578. let data = { dataString: req.body.data, userID: req.session.sessionUser.id, compilationID: req.session.sessionCompilation._id };
  579. result = await redirectToImportServer(data, "copyProject", req);
  580. } catch (err) {
  581. console.log(err);
  582. result.error = 1;
  583. result.message = err.message;
  584. }
  585. res.json(result);
  586. },
  587. projectShareInfo: async function (req, res) {
  588. try {
  589. const data = JSON.parse(req.body.data);
  590. const shareList = await pm_facade.getShareList({ projectID: data.projectID });
  591. const shareInfoMap = await pm_facade.getShareInfoMap(null, shareList);
  592. const shareInfo = shareInfoMap[data.projectID] || [];
  593. callback(req, res, 0, 'success', shareInfo);
  594. }
  595. catch (err) {
  596. callback(req, res, 1, err, null);
  597. }
  598. },
  599. getRecentShareInfo: async function (req, res) {
  600. try {
  601. const { count } = JSON.parse(req.body.data);
  602. const userID = req.session.sessionUser.id;
  603. const recentUsers = await pm_facade.getRecentShareList(userID, count);
  604. const contacts = await userModelObj.getContacts(userID);
  605. callback(req, res, 0, 'success', { recentUsers, contacts });
  606. } catch (err) {
  607. console.log(err);
  608. callback(req, res, 1, err.message, null);
  609. }
  610. },
  611. getInitialShareData: async function (req, res) {
  612. try {
  613. const { count, projectID } = JSON.parse(req.body.data);
  614. // 分享建设项目,仅提供给专业版用户
  615. /* const proShareProjType = [projType.folder, projType.project];
  616. const project = await projectModel.findOne({ ID: projectID }, 'projType');
  617. if (project && proShareProjType.indexOf(project.projType) >= 0) {
  618. const isFree = userModelObj.isFreeFromSession(req.session.compilationVersion);
  619. if (isFree) {
  620. callback(req, res, 0, 'success', { isFree });
  621. return;
  622. }
  623. } */
  624. const userID = req.session.sessionUser.id;
  625. // 最近分享
  626. const recentUsers = await pm_facade.getRecentShareList(userID, count);
  627. // 联系人
  628. const contacts = await userModelObj.getContacts(userID);
  629. // 分享过的人
  630. const sharedUsers = await pm_facade.getProjectShareList(projectID);
  631. callback(req, res, 0, 'success', { recentUsers, contacts, sharedUsers });
  632. } catch (err) {
  633. console.log(err);
  634. callback(req, res, 1, err.message, null);
  635. }
  636. },
  637. getReceiveLibList: async function (req, res) {
  638. try {
  639. const { libType } = JSON.parse(req.body.data);
  640. const userID = req.session.sessionUser.id;
  641. const compilationID = req.session.sessionCompilation._id;
  642. const list = await pm_facade.getReceiveLibList(userID, compilationID, libType);
  643. callback(req, res, 0, 'success', list);
  644. } catch (err) {
  645. callback(req, res, 1, err.message, null);
  646. }
  647. },
  648. getInitialShareLibData: async function (req, res) {
  649. try {
  650. const { libType, count } = JSON.parse(req.body.data);
  651. const userID = req.session.sessionUser.id;
  652. const compilationID = req.session.sessionCompilation._id;
  653. // 最近分享
  654. const recentUsers = await pm_facade.getRecentShareList(userID, count);
  655. // 联系人
  656. const contacts = await userModelObj.getContacts(userID);
  657. // 分享过的人
  658. const sharedUsers = await pm_facade.getLibShareList(userID, compilationID, libType, count);
  659. callback(req, res, 0, 'success', { recentUsers, contacts, sharedUsers });
  660. } catch (err) {
  661. console.log(err);
  662. callback(req, res, 1, err.message, null);
  663. }
  664. },
  665. shareLib: async function (req, res) {
  666. try {
  667. const { type, libType, shareData, count } = JSON.parse(req.body.data);
  668. const owner = req.session.sessionUser.id;
  669. const compilationID = req.session.sessionCompilation._id;
  670. const shareDate = moment(Date.now()).format('YYYY-MM-DD HH:mm:ss');
  671. shareData.forEach(item => item.shareDate = shareDate);
  672. const task = [];
  673. // 是否只是单纯的更新分享选项,如果不是,需要重新获取最近分享和联系人
  674. let isSimpleUpdate = true;
  675. if (type === 'create') {
  676. isSimpleUpdate = false;
  677. // 生成分享记录
  678. const docs = shareData.map(item => ({
  679. compilationID,
  680. owner,
  681. libType,
  682. ID: uuidV1(),
  683. receiver: item.receiver,
  684. allowCooperate: false,
  685. shareDate: item.shareDate,
  686. updateDate: item.shareDate
  687. }));
  688. task.push(pm_facade.addShareList(docs, true));
  689. // 分享即互相添加为联系人
  690. task.push(userModelObj.addContact(docs[0].owner, docs[0].receiver));
  691. } else if (type === 'cancel') { // 取消分享
  692. const cancelReceivers = shareData.map(item => item.receiver);
  693. task.push(pm_facade.deleteShareList({ owner, libType, compilationID, receiver: { $in: cancelReceivers } }, true));
  694. }
  695. await Promise.all(task);
  696. const rst = {};
  697. if (!isSimpleUpdate) {
  698. const rstTask = [
  699. pm_facade.getRecentShareList(owner, count),
  700. userModelObj.getContacts(owner)
  701. ];
  702. const [recentUsers, contacts] = await Promise.all(rstTask);
  703. Object.assign(rst, { recentUsers, contacts });
  704. }
  705. callback(req, res, 0, 'success', rst);
  706. } catch (err) {
  707. console.log(err);
  708. logger.info(err);
  709. callback(req, res, 1, err, null);
  710. }
  711. },
  712. share: async function (req, res) {
  713. try {
  714. const data = JSON.parse(req.body.data);
  715. const { type, permissionType, shareData, projectID, count } = data;
  716. const userID = req.session.sessionUser.id;
  717. const shareDate = moment(Date.now()).format('YYYY-MM-DD HH:mm:ss');
  718. shareData.forEach(item => item.shareDate = shareDate);
  719. const task = [];
  720. // 是否只是单纯的更新分享选项,如果不是,需要重新获取最近分享和联系人
  721. let isSimpleUpdate = true;
  722. if (type === 'create') {
  723. isSimpleUpdate = false;
  724. // 生成分享记录
  725. const docs = shareData.map(item => ({
  726. ID: uuidV1(),
  727. projectID,
  728. owner: userID,
  729. receiver: item.userID,
  730. allowCooperate: item.allowCooperate,
  731. allowCopy: item.allowCopy,
  732. shareDate: item.shareDate,
  733. updateDate: item.shareDate
  734. }));
  735. task.push(pm_facade.addShareList(docs));
  736. // 分享即互相添加为联系人
  737. task.push(userModelObj.addContact(docs[0].owner, docs[0].receiver));
  738. } else if (type === 'update') {
  739. // 取消分享(以前项目管理界面可一次进行更新和取消)
  740. const cancelReceivers = shareData
  741. .filter(item => item.isCancel)
  742. .map(item => item.userID);
  743. if (cancelReceivers.length) {
  744. isSimpleUpdate = false;
  745. task.push(pm_facade.deleteShareList({ projectID, receiver: { $in: cancelReceivers } }));
  746. }
  747. // 更新分享选项
  748. const updateData = shareData
  749. .filter(item => !item.isCancel)
  750. .map(item => {
  751. const update = { updateDate: shareDate };
  752. if (commonUtil.isDef(item.allowCopy)) {
  753. update.allowCopy = item.allowCopy;
  754. }
  755. if (commonUtil.isDef(item.allowCooperate)) {
  756. update.allowCooperate = item.allowCooperate;
  757. }
  758. return {
  759. query: {
  760. projectID,
  761. receiver: item.userID
  762. },
  763. update
  764. };
  765. });
  766. if (updateData.length) {
  767. task.push(pm_facade.updateShareList(updateData))
  768. }
  769. } else { // 取消分享
  770. const cancelReceivers = shareData.map(item => item.userID);
  771. task.push(pm_facade.deleteShareList({ projectID, receiver: { $in: cancelReceivers } }));
  772. }
  773. await Promise.all(task);
  774. // 获取需要广播推送的单位工程
  775. // shareData数组的形式是以前需求需要,现在的需求下,shareData数组必定只有一个元素
  776. const emitTenders = await pm_facade.getShareInfoAfterChangePermission(permissionType, shareData[0].userID, projectID);
  777. let rst = { emitTenders };
  778. if (!isSimpleUpdate) {
  779. const rstTask = [
  780. pm_facade.getRecentShareList(userID, count),
  781. userModelObj.getContacts(userID)
  782. ];
  783. const [recentUsers, contacts] = await Promise.all(rstTask);
  784. Object.assign(rst, { recentUsers, contacts });
  785. }
  786. callback(req, res, 0, 'success', rst);
  787. }
  788. catch (err) {
  789. console.log(err);
  790. callback(req, res, 1, String(err), null);
  791. }
  792. },
  793. receiveProjects: async function (req, res) {
  794. try {
  795. let rst = { grouped: [], ungrouped: [], summaryInfo: null };
  796. let userID = req.session.sessionUser.id;
  797. const shareList = await pm_facade.getShareList({ receiver: userID });
  798. const receiveProjectIDs = shareList.map(item => item.projectID);
  799. const compilation = req.session.sessionCompilation._id;
  800. const notDeleted = [{ deleteInfo: null }, { 'deleteInfo.deleted': false }];
  801. const receiveProjects = await projectModel.find({ ID: { $in: receiveProjectIDs }, compilation, $or: notDeleted }, '-_id').lean();
  802. //设置原项目用户信息
  803. const shareInfoMap = await pm_facade.getShareInfoMap(null, shareList);
  804. if (receiveProjects.length > 0) {
  805. let orgUserIDs = [];
  806. for (let proj of receiveProjects) {
  807. orgUserIDs.push(proj.userID);
  808. if (proj.projType === projType.tender) {
  809. // 设置项目类别
  810. proj.valuationType = ValuationText[proj.property.valuationType] || '';
  811. proj._valuationType = proj.property.valuationType;
  812. //设置工程专业
  813. proj.feeStandardName = proj.property.feeStandardName || '';
  814. //设置计税方法
  815. proj.taxType = proj.property.taxType;
  816. }
  817. delete proj.property;
  818. }
  819. orgUserIDs = Array.from(new Set(orgUserIDs));
  820. let userObjIDs = [];
  821. for (let uID of orgUserIDs) {
  822. userObjIDs.push(mongoose.Types.ObjectId(uID));
  823. }
  824. let orgUsersInfo = await userModel.find({ _id: { $in: userObjIDs } });
  825. //建设项目
  826. let consProjIDs = [],
  827. ungroupedTenders = [];
  828. for (let proj of receiveProjects) {
  829. // 设置分享信息
  830. proj.shareInfo = shareInfoMap[proj.ID] || [];
  831. if (proj.projType === projType.project) {
  832. consProjIDs.push(proj.ID);
  833. }
  834. //获取分享项目子项
  835. if (proj.projType !== projType.tender) {
  836. proj.children = await pm_facade.getPosterityProjects([proj.ID]);
  837. for (let projC of proj.children) {
  838. // 设置分享信息
  839. projC.shareInfo = shareInfoMap[projC.ID] || [];
  840. if (projC.projType === projType.project) {
  841. consProjIDs.push(projC.ID);
  842. } else if (projC.projType === projType.tender) {
  843. // 设置项目类别
  844. projC.valuationType = ValuationText[projC.property.valuationType] || '';
  845. projC._valuationType = projC.property.valuationType;
  846. //设置工程专业
  847. projC.feeStandardName = projC.property.feeStandardName || '';
  848. }
  849. delete projC.property;
  850. }
  851. } else {//未分类的单位工程不进行汇总,只取价格信息
  852. ungroupedTenders.push(proj);
  853. }
  854. //设置分组,单位工程及单项工程分到未分组那
  855. if (proj.projType === projType.tender || proj.projType === projType.engineering) {
  856. rst.ungrouped.push(proj);
  857. } else {
  858. rst.grouped.push(proj);
  859. }
  860. //设置项目类型为来自别人分享
  861. proj.shareType = 'receive';
  862. for (let userData of orgUsersInfo) {
  863. if (proj.userID == userData._id.toString()) {
  864. let userInfo = { name: userData.real_name, mobile: userData.mobile, company: userData.company, email: userData.email };
  865. proj.userInfo = userInfo;
  866. }
  867. }
  868. }
  869. consProjIDs = Array.from(new Set(consProjIDs));
  870. let summaryInfo = await pm_facade.getSummaryInfo(consProjIDs);
  871. let tendersFeeInfo = await pm_facade.getTendersFeeInfo(ungroupedTenders);
  872. rst.summaryInfo = { grouped: summaryInfo, ungrouped: tendersFeeInfo };
  873. }
  874. callback(req, res, 0, 'success', rst);
  875. }
  876. catch (err) {
  877. console.log(err);
  878. callback(req, res, 1, err, null);
  879. }
  880. },
  881. getProjectsByQuery: async function (req, res) {
  882. try {
  883. let data = JSON.parse(req.body.data);
  884. let compilation = req.session.sessionCompilation._id;
  885. let query = data.query;
  886. query.compilation = compilation;
  887. let options = data.options;
  888. let projects = await projectModel.find(query, options);
  889. callback(req, res, 0, 'success', projects);
  890. }
  891. catch (err) {
  892. callback(req, res, 1, err, null);
  893. }
  894. },
  895. getSummaryInfo: async function (req, res) {
  896. try {
  897. let data = JSON.parse(req.body.data);
  898. let summaryInfo = await pm_facade.getSummaryInfo(data.projectIDs);
  899. callback(req, res, 0, 'success', summaryInfo);
  900. }
  901. catch (err) {
  902. callback(req, res, 1, err, null);
  903. }
  904. },
  905. changeFile: async function (req, res) {
  906. try {
  907. let data = JSON.parse(req.body.data);
  908. console.log(data);
  909. await pm_facade.changeFile(data.projects, data.user_id, data.fileID, data.name, data.from, data.type);
  910. callback(req, res, 0, 'success', []);
  911. }
  912. catch (err) {
  913. console.log(err);
  914. callback(req, res, 1, err, null);
  915. }
  916. },
  917. exportProject: async function (req, res) {
  918. let result = {
  919. error: 0
  920. };
  921. try {
  922. let data = { dataString: req.body.data, userID: req.session.sessionUser.id };
  923. result = await redirectToImportServer(data, "exportProject", req);
  924. } catch (err) {
  925. console.log(err);
  926. result.error = 1;
  927. result.message = err.message;
  928. }
  929. res.json(result);
  930. },
  931. importProject: async function (req, res) {
  932. let data = JSON.parse(req.body.data);
  933. let result = {
  934. error: 0
  935. };
  936. try {
  937. data.session = req.session;
  938. result = await redirectToImportServer(data,"importProject",req);
  939. } catch (err) {
  940. console.log(err);
  941. result.error = 1;
  942. result.message = err.message;
  943. }
  944. res.json(result);
  945. },
  946. copyConstructionProject: async function (req, res) {
  947. let data = JSON.parse(req.body.data);
  948. let result = {
  949. error: 0
  950. };
  951. try {
  952. data.session = req.session;
  953. result.data = await redirectToImportServer(data, "copyConstructionProject", req);
  954. } catch (err) {
  955. console.log(err);
  956. result.error = 1;
  957. result.message = err.message;
  958. }
  959. res.json(result);
  960. },
  961. importProcessChecking: async function (req, res) {
  962. let result = {
  963. error: 0
  964. };
  965. try {
  966. let data = JSON.parse(req.body.data);
  967. data.userID = req.session.sessionUser.id;
  968. data.compilationID = req.session.sessionCompilation._id;
  969. result.data = await pm_facade.importProcessChecking(data);
  970. } catch (err) {
  971. console.log(err);
  972. result.error = 1;
  973. result.message = err.message;
  974. }
  975. res.json(result);
  976. },
  977. getUploadToken: function (req, res) {
  978. let result = {
  979. error: 0
  980. };
  981. try {
  982. result = pm_facade.uploadToken();
  983. } catch (err) {
  984. console.log(err);
  985. result.error = 1;
  986. result.message = err.message;
  987. }
  988. res.json(result);
  989. },
  990. getProjectByGranularity: async function (req, res) {
  991. try {
  992. const data = JSON.parse(req.body.data);
  993. const userID = req.session.sessionUser.id;
  994. const version = req.session.compilationVersion;
  995. const projData = await pm_facade.getProjectByGranularity(data.tenderID, data.granularity, data.requestForSummaryInfo, userID, version);
  996. callback(req, res, 0, 'success', projData);
  997. } catch (err) {
  998. callback(req, res, 1, err, null);
  999. }
  1000. },
  1001. getImportTemplateData: async function (req, res) {
  1002. try {
  1003. const data = JSON.parse(req.body.data);
  1004. const templateData = await pm_facade.getImportTemplateData(req.session.sessionCompilation._id, data.feeName, data.valuationID, data.projectCount);
  1005. callback(req, res, 0, 'success', templateData);
  1006. } catch (err) {
  1007. callback(req, res, 1, err, null);
  1008. }
  1009. },
  1010. importInterface: async function (req, res) {
  1011. const data = JSON.parse(req.body.data);
  1012. let result = {
  1013. error: 0
  1014. };
  1015. try {
  1016. data.session = req.session;
  1017. result = await redirectToImportServer(data, "importInterface", req);
  1018. } catch (err) {
  1019. console.log(err);
  1020. result.error = 1;
  1021. result.message = err.message;
  1022. }
  1023. res.json(result);
  1024. },
  1025. };
  1026. async function redirectToImportServer(data, action, req) {
  1027. let importURL = config.getImportURL(process.env.NODE_ENV, req.headers.origin);
  1028. let options = {
  1029. method: 'POST',
  1030. uri: `http://${importURL}/import/${action}`,
  1031. body: data,
  1032. timeout: 220000,
  1033. json: true
  1034. };
  1035. console.log("post import data to:" + options.uri);
  1036. return await rp.post(options);
  1037. }