pm_controller.js 44 KB

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