project_facade.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863
  1. /**
  2. * Created by zhang on 2018/1/26.
  3. */
  4. module.exports = {
  5. markUpdateProject: markUpdateProject,
  6. removeProjectMark: removeProjectMark,
  7. updateNodes: updateNodes,
  8. saveProperty: saveProperty,
  9. getDefaultColSetting: getDefaultColSetting,
  10. markProjectsToChange: markProjectsToChange,
  11. getBudgetSummayDatas: getBudgetSummayDatas,
  12. getGLJSummayDatas: getGLJSummayDatas,
  13. };
  14. let mongoose = require('mongoose');
  15. let logger = require("../../../logs/log_helper").logger;
  16. let projectsModel = mongoose.model('projects');
  17. let async_n = require("async");
  18. let _ = require('lodash');
  19. let ration_model = require('../models/ration');
  20. let optionModel = mongoose.model('options');
  21. let bill_model = require('../models/bills');
  22. let consts = require('../models/project_consts');
  23. let projectConsts = consts.projectConst;
  24. let ration_glj_model = mongoose.model('ration_glj');
  25. let rationTemplateModel = mongoose.model('ration_template');
  26. let project_glj_model = mongoose.model('glj_list');
  27. let ration_glj_facade = require("../../ration_glj/facade/ration_glj_facade");
  28. const uuidV1 = require('uuid/v1');
  29. const gljUtil = require('../../../public/gljUtil');
  30. let stdColSettingModel = mongoose.model('std_main_col_lib');
  31. let decimal_facade = require('../../main/facade/decimal_facade');
  32. const scMathUtil = require('../../../public/scMathUtil').getUtil();
  33. const calcUtil = require('../../../public/calculate_util')
  34. const {
  35. fixedFlag
  36. } = require('../../../public/common_constants');
  37. const GLJListModel = require("../../glj/models/glj_list_model");
  38. const projectDao = require('../../pm/models/project_model').project;
  39. async function createRationGLJData(glj) {
  40. glj.ID = uuidV1();
  41. let [info, projectGLJ] = await ration_glj_facade.getInfoFromProjectGLJ(glj);
  42. let newRecode = ration_glj_facade.createNewRecord(info);
  43. return [newRecode, projectGLJ];
  44. }
  45. function generateTasks(data, userID) {
  46. let tasks = [];
  47. let deleteInfo = {
  48. deleted: true,
  49. deleteDateTime: new Date(),
  50. deleteBy: userID
  51. };
  52. if (data.delete && data.delete.length > 0) {
  53. for (let bd of data.delete) {
  54. //原先是假删除,现在改成真删除
  55. let task = {
  56. deleteOne: {
  57. filter: {
  58. ID: bd.ID,
  59. projectID: bd.projectID
  60. }
  61. }
  62. };
  63. /* let task={
  64. updateOne:{
  65. filter:{
  66. ID:bd.ID,
  67. projectID:bd.projectID
  68. },
  69. update :{
  70. deleteInfo:deleteInfo
  71. }
  72. }
  73. };*/
  74. tasks.push(task);
  75. }
  76. }
  77. if (data.add && data.add.length > 0) {
  78. for (let n_data of data.add) {
  79. let task = {
  80. insertOne: {
  81. document: n_data
  82. }
  83. };
  84. tasks.push(task);
  85. }
  86. }
  87. return tasks;
  88. }
  89. async function updateNodes(datas) {
  90. let nodeGroups = _.groupBy(datas, 'type');
  91. let asyncTasks = [];
  92. let deleteRationIDs = [];
  93. let taskMap = {};
  94. taskMap[projectConsts.BILLS] = {
  95. tasks: [],
  96. model: bill_model.model
  97. };
  98. taskMap[projectConsts.RATION] = {
  99. tasks: [],
  100. model: ration_model.model
  101. };
  102. taskMap[projectConsts.RATION_GLJ] = {
  103. tasks: [],
  104. model: ration_glj_model
  105. };
  106. taskMap[projectConsts.PROJECTGLJ] = {
  107. tasks: [],
  108. model: project_glj_model
  109. };
  110. taskMap[projectConsts.PROJECT] = {
  111. tasks: [],
  112. model: projectsModel
  113. };
  114. taskMap[projectConsts.RATION_TEMPLATE] = {
  115. tasks: [],
  116. model: rationTemplateModel
  117. };
  118. for (let type in nodeGroups) {
  119. for (let node of nodeGroups[type]) {
  120. if (taskMap[type]) {
  121. if (type == projectConsts.RATION) {
  122. if (node.action == "delete") deleteRationIDs.push(node.data.ID);
  123. }
  124. if (type == projectConsts.RATION_GLJ) {
  125. if (node.action == "add") { //添加定額工料机的時候,要先走项目工料机的逻辑
  126. let [newRecode, projectGLJ] = await createRationGLJData(node.data);
  127. node.data = newRecode;
  128. node.projectGLJ = projectGLJ;
  129. }
  130. }
  131. taskMap[type].tasks.push(getTask(node));
  132. }
  133. }
  134. }
  135. for (let key in taskMap) {
  136. if (taskMap[key].tasks.length > 0) asyncTasks.push(taskMap[key].model.bulkWrite(taskMap[key].tasks))
  137. }
  138. if (asyncTasks.length > 0) await Promise.all(asyncTasks);
  139. if (deleteRationIDs.length > 0) await ration_glj_model.deleteMany({
  140. rationID: {
  141. $in: deleteRationIDs
  142. }
  143. });
  144. return datas;
  145. function getTask(node, idFiled = 'ID') {
  146. let task = {};
  147. if (node.action == "add") {
  148. task.insertOne = {
  149. document: node.data
  150. }
  151. } else if (node.action == "delete") {
  152. task.deleteOne = {
  153. filter: {}
  154. };
  155. task.deleteOne.filter[idFiled] = node.data[idFiled];
  156. } else {
  157. task.updateOne = {
  158. filter: {},
  159. update: _.cloneDeep(node.data)
  160. };
  161. task.updateOne.filter[idFiled] = node.data[idFiled]; //现在复制项目也重新生成一个新的ID了,所以ID是唯一的
  162. delete task.updateOne.update[idFiled]; //防止误操作
  163. }
  164. return task;
  165. }
  166. }
  167. //data = {feeRateID:111111,projectID:1245}; type = feeRate
  168. async function markUpdateProject(data, type) {
  169. let query = {
  170. deleteInfo: null
  171. };
  172. if (type == "feeRate") { //更改了费率
  173. query['property.feeFile.id'] = data.feeRateID;
  174. }
  175. if (type == "unitFile") { //更改了单价文件
  176. query['property.unitPriceFile.id'] = data.unitFileID; //unitPriceFile
  177. }
  178. let projects = await projectsModel.find(query);
  179. return await markProjectsToChange(projects, type, data.projectID, data.isInclude);
  180. }
  181. async function markProjectsToChange(projects, type, extProjectID, isInclude) {
  182. let tasks = [];
  183. for (let p of projects) {
  184. if (isInclude != true) {
  185. if (extProjectID && p.ID === extProjectID) continue; //排除当前项目
  186. }
  187. tasks.push(generateMarkTask(type, p.ID));
  188. }
  189. return tasks.length > 0 ? await projectsModel.bulkWrite(tasks) : null;
  190. }
  191. async function removeProjectMark(projectID) {
  192. return await projectsModel.findOneAndUpdate({
  193. ID: projectID
  194. }, {
  195. "$unset": {
  196. "changeMark": 1
  197. }
  198. });
  199. }
  200. function generateMarkTask(value, projectID) {
  201. let task = {
  202. updateOne: {
  203. filter: {
  204. ID: projectID
  205. },
  206. update: {
  207. changeMark: value
  208. }
  209. }
  210. };
  211. return task
  212. }
  213. // {projectID: 5, propertyName: 'aaa', propertyValue: 1}
  214. function saveProperty(data, callback) {
  215. let obj = {};
  216. let pn = 'property.' + data.propertyName;
  217. obj[pn] = data.propertyValue;
  218. projectsModel.update({
  219. "ID": data.projectID
  220. }, obj, function (err) {
  221. if (err) {
  222. logger.err(pn + ' save error: ' + err);
  223. callback(err, null)
  224. } else {
  225. logger.info(pn + ' saved.');
  226. callback('', null);
  227. }
  228. });
  229. }
  230. async function getDefaultColSetting(libID) {
  231. return await stdColSettingModel.findOne({
  232. ID: libID,
  233. deleted: false
  234. }, '-_id main_tree_col');
  235. }
  236. async function getBudgetSummayDatas(projectIDs, userID, compilationID, overWriteUrl) {
  237. try {
  238. let projects = [];
  239. let names = [];
  240. let prjTypeNames = [];
  241. let compilationScopes = [];
  242. let decimal = null;
  243. let isProgressiveType = true;
  244. for (let ID of projectIDs) {
  245. projects.push(await getBillsByProjectID(ID));
  246. }
  247. if (projects.length == 0) {
  248. return [];
  249. }
  250. let mp = projects[0];
  251. names.push(mp.name);
  252. prjTypeNames.push(mp.prjTypeName);
  253. compilationScopes.push(mp.compilationScope);
  254. if (projects.length == 1) decimal = await decimal_facade.getProjectDecimal(projectIDs[0]); //如果只有一个项目,则没走合并的那一步,decimal会为空,从面报错
  255. for (let i = 1; i < projects.length; i++) {
  256. names.push(projects[i].name);
  257. prjTypeNames.push(projects[i].prjTypeName);
  258. compilationScopes.push(projects[i].compilationScope);
  259. decimal = await mergeProject(mp.roots, projects[i].roots);
  260. }
  261. let options_setting = await optionModel.findOne({
  262. user_id: userID,
  263. compilation_id: compilationID
  264. }).lean();
  265. if (options_setting && options_setting.options && options_setting.options.GENERALOPTS) isProgressiveType = options_setting.options.GENERALOPTS.progressiveType == 1 ? false : true;
  266. let SummaryAuditDetail = getReportData(names, mp.roots, prjTypeNames, compilationScopes, decimal, isProgressiveType, mp.progressiveInterval, overWriteUrl);
  267. let parentProject = await projectsModel.findOne({
  268. ID: mp.ParentID
  269. });
  270. let result = {
  271. prj: {},
  272. SummaryAudit: {
  273. "name": parentProject ? parentProject.name : "",
  274. "编制": mp.author,
  275. "复核": mp.auditor,
  276. "编制范围": mp.compilationScope
  277. },
  278. SummaryAuditDetail: SummaryAuditDetail
  279. };
  280. return result;
  281. } catch (e) {
  282. console.log(e.message)
  283. }
  284. }
  285. function getReportData(nameList, items, prjTypeNames, compilationScopes, decimal, isProgressiveType, progressiveInterval, overWriteUrl) {
  286. let datas = [],
  287. totalItem = null,
  288. one_to_four_Item = null;
  289. let overWrite = null;
  290. if (overWriteUrl && overWriteUrl != "") {
  291. overWrite = require("../../.." + overWriteUrl);
  292. }
  293. setChildrenDatas(items, datas);
  294. if (one_to_four_Item) recalcTotalItem(one_to_four_Item, datas, isProgressiveType, progressiveInterval);
  295. if (totalItem) recalcTotalItem(totalItem, datas, isProgressiveType, progressiveInterval);
  296. for (let d of datas) {
  297. if (d.billsTtlPrice && totalItem.billsTtlPrice) {
  298. d['各项费用比例'] = scMathUtil.roundForObj(d.billsTtlPrice / totalItem.billsTtlPrice * 100, 2)
  299. }
  300. d['prjNames'] = nameList;
  301. d['prjTypeNames'] = prjTypeNames;
  302. d['编制范围明细'] = compilationScopes;
  303. }
  304. return datas;
  305. function recalcTotalItem(item, datas, isProgressiveType, progressiveInterval) {
  306. let totalExp = item.calcBase;
  307. if (totalExp.indexOf('@') == -1) return;
  308. if (isProgressiveType && progressiveInterval) { //有累进的要重新计算总金额和技术经济综合指标
  309. for (let t of datas) {
  310. totalExp = totalExp.replace(t.ID, t.billsTtlPrice + "");
  311. }
  312. totalExp = totalExp.replace(/@/g, "");
  313. let nTotal = eval(totalExp);
  314. item.billsTtlPrice = scMathUtil.roundForObj(nTotal, decimal.bills.totalPrice);
  315. item['技术经济综合指标'] = (item.billsTtlAmt && parseFloat(item.billsTtlAmt) !== 0) ? scMathUtil.roundForObj(item.billsTtlPrice / item.billsTtlAmt, 2) : scMathUtil.roundForObj(item.billsTtlPrice, 2);
  316. }
  317. }
  318. function setChildrenDatas(children, arr, level = 0, rootFlag) {
  319. let temTotalPrice = 0;
  320. for (let c of children) {
  321. if (level == 0) rootFlag = c.flag; //取最顶层节点的固定清单类别
  322. let tbill = getBillDatas(c, level, rootFlag);
  323. arr.push(tbill);
  324. let sumChildren = setChildrenDatas(c.children, arr, level + 1, rootFlag);
  325. if (isProgressiveType && progressiveInterval && rootFlag == fixedFlag.MAINTENANCE_EXPENSES) { //如果要累进的,父节点要重新汇总
  326. if (c.children.length > 0) {
  327. tbill.billsTtlPrice = sumChildren;
  328. tbill['技术经济综合指标'] = (tbill.billsTtlAmt && parseFloat(tbill.billsTtlAmt) !== 0) ? scMathUtil.roundForObj(tbill.billsTtlPrice / tbill.billsTtlAmt, 2) : scMathUtil.roundForObj(tbill.billsTtlPrice, 2);
  329. }
  330. if (level > 0) temTotalPrice = scMathUtil.roundForObj(tbill.billsTtlPrice + temTotalPrice, decimal.bills.totalPrice);
  331. }
  332. }
  333. return temTotalPrice;
  334. }
  335. function getBillDatas(bills, level, rootFlag) {
  336. let tem = {
  337. ID: bills.ID,
  338. billsName: bills.name,
  339. billsCode: bills.code,
  340. billsUnit: bills.unit,
  341. billsTtlAmt: bills.quantity,
  342. billsPrices: [],
  343. billsUnitPrices: [],
  344. rationCommons: [],
  345. billsAmounts: [],
  346. '技术经济指标': [],
  347. billsLevel: level,
  348. calcBase: bills.calcBase,
  349. billsMemos: bills.remark
  350. };
  351. let total = 0;
  352. let rationTotal = 0;
  353. let baseTotal = 0;
  354. for (let n of nameList) {
  355. let p = 0; //金额
  356. let up = 0; //单价
  357. let ra = 0; //定额建安费
  358. let bt = 0; //累计相关
  359. if (bills.unitPrices[n]) up = scMathUtil.roundForObj(bills.unitPrices[n], decimal.bills.unitPrice);
  360. tem.billsUnitPrices.push(up);
  361. if (bills.prices[n]) {
  362. p = scMathUtil.roundForObj(bills.prices[n], decimal.bills.totalPrice);
  363. total = scMathUtil.roundForObj(p + total, decimal.process);
  364. }
  365. tem.billsPrices.push(p);
  366. if (bills.rationCommons[n]) {
  367. ra = scMathUtil.roundForObj(bills.rationCommons[n], decimal.bills.totalPrice);
  368. rationTotal = scMathUtil.roundForObj(ra + rationTotal, decimal.process);
  369. }
  370. tem.rationCommons.push(ra);
  371. if (bills.quantityMap[n] && parseFloat(bills.quantityMap[n]) !== 0) {
  372. tem.billsAmounts.push(bills.quantityMap[n]);
  373. tem['技术经济指标'].push(scMathUtil.roundForObj(p / bills.quantityMap[n], 2));
  374. } else {
  375. tem.billsAmounts.push(0);
  376. tem['技术经济指标'].push(scMathUtil.roundForObj(p, 2));
  377. }
  378. if (rootFlag == fixedFlag.MAINTENANCE_EXPENSES) { //如果是第三部分下的子清单,才要计算累计的相关信息
  379. if (bills.baseProgressiveFees[n]) {
  380. bt = scMathUtil.roundForObj(bills.baseProgressiveFees[n], decimal.bills.totalPrice);
  381. baseTotal = scMathUtil.roundForObj(bt + baseTotal, decimal.process);
  382. }
  383. }
  384. }
  385. tem.billsTtlPrice = scMathUtil.roundForObj(total, decimal.bills.totalPrice);
  386. if (progressiveInterval && isProgressiveType && rootFlag == fixedFlag.MAINTENANCE_EXPENSES) {
  387. let baseArr = calcUtil.getProgressive(bills.calcBase, overWrite ? overWrite.progression : undefined);
  388. if (baseArr.length > 0) {
  389. let calcTotal = calcUtil.getProgressiveFee(baseTotal, baseArr[0], progressiveInterval, decimal.bills.totalPrice, overWrite ? overWrite.deficiency : undefined);
  390. tem.billsTtlPrice = calcTotal;
  391. let rate = scMathUtil.roundForObj(calcTotal * 100 / baseTotal, decimal.feeRate);
  392. tem.billsMemos = "费率:" + rate + "%";
  393. //“费率:n%”,n为汇总后重算的金额/汇总后的基数
  394. }
  395. }
  396. tem.rationTotal = scMathUtil.roundForObj(rationTotal, decimal.bills.totalPrice); //定额总建安费
  397. tem['技术经济综合指标'] = (tem.billsTtlAmt && parseFloat(tem.billsTtlAmt) !== 0) ? scMathUtil.roundForObj(tem.billsTtlPrice / tem.billsTtlAmt, 2) : scMathUtil.roundForObj(tem.billsTtlPrice, 2);
  398. if (bills.flag == fixedFlag.TOTAL_COST) totalItem = tem;
  399. if (bills.flag == fixedFlag.ONE_TO_FOUR_TOTAL) one_to_four_Item = tem;
  400. return tem
  401. }
  402. }
  403. async function mergeProject(main, sub) { //合并两个项目
  404. let decimal = await decimal_facade.getProjectDecimal(main[0].projectID);
  405. let project = await projectsModel.findOne({
  406. ID: main[0].projectID
  407. });
  408. let notMatchList = [];
  409. for (let s of sub) {
  410. //先找有没有相同的大项费用
  411. let same = findTheSameItem(main, s);
  412. same ? await mergeItem(same, s, decimal, project._doc) : notMatchList.push(s); //如果找到,则合并,找不到就放在未匹配表
  413. }
  414. for (let n of notMatchList) {
  415. main.push(n);
  416. }
  417. return decimal;
  418. }
  419. async function mergeItem(a, b, decimal, project) {
  420. let bqDecimal = await decimal_facade.getBillsQuantityDecimal(a.projectID, a.unit, project);
  421. a.quantity = a.quantity ? scMathUtil.roundForObj(a.quantity, bqDecimal) : 0;
  422. b.quantity = b.quantity ? scMathUtil.roundForObj(b.quantity, bqDecimal) : 0;
  423. a.quantity = scMathUtil.roundForObj(a.quantity + b.quantity, decimal.process);
  424. for (let name in b.prices) {
  425. a.prices[name] = b.prices[name];
  426. a.rationCommons[name] = b.rationCommons[name];
  427. a.quantityMap[name] = b.quantityMap[name];
  428. a.unitPrices[name] = b.unitPrices[name];
  429. a.baseProgressiveFees[name] = b.baseProgressiveFees[name];
  430. }
  431. for (let name in a.quantityMap) {
  432. a.quantityMap[name] = a.quantityMap[name] ? scMathUtil.roundForObj(a.quantityMap[name], bqDecimal) : 0;
  433. }
  434. await mergeChildren(a, b, decimal, project);
  435. }
  436. async function mergeChildren(a, b, decimal, project) {
  437. let notMatchList = [];
  438. if (a.children.length > 0 && b.children.length == 0) {
  439. return;
  440. } else if (a.children.length == 0 && b.children.length > 0) {
  441. a.children = b.children;
  442. return;
  443. }
  444. //=============剩下的是两者都有的情况
  445. for (let s of b.children) {
  446. let same = findTheSameItem(a.children, s);
  447. same ? await mergeItem(same, s, decimal, project) : notMatchList.push(s); //如果找到,则合并,找不到就放在未匹配表
  448. }
  449. for (let n of notMatchList) {
  450. let match = false; //符合插入标记
  451. //对于未匹配的子项,如果是固定清单:第100章至700章清单的子项,要匹配名字中的数字来做排充
  452. if (a.flag == fixedFlag.ONE_SEVEN_BILLS) {
  453. for (let i = 0; i < a.children.length; i++) {
  454. let m_name = a.children[i].name.replace(/[^0-9]/ig, "");
  455. let s_name = n.name.replace(/[^0-9]/ig, "");
  456. m_name = parseFloat(m_name);
  457. s_name = parseFloat(s_name);
  458. if (m_name && s_name) {
  459. if (m_name == s_name) {
  460. await mergeItem(a.children[i], n, project);
  461. match = true;
  462. break;
  463. }
  464. if (m_name > s_name) { //主节点名字中的数字大于被插节点,则被插节点放在主节点前面
  465. a.children.splice(i, 0, n);
  466. match = true;
  467. break;
  468. }
  469. }
  470. }
  471. } else { //其它的子项按编号进行排序
  472. for (let i = 0; i < a.children.length; i++) {
  473. let m_code = a.children[i].code;
  474. let s_code = n.code;
  475. if (m_code && s_code && m_code != "" && s_code != "") {
  476. if (m_code > s_code) {
  477. a.children.splice(i, 0, n);
  478. match = true;
  479. break;
  480. }
  481. }
  482. }
  483. }
  484. if (match == false) a.children.push(n) //没有插入成功,直接放到最后面
  485. }
  486. }
  487. function findTheSameItem(main, item) { //编号名称单位三个相同,认为是同一条清单
  488. return _.find(main, function (tem) {
  489. return isEqual(tem.code, item.code) && isEqual(tem.name, item.name) && isEqual(tem.unit, item.unit);
  490. })
  491. }
  492. function isEqual(a, b) { //粗略匹配,null undefind "" 认为相等
  493. return getValue(a) == getValue(b);
  494. function getValue(t) {
  495. if (t == null || t == undefined || t == "") return null;
  496. return t;
  497. }
  498. }
  499. async function getBillsByProjectID(projectID) {
  500. let roots = [],
  501. parentMap = {};
  502. let bills = await bill_model.model.find({
  503. projectID: projectID
  504. }, '-_id'); //取出所有清单
  505. let project = await projectsModel.findOne({
  506. ID: projectID
  507. });
  508. if (!project) throw new Error(`找不到项目:${projectID}`);
  509. let projectName = project.name;
  510. let author = ''; //编制人
  511. let auditor = ''; //审核人
  512. let compilationScope = ''; //编制范围
  513. let engineering = ''; //养护类别
  514. let progressiveType = 0; //累进计算类型
  515. let progressiveInterval = null;
  516. if (project.property && project.property.projectFeature) {
  517. for (let f of project.property.projectFeature) {
  518. if (f.key == 'author') author = f.value;
  519. if (f.key == 'auditor') auditor = f.value;
  520. if (f.key == 'compilationScope') compilationScope = f.value;
  521. if (f.key == 'engineering') engineering = f.value;
  522. }
  523. if (project.property.progressiveType) progressiveType = project.property.progressiveType;
  524. progressiveInterval = project.property.progressiveInterval;
  525. }
  526. for (let b of bills) {
  527. let commonFee = _.find(b._doc.fees, {
  528. "fieldName": "common"
  529. });
  530. let prices = {};
  531. let quantityMap = {};
  532. let unitPrices = {};
  533. let rationCommons = {};
  534. let baseProgressiveFees = {};
  535. let rationFee = _.find(b._doc.fees, {
  536. "fieldName": "rationCommon"
  537. });
  538. if (commonFee && commonFee.totalFee) prices[projectName] = commonFee.totalFee;
  539. if (commonFee && commonFee.unitFee) unitPrices[projectName] = commonFee.unitFee;
  540. if (rationFee && rationFee.totalFee) rationCommons[projectName] = rationFee.totalFee;
  541. baseProgressiveFees[projectName] = b.baseProgressiveFee;
  542. quantityMap[projectName] = b.quantity;
  543. let flagIndex = _.find(b._doc.flags, {
  544. 'fieldName': 'fixed'
  545. });
  546. let doc = {
  547. ID: b.ID,
  548. name: b.name,
  549. code: b.code,
  550. unit: b.unit,
  551. projectID: b.projectID,
  552. ParentID: b.ParentID,
  553. NextSiblingID: b.NextSiblingID,
  554. unitPrices: unitPrices,
  555. quantity: b.quantity,
  556. prices: prices,
  557. rationCommons: rationCommons,
  558. quantityMap: quantityMap,
  559. flag: flagIndex ? flagIndex.flag : -99,
  560. remark: b.remark,
  561. calcBase: b.calcBase,
  562. baseProgressiveFees: baseProgressiveFees
  563. }; //选取有用字段
  564. if (b.ParentID == -1) roots.push(doc);
  565. parentMap[b.ParentID] ? parentMap[b.ParentID].push(doc) : parentMap[b.ParentID] = [doc];
  566. } //设置子节点
  567. for (let r of roots) {
  568. setChildren(r, parentMap, 1);
  569. }
  570. roots = sortChildren(roots);
  571. return {
  572. name: projectName,
  573. roots: roots,
  574. author: author,
  575. auditor: auditor,
  576. compilationScope: compilationScope,
  577. ParentID: project.ParentID,
  578. prjTypeName: engineering,
  579. progressiveType: progressiveType,
  580. progressiveInterval: progressiveInterval
  581. }
  582. }
  583. function setChildren(bill, parentMap, level) {
  584. let children = parentMap[bill.ID];
  585. if (children) {
  586. for (let c of children) {
  587. setChildren(c, parentMap, level + 1)
  588. }
  589. bill.children = children;
  590. } else {
  591. bill.children = [];
  592. }
  593. }
  594. function sortChildren(lists) {
  595. let IDMap = {},
  596. nextMap = {},
  597. firstNode = null,
  598. newList = [];
  599. for (let l of lists) {
  600. if (l.children && l.children.length > 0) l.children = sortChildren(l.children); //递规排序
  601. IDMap[l.ID] = l;
  602. if (l.NextSiblingID != -1) nextMap[l.NextSiblingID] = l;
  603. }
  604. for (let t of lists) {
  605. if (!nextMap[t.ID]) { //如果在下一节点映射没找到,则是第一个节点
  606. firstNode = t;
  607. break;
  608. }
  609. }
  610. if (firstNode) {
  611. newList.push(firstNode);
  612. delete IDMap[firstNode.ID];
  613. setNext(firstNode, newList);
  614. }
  615. //容错处理,如果链断了的情况,直接添加到后面
  616. for (let key in IDMap) {
  617. if (IDMap[key]) newList.push(IDMap[key])
  618. }
  619. return newList;
  620. function setNext(node, array) {
  621. if (node.NextSiblingID != -1) {
  622. let next = IDMap[node.NextSiblingID];
  623. if (next) {
  624. array.push(next);
  625. delete IDMap[next.ID];
  626. setNext(next, array);
  627. }
  628. }
  629. }
  630. }
  631. async function getGLJSummayDatas(projectIDs) {
  632. let projects = [];
  633. let names = [];
  634. let prjTypeNames = [];
  635. let compilationScopes = [];
  636. try {
  637. for (let ID of projectIDs) {
  638. projects.push(await getProjectData(ID));
  639. }
  640. if (projects.length == 0) {
  641. return [];
  642. }
  643. let mp = projects[0];
  644. for (let p of projects) {
  645. names.push(p.name);
  646. prjTypeNames.push(p.prjTypeName);
  647. p.gljList = await getProjectGLJData(p.ID, p.unitPriceFileId, mp.property);
  648. compilationScopes.push(p.compilationScope);
  649. }
  650. let mList = mergeGLJ(mp, projects, names, prjTypeNames);
  651. mList = gljUtil.sortProjectGLJ(mList, _);
  652. let summaryGLJDatas = getSummaryGLJDatas(mList, mp.property.decimal, names, prjTypeNames, compilationScopes);
  653. let parentProject = await projectsModel.findOne({
  654. ID: mp.ParentID
  655. });
  656. let result = {
  657. prj: {},
  658. SummaryGljAudit: {
  659. "name": parentProject ? parentProject.name : "",
  660. "编制": mp.author,
  661. "复核": mp.auditor,
  662. "编制范围": mp.compilationScope
  663. },
  664. SummaryGljAuditDetail: summaryGLJDatas
  665. };
  666. return result;
  667. } catch (e) {
  668. console.log(e);
  669. }
  670. }
  671. function getSummaryGLJDatas(gljList, decimal, nameList, prjTypeNames, compilationScopes) {
  672. let datas = [],
  673. qdecimal = decimal.glj.quantity,
  674. process = decimal.process;
  675. for (let tem of gljList) {
  676. let d = {
  677. code: tem.code,
  678. name: tem.name,
  679. type: tem.type,
  680. unit: tem.unit,
  681. specs: tem.specs,
  682. marketPrice: tem.marketPrice,
  683. prjNames: nameList,
  684. prjTypeNames: prjTypeNames,
  685. quantityList: [],
  686. '编制范围明细': compilationScopes
  687. };
  688. let totalQuantity = 0;
  689. for (let n of nameList) {
  690. let q = tem.quantityMap[n] ? scMathUtil.roundForObj(tem.quantityMap[n], qdecimal) : 0;
  691. totalQuantity = scMathUtil.roundForObj(q + totalQuantity, process);
  692. d.quantityList.push(q);
  693. }
  694. d.totalQuantity = scMathUtil.roundForObj(totalQuantity, qdecimal);
  695. datas.push(d);
  696. }
  697. return datas;
  698. }
  699. function mergeGLJ(mp, projects) {
  700. let gljMap = {},
  701. gljList = [];
  702. for (let g of mp.gljList) {
  703. g.quantityMap = {};
  704. g.quantityMap[mp.name] = g.quantity;
  705. gljMap[gljUtil.getIndex(g)] = g;
  706. gljList.push(g);
  707. }
  708. for (let i = 1; i < projects.length; i++) {
  709. let temList = projects[i].gljList;
  710. for (let t of temList) {
  711. t.quantityMap = {};
  712. t.quantityMap[projects[i].name] = t.quantity;
  713. //这里除了5个属性相同判断为同一个之外,还要判断市场价相同,才认为是同一个工料机
  714. let connect_key = gljUtil.getIndex(t);
  715. let g = gljMap[connect_key];
  716. if (g && g.marketPrice == t.marketPrice) {
  717. g.quantityMap[projects[i].name] = t.quantity;
  718. } else {
  719. gljMap[connect_key] = t;
  720. gljList.push(t);
  721. }
  722. }
  723. }
  724. return gljList;
  725. }
  726. async function getProjectGLJData(projectID, unitPriceFileId, property) {
  727. //取项目工料机数据
  728. let projectGLJDatas = await getProjectGLJPrice(projectID, unitPriceFileId, property);
  729. await calcProjectGLJQuantity(projectID, projectGLJDatas, property);
  730. _.remove(projectGLJDatas.gljList, {
  731. 'quantity': 0
  732. });
  733. return projectGLJDatas.gljList;
  734. }
  735. async function getProjectData(projectID) {
  736. let project = await projectsModel.findOne({
  737. ID: projectID
  738. });
  739. if (!project) throw new Error(`找不到项目:${projectID}`);
  740. let projectName = project.name;
  741. let author = ''; //编制人
  742. let auditor = ''; //审核人
  743. let compilationScope = ''; //编制范围
  744. let engineering = ''; //养护类别
  745. if (project.property && project.property.projectFeature) {
  746. for (let f of project.property.projectFeature) {
  747. if (f.key == 'author') author = f.value;
  748. if (f.key == 'auditor') auditor = f.value;
  749. if (f.key == 'compilationScope') compilationScope = f.value;
  750. if (f.key == 'engineering') engineering = f.value;
  751. }
  752. }
  753. if (!(project.property && project.property.unitPriceFile)) throw new Error(`找不到单价文件:${projectID}`);
  754. let unitPriceFileId = project.property.unitPriceFile.id;
  755. return {
  756. ID: projectID,
  757. name: projectName,
  758. author: author,
  759. auditor: auditor,
  760. compilationScope: compilationScope,
  761. ParentID: project.ParentID,
  762. prjTypeName: engineering,
  763. property: project.property,
  764. unitPriceFileId: unitPriceFileId
  765. }
  766. }
  767. async function getProjectGLJPrice(projectID, unitPriceFileId, property) {
  768. //取项目工料机数据
  769. let calcOptions = property.calcOptions;
  770. let decimalObj = property.decimal;
  771. let labourCoeDatas = []; //取调整价才需要用到
  772. let gljListModel = new GLJListModel();
  773. let [gljList, mixRatioConnectData, mixRatioMap, unitPriceMap] = await gljListModel.getListByProjectId(projectID, unitPriceFileId);
  774. gljList = JSON.parse(JSON.stringify(gljList));
  775. for (let glj of gljList) {
  776. let result = gljUtil.getGLJPrice(glj, {
  777. gljList: gljList
  778. }, calcOptions, labourCoeDatas, decimalObj, false, _, scMathUtil);
  779. glj.marketPrice = result.marketPrice;
  780. glj.basePrice = result.basePrice;
  781. }
  782. return {
  783. gljList: gljList,
  784. mixRatioMap: mixRatioMap
  785. };
  786. }
  787. async function calcProjectGLJQuantity(projectID, projectGLJDatas, property) {
  788. let q_decimal = property.decimal.glj.quantity;
  789. let rationGLJDatas = await ration_glj_model.find({
  790. 'projectID': projectID
  791. });
  792. let rationDatas = await ration_model.model.find({
  793. 'projectID': projectID
  794. });
  795. gljUtil.calcProjectGLJQuantity(projectGLJDatas, rationGLJDatas, rationDatas, [], q_decimal)
  796. }