project_facade.js 28 KB

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