pm_controller.js 44 KB

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