project_facade.js 28 KB

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