project_facade.js 30 KB

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