pm_controller.js 45 KB

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