project_facade.js 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094
  1. /**
  2. * Created by zhang on 2018/1/26.
  3. */
  4. module.exports = {
  5. setChildren,
  6. sortChildren,
  7. markUpdateProject: markUpdateProject,
  8. removeProjectMark: removeProjectMark,
  9. updateNodes: updateNodes,
  10. saveProperty: saveProperty,
  11. getDefaultColSetting: getDefaultColSetting,
  12. markProjectsToChange: markProjectsToChange,
  13. getBudgetSummayDatas: getBudgetSummayDatas,
  14. getGLJSummayDatas: getGLJSummayDatas,
  15. };
  16. let mongoose = require("mongoose");
  17. let logger = require("../../../logs/log_helper").logger;
  18. let projectsModel = mongoose.model("projects");
  19. let async_n = require("async");
  20. let _ = require("lodash");
  21. let ration_model = require("../models/ration");
  22. let optionModel = mongoose.model("options");
  23. let bill_model = require("../models/bills");
  24. let consts = require("../models/project_consts");
  25. let projectConsts = consts.projectConst;
  26. let ration_glj_model = mongoose.model("ration_glj");
  27. let rationTemplateModel = mongoose.model("ration_template");
  28. let project_glj_model = mongoose.model("glj_list");
  29. let ration_glj_facade = require("../../ration_glj/facade/ration_glj_facade");
  30. const uuidV1 = require("uuid/v1");
  31. const gljUtil = require("../../../public/gljUtil");
  32. let stdColSettingModel = mongoose.model("std_main_col_lib");
  33. let decimal_facade = require("../../main/facade/decimal_facade");
  34. const scMathUtil = require("../../../public/scMathUtil").getUtil();
  35. const calcUtil = require("../../../public/calculate_util");
  36. const { fixedFlag } = require("../../../public/common_constants");
  37. const GLJListModel = require("../../glj/models/glj_list_model");
  38. const projectDao = require("../../pm/models/project_model").project;
  39. const UnitPriceFileModel = require("../../glj/models/unit_price_file_model");
  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. //添加定額工料机的時候,要先走项目工料机的逻辑
  128. let [newRecode, projectGLJ] = await createRationGLJData(node.data);
  129. node.data = newRecode;
  130. node.projectGLJ = projectGLJ;
  131. }
  132. }
  133. taskMap[type].tasks.push(getTask(node));
  134. }
  135. }
  136. }
  137. for (let key in taskMap) {
  138. if (taskMap[key].tasks.length > 0)
  139. asyncTasks.push(taskMap[key].model.bulkWrite(taskMap[key].tasks));
  140. }
  141. if (asyncTasks.length > 0) await Promise.all(asyncTasks);
  142. if (deleteRationIDs.length > 0)
  143. await ration_glj_model.deleteMany({
  144. rationID: {
  145. $in: deleteRationIDs,
  146. },
  147. });
  148. return datas;
  149. function getTask(node, idFiled = "ID") {
  150. let task = {};
  151. if (node.action == "add") {
  152. task.insertOne = {
  153. document: node.data,
  154. };
  155. } else if (node.action == "delete") {
  156. task.deleteOne = {
  157. filter: {},
  158. };
  159. task.deleteOne.filter[idFiled] = node.data[idFiled];
  160. } else {
  161. task.updateOne = {
  162. filter: {},
  163. update: {}, //_.cloneDeep(node.data)
  164. };
  165. for (let key in node.data) {
  166. if (key.indexOf("function(") !== -1) {
  167. //有时候会出现field里包含一串 function(e){if(e.length>0)... 这些东西,本地测试又不出现,所以这里先把这些field删除看看
  168. delete node.data[key];
  169. } else {
  170. task.updateOne.update[key] = node.data[key];
  171. }
  172. }
  173. task.updateOne.filter[idFiled] = node.data[idFiled]; //现在复制项目也重新生成一个新的ID了,所以ID是唯一的
  174. delete task.updateOne.update[idFiled]; //防止误操作
  175. }
  176. return task;
  177. }
  178. }
  179. //data = {feeRateID:111111,projectID:1245}; type = feeRate
  180. async function markUpdateProject(data, type) {
  181. let query = {
  182. deleteInfo: null,
  183. };
  184. if (type == "feeRate") {
  185. //更改了费率
  186. query["property.feeFile.id"] = data.feeRateID;
  187. }
  188. if (type == "unitFile") {
  189. //更改了单价文件
  190. query["property.unitPriceFile.id"] = data.unitFileID; //unitPriceFile
  191. }
  192. let projects = await projectsModel.find(query);
  193. return await markProjectsToChange(
  194. projects,
  195. type,
  196. data.projectID,
  197. data.isInclude
  198. );
  199. }
  200. async function markProjectsToChange(projects, type, extProjectID, isInclude) {
  201. let tasks = [];
  202. for (let p of projects) {
  203. if (isInclude != true) {
  204. if (extProjectID && p.ID === extProjectID) continue; //排除当前项目
  205. }
  206. tasks.push(generateMarkTask(type, p.ID));
  207. }
  208. return tasks.length > 0 ? await projectsModel.bulkWrite(tasks) : null;
  209. }
  210. async function removeProjectMark(projectID) {
  211. return await projectsModel.findOneAndUpdate(
  212. {
  213. ID: projectID,
  214. },
  215. {
  216. $unset: {
  217. changeMark: 1,
  218. },
  219. }
  220. );
  221. }
  222. function generateMarkTask(value, projectID) {
  223. let task = {
  224. updateOne: {
  225. filter: {
  226. ID: projectID,
  227. },
  228. update: {
  229. changeMark: value,
  230. },
  231. },
  232. };
  233. return task;
  234. }
  235. // {projectID: 5, propertyName: 'aaa', propertyValue: 1}
  236. function saveProperty(data, callback) {
  237. let obj = {};
  238. let pn = "property." + data.propertyName;
  239. obj[pn] = data.propertyValue;
  240. projectsModel.update(
  241. {
  242. ID: data.projectID,
  243. },
  244. obj,
  245. function (err) {
  246. if (err) {
  247. logger.err(pn + " save error: " + err);
  248. callback(err, null);
  249. } else {
  250. logger.info(pn + " saved.");
  251. callback("", null);
  252. }
  253. }
  254. );
  255. }
  256. async function getDefaultColSetting(libID) {
  257. return await stdColSettingModel.findOne(
  258. {
  259. ID: libID,
  260. deleted: false,
  261. },
  262. "-_id main_tree_col"
  263. );
  264. }
  265. async function getBudgetSummayDatas(
  266. projectIDs,
  267. userID,
  268. compilationID,
  269. overWriteUrl
  270. ) {
  271. try {
  272. let projects = [];
  273. let names = [];
  274. let prjTypeNames = [];
  275. let compilationScopes = [];
  276. let decimal = null;
  277. let isProgressiveType = true;
  278. for (let ID of projectIDs) {
  279. projects.push(await getBillsByProjectID(ID));
  280. }
  281. if (projects.length == 0) {
  282. return [];
  283. }
  284. let mp = projects[0];
  285. names.push(mp.name);
  286. prjTypeNames.push(mp.prjTypeName);
  287. compilationScopes.push(mp.compilationScope);
  288. if (projects.length == 1)
  289. decimal = await decimal_facade.getProjectDecimal(projectIDs[0]); //如果只有一个项目,则没走合并的那一步,decimal会为空,从面报错
  290. for (let i = 1; i < projects.length; i++) {
  291. names.push(projects[i].name);
  292. prjTypeNames.push(projects[i].prjTypeName);
  293. compilationScopes.push(projects[i].compilationScope);
  294. decimal = await mergeProject(mp.roots, projects[i].roots);
  295. }
  296. let options_setting = await optionModel
  297. .findOne({
  298. user_id: userID,
  299. compilation_id: compilationID,
  300. })
  301. .lean();
  302. if (
  303. options_setting &&
  304. options_setting.options &&
  305. options_setting.options.GENERALOPTS
  306. )
  307. isProgressiveType =
  308. options_setting.options.GENERALOPTS.progressiveType == 1 ? false : true;
  309. let SummaryAuditDetail = getReportData(
  310. names,
  311. mp.roots,
  312. prjTypeNames,
  313. compilationScopes,
  314. decimal,
  315. isProgressiveType,
  316. mp.progressiveInterval,
  317. overWriteUrl
  318. );
  319. let parentProject = await projectsModel.findOne({
  320. ID: mp.ParentID,
  321. });
  322. let result = {
  323. prj: {},
  324. SummaryAudit: {
  325. name: parentProject ? parentProject.name : "",
  326. 编制: mp.author,
  327. 复核: mp.auditor,
  328. 编制范围: mp.compilationScope,
  329. },
  330. SummaryAuditDetail: SummaryAuditDetail,
  331. };
  332. return result;
  333. } catch (e) {
  334. // console.log(e.message)
  335. console.log(e);
  336. }
  337. }
  338. function getReportData(
  339. nameList,
  340. items,
  341. prjTypeNames,
  342. compilationScopes,
  343. decimal,
  344. isProgressiveType,
  345. progressiveInterval,
  346. overWriteUrl
  347. ) {
  348. let datas = [],
  349. totalItem = null,
  350. one_to_four_Item = null;
  351. let overWrite = null;
  352. if (overWriteUrl && overWriteUrl != "") {
  353. overWrite = require("../../.." + overWriteUrl);
  354. }
  355. setChildrenDatas(items, datas);
  356. if (one_to_four_Item)
  357. recalcTotalItem(
  358. one_to_four_Item,
  359. datas,
  360. isProgressiveType,
  361. progressiveInterval
  362. );
  363. if (totalItem)
  364. recalcTotalItem(totalItem, datas, isProgressiveType, progressiveInterval);
  365. for (let d of datas) {
  366. if (d.billsTtlPrice && totalItem.billsTtlPrice) {
  367. d["各项费用比例"] = scMathUtil.roundForObj(
  368. (d.billsTtlPrice / totalItem.billsTtlPrice) * 100,
  369. 2
  370. );
  371. }
  372. d["prjNames"] = nameList;
  373. d["prjTypeNames"] = prjTypeNames;
  374. d["编制范围明细"] = compilationScopes;
  375. }
  376. return datas;
  377. function recalcTotalItem(
  378. item,
  379. datas,
  380. isProgressiveType,
  381. progressiveInterval
  382. ) {
  383. let totalExp = item.calcBase;
  384. if (totalExp.indexOf("@") == -1) return;
  385. if (isProgressiveType && progressiveInterval) {
  386. //有累进的要重新计算总金额和技术经济综合指标
  387. let hasReplace = false;
  388. for (let t of datas) {
  389. if (totalExp.includes(t.ID)) hasReplace = true; // 强壮性处理:控制提前计算问题(ID在datas中找不到)
  390. totalExp = totalExp.replace(t.ID, t.billsTtlPrice + "");
  391. }
  392. if (hasReplace) {
  393. totalExp = totalExp.replace(/@/g, "");
  394. //还有其他符号(如%)
  395. totalExp = totalExp.replace(/%/g, " / 100 ");
  396. let nTotal = eval(totalExp);
  397. item.billsTtlPrice = scMathUtil.roundForObj(
  398. nTotal,
  399. decimal.bills.totalPrice
  400. );
  401. item["技术经济综合指标"] =
  402. item.billsTtlAmt && parseFloat(item.billsTtlAmt) !== 0
  403. ? scMathUtil.roundForObj(item.billsTtlPrice / item.billsTtlAmt, 2)
  404. : scMathUtil.roundForObj(item.billsTtlPrice, 2);
  405. }
  406. }
  407. }
  408. function setChildrenDatas(children, arr, level = 0, rootFlag) {
  409. let temTotalPrice = 0;
  410. for (let c of children) {
  411. if (level == 0) rootFlag = c.flag; //取最顶层节点的固定清单类别
  412. let tbill = getBillDatas(c, level, rootFlag);
  413. arr.push(tbill);
  414. let sumChildren = setChildrenDatas(c.children, arr, level + 1, rootFlag);
  415. if (isProgressiveType && progressiveInterval) {
  416. //如果要累进的,父节点要重新汇总
  417. if (c.children.length > 0) {
  418. tbill.billsTtlPrice = sumChildren;
  419. tbill["技术经济综合指标"] =
  420. tbill.billsTtlAmt && parseFloat(tbill.billsTtlAmt) !== 0
  421. ? scMathUtil.roundForObj(
  422. tbill.billsTtlPrice / tbill.billsTtlAmt,
  423. 2
  424. )
  425. : scMathUtil.roundForObj(tbill.billsTtlPrice, 2);
  426. } else if (
  427. tbill.calcBase &&
  428. tbill.calcBase.indexOf("@") >= 0 &&
  429. tbill.calcBase.indexOf("{") < 0
  430. ) {
  431. // 说明:在实际中,发现清单‘第一、二、三部分费用合计’没有再计算,这样会造成问题(实际情况比较复杂,需要多方测试)
  432. recalcTotalItem(tbill, arr, isProgressiveType, progressiveInterval);
  433. }
  434. if (level > 0)
  435. temTotalPrice = scMathUtil.roundForObj(
  436. tbill.billsTtlPrice + temTotalPrice,
  437. decimal.bills.totalPrice
  438. );
  439. }
  440. }
  441. return temTotalPrice;
  442. }
  443. function getBillDatas(bills, level, rootFlag) {
  444. let tem = {
  445. ID: bills.ID,
  446. billsName: bills.name,
  447. billsCode: bills.code,
  448. billsUnit: bills.unit,
  449. billsTtlAmt: bills.quantity,
  450. billsPrices: [],
  451. billsUnitPrices: [],
  452. rationCommons: [],
  453. billsAmounts: [],
  454. 技术经济指标: [],
  455. billsLevel: level,
  456. calcBase: bills.calcBase,
  457. billsMemos: bills.remark,
  458. };
  459. let total = 0;
  460. let rationTotal = 0;
  461. let baseTotal = 0;
  462. for (let n of nameList) {
  463. let p = 0; //金额
  464. let up = 0; //单价
  465. let ra = 0; //定额建安费
  466. let bt = 0; //累计相关
  467. if (bills.unitPrices[n])
  468. up = scMathUtil.roundForObj(
  469. bills.unitPrices[n],
  470. decimal.bills.unitPrice
  471. );
  472. tem.billsUnitPrices.push(up);
  473. if (bills.prices[n]) {
  474. p = scMathUtil.roundForObj(bills.prices[n], decimal.bills.totalPrice);
  475. total = scMathUtil.roundForObj(p + total, decimal.process);
  476. }
  477. tem.billsPrices.push(p);
  478. if (bills.rationCommons[n]) {
  479. ra = scMathUtil.roundForObj(
  480. bills.rationCommons[n],
  481. decimal.bills.totalPrice
  482. );
  483. rationTotal = scMathUtil.roundForObj(ra + rationTotal, decimal.process);
  484. }
  485. tem.rationCommons.push(ra);
  486. if (bills.quantityMap[n] && parseFloat(bills.quantityMap[n]) !== 0) {
  487. tem.billsAmounts.push(bills.quantityMap[n]);
  488. tem["技术经济指标"].push(
  489. scMathUtil.roundForObj(p / bills.quantityMap[n], 2)
  490. );
  491. } else {
  492. tem.billsAmounts.push(0);
  493. tem["技术经济指标"].push(scMathUtil.roundForObj(p, 2));
  494. }
  495. //如果是第三部分下的子清单,才要计算累计的相关信息
  496. // 10-26 需求变更,所有清单都算累计
  497. /* if (rootFlag == fixedFlag.MAINTENANCE_EXPENSES) {
  498. if (bills.baseProgressiveFees[n]) {
  499. bt = scMathUtil.roundForObj(bills.baseProgressiveFees[n], decimal.bills.totalPrice);
  500. baseTotal = scMathUtil.roundForObj(bt + baseTotal, decimal.process);
  501. }
  502. } */
  503. if (bills.baseProgressiveFees[n]) {
  504. bt = scMathUtil.roundForObj(
  505. bills.baseProgressiveFees[n],
  506. decimal.bills.totalPrice
  507. );
  508. baseTotal = scMathUtil.roundForObj(bt + baseTotal, decimal.process);
  509. }
  510. }
  511. tem.billsTtlPrice = scMathUtil.roundForObj(total, decimal.bills.totalPrice);
  512. // 10-26 需求变更,所有清单都算累计 && rootFlag == fixedFlag.MAINTENANCE_EXPENSES
  513. if (progressiveInterval && isProgressiveType) {
  514. let baseArr = calcUtil.getProgressive(
  515. bills.calcBase,
  516. overWrite ? overWrite.progression : undefined
  517. );
  518. if (baseArr.length > 0) {
  519. let deficiency = (overWrite && overWrite.deficiency) || null;
  520. let beyond = (overWrite && overWrite.beyond) || null;
  521. let calcTotal = calcUtil.getProgressiveFee(
  522. baseTotal,
  523. baseArr[0],
  524. progressiveInterval,
  525. decimal.bills.totalPrice,
  526. deficiency,
  527. beyond
  528. );
  529. tem.billsTtlPrice = calcTotal;
  530. let rate = scMathUtil.roundForObj(
  531. (calcTotal * 100) / baseTotal,
  532. decimal.feeRate
  533. );
  534. tem.billsMemos = "费率:" + rate + "%";
  535. //“费率:n%”,n为汇总后重算的金额/汇总后的基数
  536. }
  537. }
  538. tem.rationTotal = scMathUtil.roundForObj(
  539. rationTotal,
  540. decimal.bills.totalPrice
  541. ); //定额总建安费
  542. tem["技术经济综合指标"] =
  543. tem.billsTtlAmt && parseFloat(tem.billsTtlAmt) !== 0
  544. ? scMathUtil.roundForObj(tem.billsTtlPrice / tem.billsTtlAmt, 2)
  545. : scMathUtil.roundForObj(tem.billsTtlPrice, 2);
  546. if (bills.flag == fixedFlag.TOTAL_COST) totalItem = tem;
  547. if (bills.flag == fixedFlag.ONE_TO_FOUR_TOTAL) one_to_four_Item = tem;
  548. return tem;
  549. }
  550. }
  551. async function mergeProject(main, sub) {
  552. //合并两个项目
  553. let decimal = await decimal_facade.getProjectDecimal(main[0].projectID);
  554. let project = await projectsModel.findOne({
  555. ID: main[0].projectID,
  556. });
  557. let notMatchList = [];
  558. for (let s of sub) {
  559. //先找有没有相同的大项费用
  560. let same = findTheSameItem(main, s);
  561. same
  562. ? await mergeItem(same, s, decimal, project._doc)
  563. : notMatchList.push(s); //如果找到,则合并,找不到就放在未匹配表
  564. }
  565. for (let n of notMatchList) {
  566. main.push(n);
  567. }
  568. return decimal;
  569. }
  570. async function mergeItem(a, b, decimal, project) {
  571. let bqDecimal = await decimal_facade.getBillsQuantityDecimal(
  572. a.projectID,
  573. a.unit,
  574. project
  575. );
  576. a.quantity = a.quantity ? scMathUtil.roundForObj(a.quantity, bqDecimal) : 0;
  577. b.quantity = b.quantity ? scMathUtil.roundForObj(b.quantity, bqDecimal) : 0;
  578. a.quantity = scMathUtil.roundForObj(a.quantity + b.quantity, decimal.process);
  579. for (let name in b.prices) {
  580. a.prices[name] = b.prices[name];
  581. a.rationCommons[name] = b.rationCommons[name];
  582. a.quantityMap[name] = b.quantityMap[name];
  583. a.unitPrices[name] = b.unitPrices[name];
  584. a.baseProgressiveFees[name] = b.baseProgressiveFees[name];
  585. }
  586. for (let name in a.quantityMap) {
  587. a.quantityMap[name] = a.quantityMap[name]
  588. ? scMathUtil.roundForObj(a.quantityMap[name], bqDecimal)
  589. : 0;
  590. }
  591. await mergeChildren(a, b, decimal, project);
  592. }
  593. async function mergeChildren(a, b, decimal, project) {
  594. let notMatchList = [];
  595. if (a.children.length > 0 && b.children.length == 0) {
  596. return;
  597. } else if (a.children.length == 0 && b.children.length > 0) {
  598. a.children = b.children;
  599. return;
  600. }
  601. //=============剩下的是两者都有的情况
  602. for (let s of b.children) {
  603. let same = findTheSameItem(a.children, s);
  604. same ? await mergeItem(same, s, decimal, project) : notMatchList.push(s); //如果找到,则合并,找不到就放在未匹配表
  605. }
  606. for (let n of notMatchList) {
  607. let match = false; //符合插入标记
  608. //对于未匹配的子项,如果是固定清单:第100章至700章清单的子项,要匹配名字中的数字来做排充
  609. if (a.flag == fixedFlag.ONE_SEVEN_BILLS) {
  610. for (let i = 0; i < a.children.length; i++) {
  611. let m_name = a.children[i].name.replace(/[^0-9]/gi, "");
  612. let s_name = n.name.replace(/[^0-9]/gi, "");
  613. m_name = parseFloat(m_name);
  614. s_name = parseFloat(s_name);
  615. if (m_name && s_name) {
  616. if (m_name == s_name) {
  617. await mergeItem(a.children[i], n, project);
  618. match = true;
  619. break;
  620. }
  621. if (m_name > s_name) {
  622. //主节点名字中的数字大于被插节点,则被插节点放在主节点前面
  623. a.children.splice(i, 0, n);
  624. match = true;
  625. break;
  626. }
  627. }
  628. }
  629. } else {
  630. //其它的子项按编号进行排序
  631. for (let i = 0; i < a.children.length; i++) {
  632. let m_code = a.children[i].code;
  633. let s_code = n.code;
  634. if (m_code && s_code && m_code != "" && s_code != "") {
  635. if (m_code > s_code) {
  636. a.children.splice(i, 0, n);
  637. match = true;
  638. break;
  639. }
  640. }
  641. }
  642. }
  643. if (match == false) a.children.push(n); //没有插入成功,直接放到最后面
  644. }
  645. }
  646. function findTheSameItem(main, item) {
  647. //编号名称单位三个相同,认为是同一条清单
  648. return _.find(main, function (tem) {
  649. return (
  650. isEqual(tem.code, item.code) &&
  651. isEqual(tem.name, item.name) &&
  652. isEqual(tem.unit, item.unit)
  653. );
  654. });
  655. }
  656. function isEqual(a, b) {
  657. //粗略匹配,null undefind "" 认为相等
  658. return getValue(a) == getValue(b);
  659. function getValue(t) {
  660. if (t == null || t == undefined || t == "") return null;
  661. return t;
  662. }
  663. }
  664. async function getBillsByProjectID(projectID) {
  665. let roots = [],
  666. parentMap = {};
  667. let bills = await bill_model.model.find(
  668. {
  669. projectID: projectID,
  670. },
  671. "-_id"
  672. ); //取出所有清单
  673. let project = await projectsModel.findOne({
  674. ID: projectID,
  675. });
  676. if (!project) throw new Error(`找不到项目:${projectID}`);
  677. let projectName = project.name;
  678. let author = ""; //编制人
  679. let auditor = ""; //审核人
  680. let compilationScope = ""; //编制范围
  681. let engineering = ""; //养护类别
  682. let progressiveType = 0; //累进计算类型
  683. let progressiveInterval = null;
  684. if (project.property && project.property.projectFeature) {
  685. for (let f of project.property.projectFeature) {
  686. if (f.key == "author") author = f.value;
  687. if (f.key == "auditor") auditor = f.value;
  688. if (f.key == "compilationScope") compilationScope = f.value;
  689. if (f.key == "engineering") engineering = f.value;
  690. }
  691. if (project.property.progressiveType)
  692. progressiveType = project.property.progressiveType;
  693. progressiveInterval = project.property.progressiveInterval;
  694. }
  695. for (let b of bills) {
  696. let commonFee = _.find(b._doc.fees, {
  697. fieldName: "common",
  698. });
  699. let prices = {};
  700. let quantityMap = {};
  701. let unitPrices = {};
  702. let rationCommons = {};
  703. let baseProgressiveFees = {};
  704. let rationFee = _.find(b._doc.fees, {
  705. fieldName: "rationCommon",
  706. });
  707. if (commonFee && commonFee.tenderTotalFee)
  708. prices[projectName] = commonFee.tenderTotalFee;
  709. if (commonFee && commonFee.tenderUnitFee)
  710. unitPrices[projectName] = commonFee.tenderUnitFee;
  711. if (rationFee && rationFee.tenderTotalFee)
  712. rationCommons[projectName] = rationFee.tenderTotalFee;
  713. baseProgressiveFees[projectName] = b.baseProgressiveFee;
  714. quantityMap[projectName] = b.quantity;
  715. let flagIndex = _.find(b._doc.flags, {
  716. fieldName: "fixed",
  717. });
  718. let doc = {
  719. ID: b.ID,
  720. name: b.name,
  721. code: b.code,
  722. unit: b.unit,
  723. projectID: b.projectID,
  724. ParentID: b.ParentID,
  725. NextSiblingID: b.NextSiblingID,
  726. unitPrices: unitPrices,
  727. quantity: b.quantity,
  728. prices: prices,
  729. rationCommons: rationCommons,
  730. quantityMap: quantityMap,
  731. flag: flagIndex ? flagIndex.flag : -99,
  732. remark: b.remark,
  733. calcBase: b.calcBase,
  734. baseProgressiveFees: baseProgressiveFees,
  735. }; //选取有用字段
  736. if (b.ParentID == -1) roots.push(doc);
  737. parentMap[b.ParentID]
  738. ? parentMap[b.ParentID].push(doc)
  739. : (parentMap[b.ParentID] = [doc]);
  740. } //设置子节点
  741. for (let r of roots) {
  742. setChildren(r, parentMap);
  743. }
  744. roots = sortChildren(roots);
  745. return {
  746. name: projectName,
  747. roots: roots,
  748. author: author,
  749. auditor: auditor,
  750. compilationScope: compilationScope,
  751. ParentID: project.ParentID,
  752. prjTypeName: engineering,
  753. progressiveType: progressiveType,
  754. progressiveInterval: progressiveInterval,
  755. };
  756. }
  757. function setChildren(bill, parentMap) {
  758. let children = parentMap[bill.ID];
  759. if (children) {
  760. for (let c of children) {
  761. setChildren(c, parentMap);
  762. }
  763. bill.children = children;
  764. } else {
  765. bill.children = [];
  766. }
  767. }
  768. function sortChildren(lists) {
  769. let IDMap = {},
  770. nextMap = {},
  771. firstNode = null,
  772. newList = [];
  773. for (let l of lists) {
  774. if (l.children && l.children.length > 0)
  775. l.children = sortChildren(l.children); //递规排序
  776. IDMap[l.ID] = l;
  777. if (l.NextSiblingID != -1) nextMap[l.NextSiblingID] = l;
  778. }
  779. for (let t of lists) {
  780. if (!nextMap[t.ID]) {
  781. //如果在下一节点映射没找到,则是第一个节点
  782. firstNode = t;
  783. break;
  784. }
  785. }
  786. if (firstNode) {
  787. newList.push(firstNode);
  788. delete IDMap[firstNode.ID];
  789. setNext(firstNode, newList);
  790. }
  791. //容错处理,如果链断了的情况,直接添加到后面
  792. for (let key in IDMap) {
  793. if (IDMap[key]) newList.push(IDMap[key]);
  794. }
  795. return newList;
  796. function setNext(node, array) {
  797. if (node.NextSiblingID != -1) {
  798. let next = IDMap[node.NextSiblingID];
  799. if (next) {
  800. array.push(next);
  801. delete IDMap[next.ID];
  802. setNext(next, array);
  803. }
  804. }
  805. }
  806. }
  807. async function getGLJSummayDatas(projectIDs, compilationName = "") {
  808. let projects = [];
  809. let names = [];
  810. let prjTypeNames = [];
  811. let compilationScopes = [];
  812. try {
  813. for (let ID of projectIDs) {
  814. projects.push(await getProjectData(ID));
  815. }
  816. if (projects.length == 0) {
  817. return [];
  818. }
  819. let mp = projects[0];
  820. for (let p of projects) {
  821. names.push(p.name);
  822. prjTypeNames.push(p.prjTypeName);
  823. p.gljList = await getProjectGLJData(p.ID, p.unitPriceFileId, mp.property);
  824. compilationScopes.push(p.compilationScope);
  825. }
  826. let mList = mergeGLJ(mp, projects, names, prjTypeNames, compilationName);
  827. mList = gljUtil.sortProjectGLJ(mList, _);
  828. let summaryGLJDatas = getSummaryGLJDatas(
  829. mList,
  830. mp.property.decimal,
  831. names,
  832. prjTypeNames,
  833. compilationScopes
  834. );
  835. let parentProject = await projectsModel.findOne({
  836. ID: mp.ParentID,
  837. });
  838. let result = {
  839. prj: {},
  840. SummaryGljAudit: {
  841. name: parentProject ? parentProject.name : "",
  842. 编制: mp.author,
  843. 复核: mp.auditor,
  844. 编制范围: mp.compilationScope,
  845. },
  846. SummaryGljAuditDetail: summaryGLJDatas,
  847. };
  848. return result;
  849. } catch (e) {
  850. console.log(e.toString());
  851. }
  852. }
  853. function getSummaryGLJDatas(
  854. gljList,
  855. decimal,
  856. nameList,
  857. prjTypeNames,
  858. compilationScopes
  859. ) {
  860. let datas = [],
  861. qdecimal = decimal.glj.quantity,
  862. upDecimal = decimal.glj.unitPrice,
  863. process = decimal.process;
  864. for (let tem of gljList) {
  865. let d = {
  866. code: tem.code,
  867. name: tem.name,
  868. type: tem.type,
  869. unit: tem.unit,
  870. specs: tem.specs,
  871. marketPrice: tem.marketPrice,
  872. marketPriceList: [],
  873. prjNames: nameList,
  874. prjTypeNames: prjTypeNames,
  875. quantityList: [],
  876. 编制范围明细: compilationScopes,
  877. };
  878. let totalQuantity = 0;
  879. let totalPrice = 0;
  880. for (let n of nameList) {
  881. let q = tem.quantityMap[n]
  882. ? scMathUtil.roundForObj(tem.quantityMap[n], qdecimal)
  883. : 0;
  884. totalQuantity = scMathUtil.roundForObj(q + totalQuantity, process);
  885. d.quantityList.push(q);
  886. let up = tem.unitPriceMap[n]
  887. ? scMathUtil.roundForObj(tem.unitPriceMap[n], upDecimal)
  888. : 0;
  889. d.marketPriceList.push(up);
  890. totalPrice = scMathUtil.roundForObj(q * up + totalPrice, process);
  891. }
  892. d.totalQuantity = scMathUtil.roundForObj(totalQuantity, qdecimal);
  893. d.totalPrice = scMathUtil.roundForObj(totalPrice, upDecimal);
  894. datas.push(d);
  895. }
  896. return datas;
  897. }
  898. function mergeGLJ(mp, projects, names, prjTypeNames, compilationName = "") {
  899. let gljMap = {},
  900. gljList = [];
  901. const noPriceChkList = [
  902. "甘肃养护(2021)",
  903. "重庆养护(2018)",
  904. "浙江养护(2005)",
  905. "安徽养护(2018)",
  906. "山东养护(2016/2024)",
  907. "湖南养护(2014)",
  908. "广西日常养护年度预算(2020)",
  909. ];
  910. const noPriceCheck = noPriceChkList.indexOf(compilationName) >= 0;
  911. for (let g of mp.gljList) {
  912. g.quantityMap = {};
  913. g.quantityMap[mp.name] = g.tenderQuantity;
  914. g.unitPriceMap = {};
  915. g.unitPriceMap[mp.name] = g.marketPrice;
  916. gljMap[gljUtil.getIndex(g)] = g;
  917. gljList.push(g);
  918. }
  919. for (let i = 1; i < projects.length; i++) {
  920. let temList = projects[i].gljList;
  921. for (let t of temList) {
  922. t.quantityMap = {};
  923. t.quantityMap[projects[i].name] = t.tenderQuantity;
  924. t.unitPriceMap = {};
  925. t.unitPriceMap[projects[i].name] = t.marketPrice;
  926. //这里除了5个属性相同判断为同一个之外,还要判断市场价相同,才认为是同一个工料机
  927. //但有些省份不需要检测,体现在noPriceCheck标记
  928. let connect_key = gljUtil.getIndex(t);
  929. let g = gljMap[connect_key];
  930. if (g && (noPriceCheck || g.marketPrice == t.marketPrice)) {
  931. g.quantityMap[projects[i].name] = t.tenderQuantity;
  932. g.unitPriceMap[projects[i].name] = t.marketPrice;
  933. } else {
  934. gljMap[connect_key] = t;
  935. gljList.push(t);
  936. }
  937. }
  938. }
  939. return gljList;
  940. }
  941. async function getProjectGLJData(projectID, unitPriceFileId, property) {
  942. //取项目工料机数据
  943. let projectGLJDatas = await getProjectGLJPrice(
  944. projectID,
  945. unitPriceFileId,
  946. property
  947. );
  948. await calcProjectGLJQuantity(projectID, projectGLJDatas, property);
  949. _.remove(projectGLJDatas.gljList, {
  950. quantity: 0,
  951. });
  952. return projectGLJDatas.gljList;
  953. }
  954. async function getProjectData(projectID) {
  955. let project = await projectsModel.findOne({
  956. ID: projectID,
  957. });
  958. if (!project) throw new Error(`找不到项目:${projectID}`);
  959. let projectName = project.name;
  960. let author = ""; //编制人
  961. let auditor = ""; //审核人
  962. let compilationScope = ""; //编制范围
  963. let engineering = ""; //养护类别
  964. if (project.property && project.property.projectFeature) {
  965. for (let f of project.property.projectFeature) {
  966. if (f.key == "author") author = f.value;
  967. if (f.key == "auditor") auditor = f.value;
  968. if (f.key == "compilationScope") compilationScope = f.value;
  969. if (f.key == "engineering") engineering = f.value;
  970. }
  971. }
  972. if (!(project.property && project.property.unitPriceFile))
  973. throw new Error(`找不到单价文件:${projectID}`);
  974. let unitPriceFileId = project.property.unitPriceFile.id;
  975. return {
  976. ID: projectID,
  977. name: projectName,
  978. author: author,
  979. auditor: auditor,
  980. compilationScope: compilationScope,
  981. ParentID: project.ParentID,
  982. prjTypeName: engineering,
  983. property: project.property,
  984. unitPriceFileId: unitPriceFileId,
  985. };
  986. }
  987. async function getProjectGLJPrice(projectID, unitPriceFileId, property) {
  988. //取项目工料机数据
  989. let calcOptions = property.calcOptions;
  990. let decimalObj = property.decimal;
  991. let labourCoeDatas = []; //取调整价才需要用到
  992. let gljListModel = new GLJListModel();
  993. let [gljList, mixRatioConnectData, mixRatioMap, unitPriceMap] =
  994. await gljListModel.getListByProjectId(projectID, unitPriceFileId);
  995. let unitPriceFileModel = new UnitPriceFileModel();
  996. let unitFileInfo = await unitPriceFileModel.findDataByCondition({
  997. id: unitPriceFileId,
  998. });
  999. let machineConstCoe = unitFileInfo.machineConstCoe
  1000. ? unitFileInfo.machineConstCoe
  1001. : 1;
  1002. gljList = JSON.parse(JSON.stringify(gljList));
  1003. for (let glj of gljList) {
  1004. let tenderCoe = gljUtil.getTenderPriceCoe(glj, property);
  1005. let result = gljUtil.getGLJPrice(
  1006. glj,
  1007. {
  1008. gljList: gljList,
  1009. constData: { machineConstCoe: machineConstCoe },
  1010. },
  1011. calcOptions,
  1012. labourCoeDatas,
  1013. decimalObj,
  1014. false,
  1015. tenderCoe,
  1016. true
  1017. );
  1018. glj.marketPrice = result.marketPrice;
  1019. glj.basePrice = result.basePrice;
  1020. }
  1021. return {
  1022. gljList: gljList,
  1023. mixRatioMap: mixRatioMap,
  1024. };
  1025. }
  1026. async function calcProjectGLJQuantity(projectID, projectGLJDatas, property) {
  1027. let q_decimal = property.decimal.glj.quantity;
  1028. let rationGLJDatas = await ration_glj_model.find({
  1029. projectID: projectID,
  1030. });
  1031. let rationDatas = await ration_model.model.find({
  1032. projectID: projectID,
  1033. });
  1034. let billDatas = await bill_model.model.find({
  1035. projectID: projectID,
  1036. });
  1037. gljUtil.calcProjectGLJQuantity(
  1038. projectGLJDatas,
  1039. rationGLJDatas,
  1040. rationDatas,
  1041. billDatas,
  1042. q_decimal
  1043. );
  1044. }