pm_controller.js 50 KB

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