project_facade.js 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919
  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. }
  294. }
  295. function getReportData(nameList, items, prjTypeNames, compilationScopes, decimal, isProgressiveType, progressiveInterval, overWriteUrl) {
  296. let datas = [],
  297. totalItem = null,
  298. one_to_four_Item = null;
  299. let overWrite = null;
  300. if (overWriteUrl && overWriteUrl != "") {
  301. overWrite = require("../../.." + overWriteUrl);
  302. }
  303. setChildrenDatas(items, datas);
  304. if (one_to_four_Item) recalcTotalItem(one_to_four_Item, datas, isProgressiveType, progressiveInterval);
  305. if (totalItem) recalcTotalItem(totalItem, datas, isProgressiveType, progressiveInterval);
  306. for (let d of datas) {
  307. if (d.billsTtlPrice && totalItem.billsTtlPrice) {
  308. d['各项费用比例'] = scMathUtil.roundForObj(d.billsTtlPrice / totalItem.billsTtlPrice * 100, 2)
  309. }
  310. d['prjNames'] = nameList;
  311. d['prjTypeNames'] = prjTypeNames;
  312. d['编制范围明细'] = compilationScopes;
  313. }
  314. return datas;
  315. function recalcTotalItem(item, datas, isProgressiveType, progressiveInterval) {
  316. let totalExp = item.calcBase;
  317. if (totalExp.indexOf('@') == -1) return;
  318. if (isProgressiveType && progressiveInterval) { //有累进的要重新计算总金额和技术经济综合指标
  319. let hasReplace = false;
  320. for (let t of datas) {
  321. if (totalExp.includes(t.ID)) hasReplace = true; // 强壮性处理:控制提前计算问题(ID在datas中找不到)
  322. totalExp = totalExp.replace(t.ID, t.billsTtlPrice + "");
  323. }
  324. if (hasReplace) {
  325. totalExp = totalExp.replace(/@/g, "");
  326. //还有其他符号(如%)
  327. totalExp = totalExp.replace(/%/g, " / 100 ");
  328. let nTotal = eval(totalExp);
  329. item.billsTtlPrice = scMathUtil.roundForObj(nTotal, decimal.bills.totalPrice);
  330. item['技术经济综合指标'] = (item.billsTtlAmt && parseFloat(item.billsTtlAmt) !== 0) ? scMathUtil.roundForObj(item.billsTtlPrice / item.billsTtlAmt, 2) : scMathUtil.roundForObj(item.billsTtlPrice, 2);
  331. }
  332. }
  333. }
  334. function setChildrenDatas(children, arr, level = 0, rootFlag) {
  335. let temTotalPrice = 0;
  336. for (let c of children) {
  337. if (level == 0) rootFlag = c.flag; //取最顶层节点的固定清单类别
  338. let tbill = getBillDatas(c, level, rootFlag);
  339. arr.push(tbill);
  340. let sumChildren = setChildrenDatas(c.children, arr, level + 1, rootFlag);
  341. if (isProgressiveType && progressiveInterval) { //如果要累进的,父节点要重新汇总
  342. if (c.children.length > 0) {
  343. tbill.billsTtlPrice = sumChildren;
  344. tbill['技术经济综合指标'] = (tbill.billsTtlAmt && parseFloat(tbill.billsTtlAmt) !== 0) ? scMathUtil.roundForObj(tbill.billsTtlPrice / tbill.billsTtlAmt, 2) : scMathUtil.roundForObj(tbill.billsTtlPrice, 2);
  345. } else if (tbill.calcBase && tbill.calcBase.indexOf('@') >= 0 && tbill.calcBase.indexOf('{') < 0) {
  346. // 说明:在实际中,发现清单‘第一、二、三部分费用合计’没有再计算,这样会造成问题(实际情况比较复杂,需要多方测试)
  347. recalcTotalItem(tbill, arr, isProgressiveType, progressiveInterval);
  348. }
  349. if (level > 0) temTotalPrice = scMathUtil.roundForObj(tbill.billsTtlPrice + temTotalPrice, decimal.bills.totalPrice);
  350. }
  351. }
  352. return temTotalPrice;
  353. }
  354. function getBillDatas(bills, level, rootFlag) {
  355. let tem = {
  356. ID: bills.ID,
  357. billsName: bills.name,
  358. billsCode: bills.code,
  359. billsUnit: bills.unit,
  360. billsTtlAmt: bills.quantity,
  361. billsPrices: [],
  362. billsUnitPrices: [],
  363. rationCommons: [],
  364. billsAmounts: [],
  365. '技术经济指标': [],
  366. billsLevel: level,
  367. calcBase: bills.calcBase,
  368. billsMemos: bills.remark
  369. };
  370. let total = 0;
  371. let rationTotal = 0;
  372. let baseTotal = 0;
  373. for (let n of nameList) {
  374. let p = 0; //金额
  375. let up = 0; //单价
  376. let ra = 0; //定额建安费
  377. let bt = 0; //累计相关
  378. if (bills.unitPrices[n]) up = scMathUtil.roundForObj(bills.unitPrices[n], decimal.bills.unitPrice);
  379. tem.billsUnitPrices.push(up);
  380. if (bills.prices[n]) {
  381. p = scMathUtil.roundForObj(bills.prices[n], decimal.bills.totalPrice);
  382. total = scMathUtil.roundForObj(p + total, decimal.process);
  383. }
  384. tem.billsPrices.push(p);
  385. if (bills.rationCommons[n]) {
  386. ra = scMathUtil.roundForObj(bills.rationCommons[n], decimal.bills.totalPrice);
  387. rationTotal = scMathUtil.roundForObj(ra + rationTotal, decimal.process);
  388. }
  389. tem.rationCommons.push(ra);
  390. if (bills.quantityMap[n] && parseFloat(bills.quantityMap[n]) !== 0) {
  391. tem.billsAmounts.push(bills.quantityMap[n]);
  392. tem['技术经济指标'].push(scMathUtil.roundForObj(p / bills.quantityMap[n], 2));
  393. } else {
  394. tem.billsAmounts.push(0);
  395. tem['技术经济指标'].push(scMathUtil.roundForObj(p, 2));
  396. }
  397. //如果是第三部分下的子清单,才要计算累计的相关信息
  398. // 10-26 需求变更,所有清单都算累计
  399. /* if (rootFlag == fixedFlag.MAINTENANCE_EXPENSES) {
  400. if (bills.baseProgressiveFees[n]) {
  401. bt = scMathUtil.roundForObj(bills.baseProgressiveFees[n], decimal.bills.totalPrice);
  402. baseTotal = scMathUtil.roundForObj(bt + baseTotal, decimal.process);
  403. }
  404. } */
  405. if (bills.baseProgressiveFees[n]) {
  406. bt = scMathUtil.roundForObj(bills.baseProgressiveFees[n], decimal.bills.totalPrice);
  407. baseTotal = scMathUtil.roundForObj(bt + baseTotal, decimal.process);
  408. }
  409. }
  410. tem.billsTtlPrice = scMathUtil.roundForObj(total, decimal.bills.totalPrice);
  411. // 10-26 需求变更,所有清单都算累计 && rootFlag == fixedFlag.MAINTENANCE_EXPENSES
  412. if (progressiveInterval && isProgressiveType) {
  413. let baseArr = calcUtil.getProgressive(bills.calcBase, overWrite ? overWrite.progression : undefined);
  414. if (baseArr.length > 0) {
  415. let deficiency = overWrite && overWrite.deficiency || null;
  416. let beyond = overWrite && overWrite.beyond || null;
  417. let calcTotal = calcUtil.getProgressiveFee(baseTotal, baseArr[0], progressiveInterval, decimal.bills.totalPrice, deficiency, beyond );
  418. tem.billsTtlPrice = calcTotal;
  419. let rate = scMathUtil.roundForObj(calcTotal * 100 / baseTotal, decimal.feeRate);
  420. tem.billsMemos = "费率:" + rate + "%";
  421. //“费率:n%”,n为汇总后重算的金额/汇总后的基数
  422. }
  423. }
  424. tem.rationTotal = scMathUtil.roundForObj(rationTotal, decimal.bills.totalPrice); //定额总建安费
  425. tem['技术经济综合指标'] = (tem.billsTtlAmt && parseFloat(tem.billsTtlAmt) !== 0) ? scMathUtil.roundForObj(tem.billsTtlPrice / tem.billsTtlAmt, 2) : scMathUtil.roundForObj(tem.billsTtlPrice, 2);
  426. if (bills.flag == fixedFlag.TOTAL_COST) totalItem = tem;
  427. if (bills.flag == fixedFlag.ONE_TO_FOUR_TOTAL) one_to_four_Item = tem;
  428. return tem
  429. }
  430. }
  431. async function mergeProject(main, sub) { //合并两个项目
  432. let decimal = await decimal_facade.getProjectDecimal(main[0].projectID);
  433. let project = await projectsModel.findOne({
  434. ID: main[0].projectID
  435. });
  436. let notMatchList = [];
  437. for (let s of sub) {
  438. //先找有没有相同的大项费用
  439. let same = findTheSameItem(main, s);
  440. same ? await mergeItem(same, s, decimal, project._doc) : notMatchList.push(s); //如果找到,则合并,找不到就放在未匹配表
  441. }
  442. for (let n of notMatchList) {
  443. main.push(n);
  444. }
  445. return decimal;
  446. }
  447. async function mergeItem(a, b, decimal, project) {
  448. let bqDecimal = await decimal_facade.getBillsQuantityDecimal(a.projectID, a.unit, project);
  449. a.quantity = a.quantity ? scMathUtil.roundForObj(a.quantity, bqDecimal) : 0;
  450. b.quantity = b.quantity ? scMathUtil.roundForObj(b.quantity, bqDecimal) : 0;
  451. a.quantity = scMathUtil.roundForObj(a.quantity + b.quantity, decimal.process);
  452. for (let name in b.prices) {
  453. a.prices[name] = b.prices[name];
  454. a.rationCommons[name] = b.rationCommons[name];
  455. a.quantityMap[name] = b.quantityMap[name];
  456. a.unitPrices[name] = b.unitPrices[name];
  457. a.baseProgressiveFees[name] = b.baseProgressiveFees[name];
  458. }
  459. for (let name in a.quantityMap) {
  460. a.quantityMap[name] = a.quantityMap[name] ? scMathUtil.roundForObj(a.quantityMap[name], bqDecimal) : 0;
  461. }
  462. await mergeChildren(a, b, decimal, project);
  463. }
  464. async function mergeChildren(a, b, decimal, project) {
  465. let notMatchList = [];
  466. if (a.children.length > 0 && b.children.length == 0) {
  467. return;
  468. } else if (a.children.length == 0 && b.children.length > 0) {
  469. a.children = b.children;
  470. return;
  471. }
  472. //=============剩下的是两者都有的情况
  473. for (let s of b.children) {
  474. let same = findTheSameItem(a.children, s);
  475. same ? await mergeItem(same, s, decimal, project) : notMatchList.push(s); //如果找到,则合并,找不到就放在未匹配表
  476. }
  477. for (let n of notMatchList) {
  478. let match = false; //符合插入标记
  479. //对于未匹配的子项,如果是固定清单:第100章至700章清单的子项,要匹配名字中的数字来做排充
  480. if (a.flag == fixedFlag.ONE_SEVEN_BILLS) {
  481. for (let i = 0; i < a.children.length; i++) {
  482. let m_name = a.children[i].name.replace(/[^0-9]/ig, "");
  483. let s_name = n.name.replace(/[^0-9]/ig, "");
  484. m_name = parseFloat(m_name);
  485. s_name = parseFloat(s_name);
  486. if (m_name && s_name) {
  487. if (m_name == s_name) {
  488. await mergeItem(a.children[i], n, project);
  489. match = true;
  490. break;
  491. }
  492. if (m_name > s_name) { //主节点名字中的数字大于被插节点,则被插节点放在主节点前面
  493. a.children.splice(i, 0, n);
  494. match = true;
  495. break;
  496. }
  497. }
  498. }
  499. } else { //其它的子项按编号进行排序
  500. for (let i = 0; i < a.children.length; i++) {
  501. let m_code = a.children[i].code;
  502. let s_code = n.code;
  503. if (m_code && s_code && m_code != "" && s_code != "") {
  504. if (m_code > s_code) {
  505. a.children.splice(i, 0, n);
  506. match = true;
  507. break;
  508. }
  509. }
  510. }
  511. }
  512. if (match == false) a.children.push(n) //没有插入成功,直接放到最后面
  513. }
  514. }
  515. function findTheSameItem(main, item) { //编号名称单位三个相同,认为是同一条清单
  516. return _.find(main, function (tem) {
  517. return isEqual(tem.code, item.code) && isEqual(tem.name, item.name) && isEqual(tem.unit, item.unit);
  518. })
  519. }
  520. function isEqual(a, b) { //粗略匹配,null undefind "" 认为相等
  521. return getValue(a) == getValue(b);
  522. function getValue(t) {
  523. if (t == null || t == undefined || t == "") return null;
  524. return t;
  525. }
  526. }
  527. async function getBillsByProjectID(projectID) {
  528. let roots = [],
  529. parentMap = {};
  530. let bills = await bill_model.model.find({
  531. projectID: projectID
  532. }, '-_id'); //取出所有清单
  533. let project = await projectsModel.findOne({
  534. ID: projectID
  535. });
  536. if (!project) throw new Error(`找不到项目:${projectID}`);
  537. let projectName = project.name;
  538. let author = ''; //编制人
  539. let auditor = ''; //审核人
  540. let compilationScope = ''; //编制范围
  541. let engineering = ''; //养护类别
  542. let progressiveType = 0; //累进计算类型
  543. let progressiveInterval = null;
  544. if (project.property && project.property.projectFeature) {
  545. for (let f of project.property.projectFeature) {
  546. if (f.key == 'author') author = f.value;
  547. if (f.key == 'auditor') auditor = f.value;
  548. if (f.key == 'compilationScope') compilationScope = f.value;
  549. if (f.key == 'engineering') engineering = f.value;
  550. }
  551. if (project.property.progressiveType) progressiveType = project.property.progressiveType;
  552. progressiveInterval = project.property.progressiveInterval;
  553. }
  554. for (let b of bills) {
  555. let commonFee = _.find(b._doc.fees, {
  556. "fieldName": "common"
  557. });
  558. let prices = {};
  559. let quantityMap = {};
  560. let unitPrices = {};
  561. let rationCommons = {};
  562. let baseProgressiveFees = {};
  563. let rationFee = _.find(b._doc.fees, {
  564. "fieldName": "rationCommon"
  565. });
  566. if (commonFee && commonFee.tenderTotalFee) prices[projectName] = commonFee.tenderTotalFee;
  567. if (commonFee && commonFee.tenderUnitFee) unitPrices[projectName] = commonFee.tenderUnitFee;
  568. if (rationFee && rationFee.tenderTotalFee) rationCommons[projectName] = rationFee.tenderTotalFee;
  569. baseProgressiveFees[projectName] = b.baseProgressiveFee;
  570. quantityMap[projectName] = b.quantity;
  571. let flagIndex = _.find(b._doc.flags, {
  572. 'fieldName': 'fixed'
  573. });
  574. let doc = {
  575. ID: b.ID,
  576. name: b.name,
  577. code: b.code,
  578. unit: b.unit,
  579. projectID: b.projectID,
  580. ParentID: b.ParentID,
  581. NextSiblingID: b.NextSiblingID,
  582. unitPrices: unitPrices,
  583. quantity: b.quantity,
  584. prices: prices,
  585. rationCommons: rationCommons,
  586. quantityMap: quantityMap,
  587. flag: flagIndex ? flagIndex.flag : -99,
  588. remark: b.remark,
  589. calcBase: b.calcBase,
  590. baseProgressiveFees: baseProgressiveFees
  591. }; //选取有用字段
  592. if (b.ParentID == -1) roots.push(doc);
  593. parentMap[b.ParentID] ? parentMap[b.ParentID].push(doc) : parentMap[b.ParentID] = [doc];
  594. } //设置子节点
  595. for (let r of roots) {
  596. setChildren(r, parentMap);
  597. }
  598. roots = sortChildren(roots);
  599. return {
  600. name: projectName,
  601. roots: roots,
  602. author: author,
  603. auditor: auditor,
  604. compilationScope: compilationScope,
  605. ParentID: project.ParentID,
  606. prjTypeName: engineering,
  607. progressiveType: progressiveType,
  608. progressiveInterval: progressiveInterval
  609. }
  610. }
  611. function setChildren(bill, parentMap) {
  612. let children = parentMap[bill.ID];
  613. if (children) {
  614. for (let c of children) {
  615. setChildren(c, parentMap);
  616. }
  617. bill.children = children;
  618. } else {
  619. bill.children = [];
  620. }
  621. }
  622. function sortChildren(lists) {
  623. let IDMap = {},
  624. nextMap = {},
  625. firstNode = null,
  626. newList = [];
  627. for (let l of lists) {
  628. if (l.children && l.children.length > 0) l.children = sortChildren(l.children); //递规排序
  629. IDMap[l.ID] = l;
  630. if (l.NextSiblingID != -1) nextMap[l.NextSiblingID] = l;
  631. }
  632. for (let t of lists) {
  633. if (!nextMap[t.ID]) { //如果在下一节点映射没找到,则是第一个节点
  634. firstNode = t;
  635. break;
  636. }
  637. }
  638. if (firstNode) {
  639. newList.push(firstNode);
  640. delete IDMap[firstNode.ID];
  641. setNext(firstNode, newList);
  642. }
  643. //容错处理,如果链断了的情况,直接添加到后面
  644. for (let key in IDMap) {
  645. if (IDMap[key]) newList.push(IDMap[key])
  646. }
  647. return newList;
  648. function setNext(node, array) {
  649. if (node.NextSiblingID != -1) {
  650. let next = IDMap[node.NextSiblingID];
  651. if (next) {
  652. array.push(next);
  653. delete IDMap[next.ID];
  654. setNext(next, array);
  655. }
  656. }
  657. }
  658. }
  659. async function getGLJSummayDatas(projectIDs, compilationName = '') {
  660. let projects = [];
  661. let names = [];
  662. let prjTypeNames = [];
  663. let compilationScopes = [];
  664. try {
  665. for (let ID of projectIDs) {
  666. projects.push(await getProjectData(ID));
  667. }
  668. if (projects.length == 0) {
  669. return [];
  670. }
  671. let mp = projects[0];
  672. for (let p of projects) {
  673. names.push(p.name);
  674. prjTypeNames.push(p.prjTypeName);
  675. p.gljList = await getProjectGLJData(p.ID, p.unitPriceFileId, mp.property);
  676. compilationScopes.push(p.compilationScope);
  677. }
  678. let mList = mergeGLJ(mp, projects, names, prjTypeNames, compilationName);
  679. mList = gljUtil.sortProjectGLJ(mList, _);
  680. let summaryGLJDatas = getSummaryGLJDatas(mList, mp.property.decimal, names, prjTypeNames, compilationScopes);
  681. let parentProject = await projectsModel.findOne({
  682. ID: mp.ParentID
  683. });
  684. let result = {
  685. prj: {},
  686. SummaryGljAudit: {
  687. "name": parentProject ? parentProject.name : "",
  688. "编制": mp.author,
  689. "复核": mp.auditor,
  690. "编制范围": mp.compilationScope
  691. },
  692. SummaryGljAuditDetail: summaryGLJDatas
  693. };
  694. return result;
  695. } catch (e) {
  696. console.log(e.toString());
  697. }
  698. }
  699. function getSummaryGLJDatas(gljList, decimal, nameList, prjTypeNames, compilationScopes) {
  700. let datas = [],
  701. qdecimal = decimal.glj.quantity,
  702. upDecimal = decimal.glj.unitPrice,
  703. process = decimal.process;
  704. for (let tem of gljList) {
  705. let d = {
  706. code: tem.code,
  707. name: tem.name,
  708. type: tem.type,
  709. unit: tem.unit,
  710. specs: tem.specs,
  711. marketPrice: tem.marketPrice,
  712. marketPriceList: [],
  713. prjNames: nameList,
  714. prjTypeNames: prjTypeNames,
  715. quantityList: [],
  716. '编制范围明细': compilationScopes
  717. };
  718. let totalQuantity = 0;
  719. let totalPrice = 0;
  720. for (let n of nameList) {
  721. let q = tem.quantityMap[n] ? scMathUtil.roundForObj(tem.quantityMap[n], qdecimal) : 0;
  722. totalQuantity = scMathUtil.roundForObj(q + totalQuantity, process);
  723. d.quantityList.push(q);
  724. let up = tem.unitPriceMap[n] ? scMathUtil.roundForObj(tem.unitPriceMap[n], upDecimal) : 0;
  725. d.marketPriceList.push(up);
  726. totalPrice = scMathUtil.roundForObj(q * up + totalPrice, process);
  727. }
  728. d.totalQuantity = scMathUtil.roundForObj(totalQuantity, qdecimal);
  729. d.totalPrice = scMathUtil.roundForObj(totalPrice, upDecimal);
  730. datas.push(d);
  731. }
  732. return datas;
  733. }
  734. function mergeGLJ(mp, projects, names, prjTypeNames, compilationName = '') {
  735. let gljMap = {},
  736. gljList = [];
  737. const noPriceChkList = ['甘肃养护(2021)', '重庆养护(2018)', '浙江养护(2005)', '安徽养护(2018)', '山东养护(2016)', '湖南养护(2014)', '广西日常养护年度预算(2020)'];
  738. const noPriceCheck = noPriceChkList.indexOf(compilationName) >= 0;
  739. for (let g of mp.gljList) {
  740. g.quantityMap = {};
  741. g.quantityMap[mp.name] = g.tenderQuantity;
  742. g.unitPriceMap = {};
  743. g.unitPriceMap[mp.name] = g.marketPrice;
  744. gljMap[gljUtil.getIndex(g)] = g;
  745. gljList.push(g);
  746. }
  747. for (let i = 1; i < projects.length; i++) {
  748. let temList = projects[i].gljList;
  749. for (let t of temList) {
  750. t.quantityMap = {};
  751. t.quantityMap[projects[i].name] = t.tenderQuantity;
  752. t.unitPriceMap = {};
  753. t.unitPriceMap[projects[i].name] = t.marketPrice;
  754. //这里除了5个属性相同判断为同一个之外,还要判断市场价相同,才认为是同一个工料机
  755. //但有些省份不需要检测,体现在noPriceCheck标记
  756. let connect_key = gljUtil.getIndex(t);
  757. let g = gljMap[connect_key];
  758. if (g && (noPriceCheck || g.marketPrice == t.marketPrice)) {
  759. g.quantityMap[projects[i].name] = t.tenderQuantity;
  760. g.unitPriceMap[projects[i].name] = t.marketPrice;
  761. } else {
  762. gljMap[connect_key] = t;
  763. gljList.push(t);
  764. }
  765. }
  766. }
  767. return gljList;
  768. }
  769. async function getProjectGLJData(projectID, unitPriceFileId, property) {
  770. //取项目工料机数据
  771. let projectGLJDatas = await getProjectGLJPrice(projectID, unitPriceFileId, property);
  772. await calcProjectGLJQuantity(projectID, projectGLJDatas, property);
  773. _.remove(projectGLJDatas.gljList, {
  774. 'quantity': 0
  775. });
  776. return projectGLJDatas.gljList;
  777. }
  778. async function getProjectData(projectID) {
  779. let project = await projectsModel.findOne({
  780. ID: projectID
  781. });
  782. if (!project) throw new Error(`找不到项目:${projectID}`);
  783. let projectName = project.name;
  784. let author = ''; //编制人
  785. let auditor = ''; //审核人
  786. let compilationScope = ''; //编制范围
  787. let engineering = ''; //养护类别
  788. if (project.property && project.property.projectFeature) {
  789. for (let f of project.property.projectFeature) {
  790. if (f.key == 'author') author = f.value;
  791. if (f.key == 'auditor') auditor = f.value;
  792. if (f.key == 'compilationScope') compilationScope = f.value;
  793. if (f.key == 'engineering') engineering = f.value;
  794. }
  795. }
  796. if (!(project.property && project.property.unitPriceFile)) throw new Error(`找不到单价文件:${projectID}`);
  797. let unitPriceFileId = project.property.unitPriceFile.id;
  798. return {
  799. ID: projectID,
  800. name: projectName,
  801. author: author,
  802. auditor: auditor,
  803. compilationScope: compilationScope,
  804. ParentID: project.ParentID,
  805. prjTypeName: engineering,
  806. property: project.property,
  807. unitPriceFileId: unitPriceFileId
  808. }
  809. }
  810. async function getProjectGLJPrice(projectID, unitPriceFileId, property) {
  811. //取项目工料机数据
  812. let calcOptions = property.calcOptions;
  813. let decimalObj = property.decimal;
  814. let labourCoeDatas = []; //取调整价才需要用到
  815. let gljListModel = new GLJListModel();
  816. let [gljList, mixRatioConnectData, mixRatioMap, unitPriceMap] = await gljListModel.getListByProjectId(projectID, unitPriceFileId);
  817. let unitPriceFileModel = new UnitPriceFileModel();
  818. let unitFileInfo = await unitPriceFileModel.findDataByCondition({id: unitPriceFileId});
  819. let machineConstCoe = unitFileInfo.machineConstCoe?unitFileInfo.machineConstCoe:1
  820. gljList = JSON.parse(JSON.stringify(gljList));
  821. for (let glj of gljList) {
  822. let tenderCoe = gljUtil.getTenderPriceCoe(glj, property);
  823. let result = gljUtil.getGLJPrice(glj, {
  824. gljList: gljList,
  825. constData:{machineConstCoe:machineConstCoe}
  826. }, calcOptions, labourCoeDatas, decimalObj, false,tenderCoe,true);
  827. glj.marketPrice = result.marketPrice;
  828. glj.basePrice = result.basePrice;
  829. }
  830. return {
  831. gljList: gljList,
  832. mixRatioMap: mixRatioMap
  833. };
  834. }
  835. async function calcProjectGLJQuantity(projectID, projectGLJDatas, property) {
  836. let q_decimal = property.decimal.glj.quantity;
  837. let rationGLJDatas = await ration_glj_model.find({
  838. 'projectID': projectID
  839. });
  840. let rationDatas = await ration_model.model.find({
  841. 'projectID': projectID
  842. });
  843. let billDatas = await bill_model.model.find({
  844. 'projectID': projectID
  845. });
  846. gljUtil.calcProjectGLJQuantity(projectGLJDatas, rationGLJDatas, rationDatas, billDatas, q_decimal)
  847. }