project_facade.js 31 KB

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