project_facade.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876
  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. task.updateOne.filter[idFiled] = node.data[idFiled]; //现在复制项目也重新生成一个新的ID了,所以ID是唯一的
  165. delete task.updateOne.update[idFiled]; //防止误操作
  166. }
  167. return task;
  168. }
  169. }
  170. //data = {feeRateID:111111,projectID:1245}; type = feeRate
  171. async function markUpdateProject(data, type) {
  172. let query = {
  173. deleteInfo: null
  174. };
  175. if (type == "feeRate") { //更改了费率
  176. query['property.feeFile.id'] = data.feeRateID;
  177. }
  178. if (type == "unitFile") { //更改了单价文件
  179. query['property.unitPriceFile.id'] = data.unitFileID; //unitPriceFile
  180. }
  181. let projects = await projectsModel.find(query);
  182. return await markProjectsToChange(projects, type, data.projectID, data.isInclude);
  183. }
  184. async function markProjectsToChange(projects, type, extProjectID, isInclude) {
  185. let tasks = [];
  186. for (let p of projects) {
  187. if (isInclude != true) {
  188. if (extProjectID && p.ID === extProjectID) continue; //排除当前项目
  189. }
  190. tasks.push(generateMarkTask(type, p.ID));
  191. }
  192. return tasks.length > 0 ? await projectsModel.bulkWrite(tasks) : null;
  193. }
  194. async function removeProjectMark(projectID) {
  195. return await projectsModel.findOneAndUpdate({
  196. ID: projectID
  197. }, {
  198. "$unset": {
  199. "changeMark": 1
  200. }
  201. });
  202. }
  203. function generateMarkTask(value, projectID) {
  204. let task = {
  205. updateOne: {
  206. filter: {
  207. ID: projectID
  208. },
  209. update: {
  210. changeMark: value
  211. }
  212. }
  213. };
  214. return task
  215. }
  216. // {projectID: 5, propertyName: 'aaa', propertyValue: 1}
  217. function saveProperty(data, callback) {
  218. let obj = {};
  219. let pn = 'property.' + data.propertyName;
  220. obj[pn] = data.propertyValue;
  221. projectsModel.update({
  222. "ID": data.projectID
  223. }, obj, function (err) {
  224. if (err) {
  225. logger.err(pn + ' save error: ' + err);
  226. callback(err, null)
  227. } else {
  228. logger.info(pn + ' saved.');
  229. callback('', null);
  230. }
  231. });
  232. }
  233. async function getDefaultColSetting(libID) {
  234. return await stdColSettingModel.findOne({
  235. ID: libID,
  236. deleted: false
  237. }, '-_id main_tree_col');
  238. }
  239. async function getBudgetSummayDatas(projectIDs, userID, compilationID, overWriteUrl) {
  240. try {
  241. let projects = [];
  242. let names = [];
  243. let prjTypeNames = [];
  244. let compilationScopes = [];
  245. let decimal = null;
  246. let isProgressiveType = true;
  247. for (let ID of projectIDs) {
  248. projects.push(await getBillsByProjectID(ID));
  249. }
  250. if (projects.length == 0) {
  251. return [];
  252. }
  253. let mp = projects[0];
  254. names.push(mp.name);
  255. prjTypeNames.push(mp.prjTypeName);
  256. compilationScopes.push(mp.compilationScope);
  257. if (projects.length == 1) decimal = await decimal_facade.getProjectDecimal(projectIDs[0]); //如果只有一个项目,则没走合并的那一步,decimal会为空,从面报错
  258. for (let i = 1; i < projects.length; i++) {
  259. names.push(projects[i].name);
  260. prjTypeNames.push(projects[i].prjTypeName);
  261. compilationScopes.push(projects[i].compilationScope);
  262. decimal = await mergeProject(mp.roots, projects[i].roots);
  263. }
  264. let options_setting = await optionModel.findOne({
  265. user_id: userID,
  266. compilation_id: compilationID
  267. }).lean();
  268. if (options_setting && options_setting.options && options_setting.options.GENERALOPTS) isProgressiveType = options_setting.options.GENERALOPTS.progressiveType == 1 ? false : true;
  269. let SummaryAuditDetail = getReportData(names, mp.roots, prjTypeNames, compilationScopes, decimal, isProgressiveType, mp.progressiveInterval, overWriteUrl);
  270. let parentProject = await projectsModel.findOne({
  271. ID: mp.ParentID
  272. });
  273. let result = {
  274. prj: {},
  275. SummaryAudit: {
  276. "name": parentProject ? parentProject.name : "",
  277. "编制": mp.author,
  278. "复核": mp.auditor,
  279. "编制范围": mp.compilationScope
  280. },
  281. SummaryAuditDetail: SummaryAuditDetail
  282. };
  283. return result;
  284. } catch (e) {
  285. console.log(e.message)
  286. }
  287. }
  288. function getReportData(nameList, items, prjTypeNames, compilationScopes, decimal, isProgressiveType, progressiveInterval, overWriteUrl) {
  289. let datas = [],
  290. totalItem = null,
  291. one_to_four_Item = null;
  292. let overWrite = null;
  293. if (overWriteUrl && overWriteUrl != "") {
  294. overWrite = require("../../.." + overWriteUrl);
  295. }
  296. setChildrenDatas(items, datas);
  297. if (one_to_four_Item) recalcTotalItem(one_to_four_Item, datas, isProgressiveType, progressiveInterval);
  298. if (totalItem) recalcTotalItem(totalItem, datas, isProgressiveType, progressiveInterval);
  299. for (let d of datas) {
  300. if (d.billsTtlPrice && totalItem.billsTtlPrice) {
  301. d['各项费用比例'] = scMathUtil.roundForObj(d.billsTtlPrice / totalItem.billsTtlPrice * 100, 2)
  302. }
  303. d['prjNames'] = nameList;
  304. d['prjTypeNames'] = prjTypeNames;
  305. d['编制范围明细'] = compilationScopes;
  306. }
  307. return datas;
  308. function recalcTotalItem(item, datas, isProgressiveType, progressiveInterval) {
  309. let totalExp = item.calcBase;
  310. if (totalExp.indexOf('@') == -1) return;
  311. if (isProgressiveType && progressiveInterval) { //有累进的要重新计算总金额和技术经济综合指标
  312. for (let t of datas) {
  313. totalExp = totalExp.replace(t.ID, t.billsTtlPrice + "");
  314. }
  315. totalExp = totalExp.replace(/@/g, "");
  316. let nTotal = eval(totalExp);
  317. item.billsTtlPrice = scMathUtil.roundForObj(nTotal, decimal.bills.totalPrice);
  318. item['技术经济综合指标'] = (item.billsTtlAmt && parseFloat(item.billsTtlAmt) !== 0) ? scMathUtil.roundForObj(item.billsTtlPrice / item.billsTtlAmt, 2) : scMathUtil.roundForObj(item.billsTtlPrice, 2);
  319. }
  320. }
  321. function setChildrenDatas(children, arr, level = 0, rootFlag) {
  322. let temTotalPrice = 0;
  323. for (let c of children) {
  324. if (level == 0) rootFlag = c.flag; //取最顶层节点的固定清单类别
  325. let tbill = getBillDatas(c, level, rootFlag);
  326. arr.push(tbill);
  327. let sumChildren = setChildrenDatas(c.children, arr, level + 1, rootFlag);
  328. if (isProgressiveType && progressiveInterval && rootFlag == fixedFlag.MAINTENANCE_EXPENSES) { //如果要累进的,父节点要重新汇总
  329. if (c.children.length > 0) {
  330. tbill.billsTtlPrice = sumChildren;
  331. tbill['技术经济综合指标'] = (tbill.billsTtlAmt && parseFloat(tbill.billsTtlAmt) !== 0) ? scMathUtil.roundForObj(tbill.billsTtlPrice / tbill.billsTtlAmt, 2) : scMathUtil.roundForObj(tbill.billsTtlPrice, 2);
  332. }
  333. if (level > 0) temTotalPrice = scMathUtil.roundForObj(tbill.billsTtlPrice + temTotalPrice, decimal.bills.totalPrice);
  334. }
  335. }
  336. return temTotalPrice;
  337. }
  338. function getBillDatas(bills, level, rootFlag) {
  339. let tem = {
  340. ID: bills.ID,
  341. billsName: bills.name,
  342. billsCode: bills.code,
  343. billsUnit: bills.unit,
  344. billsTtlAmt: bills.quantity,
  345. billsPrices: [],
  346. billsUnitPrices: [],
  347. rationCommons: [],
  348. billsAmounts: [],
  349. '技术经济指标': [],
  350. billsLevel: level,
  351. calcBase: bills.calcBase,
  352. billsMemos: bills.remark
  353. };
  354. let total = 0;
  355. let rationTotal = 0;
  356. let baseTotal = 0;
  357. for (let n of nameList) {
  358. let p = 0; //金额
  359. let up = 0; //单价
  360. let ra = 0; //定额建安费
  361. let bt = 0; //累计相关
  362. if (bills.unitPrices[n]) up = scMathUtil.roundForObj(bills.unitPrices[n], decimal.bills.unitPrice);
  363. tem.billsUnitPrices.push(up);
  364. if (bills.prices[n]) {
  365. p = scMathUtil.roundForObj(bills.prices[n], decimal.bills.totalPrice);
  366. total = scMathUtil.roundForObj(p + total, decimal.process);
  367. }
  368. tem.billsPrices.push(p);
  369. if (bills.rationCommons[n]) {
  370. ra = scMathUtil.roundForObj(bills.rationCommons[n], decimal.bills.totalPrice);
  371. rationTotal = scMathUtil.roundForObj(ra + rationTotal, decimal.process);
  372. }
  373. tem.rationCommons.push(ra);
  374. if (bills.quantityMap[n] && parseFloat(bills.quantityMap[n]) !== 0) {
  375. tem.billsAmounts.push(bills.quantityMap[n]);
  376. tem['技术经济指标'].push(scMathUtil.roundForObj(p / bills.quantityMap[n], 2));
  377. } else {
  378. tem.billsAmounts.push(0);
  379. tem['技术经济指标'].push(scMathUtil.roundForObj(p, 2));
  380. }
  381. if (rootFlag == fixedFlag.MAINTENANCE_EXPENSES) { //如果是第三部分下的子清单,才要计算累计的相关信息
  382. if (bills.baseProgressiveFees[n]) {
  383. bt = scMathUtil.roundForObj(bills.baseProgressiveFees[n], decimal.bills.totalPrice);
  384. baseTotal = scMathUtil.roundForObj(bt + baseTotal, decimal.process);
  385. }
  386. }
  387. }
  388. tem.billsTtlPrice = scMathUtil.roundForObj(total, decimal.bills.totalPrice);
  389. if (progressiveInterval && isProgressiveType && rootFlag == fixedFlag.MAINTENANCE_EXPENSES) {
  390. let baseArr = calcUtil.getProgressive(bills.calcBase, overWrite ? overWrite.progression : undefined);
  391. if (baseArr.length > 0) {
  392. let deficiency = overWrite && overWrite.deficiency || null;
  393. let beyond = overWrite && overWrite.beyond || null;
  394. let calcTotal = calcUtil.getProgressiveFee(baseTotal, baseArr[0], progressiveInterval, decimal.bills.totalPrice, deficiency, beyond );
  395. tem.billsTtlPrice = calcTotal;
  396. let rate = scMathUtil.roundForObj(calcTotal * 100 / baseTotal, decimal.feeRate);
  397. tem.billsMemos = "费率:" + rate + "%";
  398. //“费率:n%”,n为汇总后重算的金额/汇总后的基数
  399. }
  400. }
  401. tem.rationTotal = scMathUtil.roundForObj(rationTotal, decimal.bills.totalPrice); //定额总建安费
  402. tem['技术经济综合指标'] = (tem.billsTtlAmt && parseFloat(tem.billsTtlAmt) !== 0) ? scMathUtil.roundForObj(tem.billsTtlPrice / tem.billsTtlAmt, 2) : scMathUtil.roundForObj(tem.billsTtlPrice, 2);
  403. if (bills.flag == fixedFlag.TOTAL_COST) totalItem = tem;
  404. if (bills.flag == fixedFlag.ONE_TO_FOUR_TOTAL) one_to_four_Item = tem;
  405. return tem
  406. }
  407. }
  408. async function mergeProject(main, sub) { //合并两个项目
  409. let decimal = await decimal_facade.getProjectDecimal(main[0].projectID);
  410. let project = await projectsModel.findOne({
  411. ID: main[0].projectID
  412. });
  413. let notMatchList = [];
  414. for (let s of sub) {
  415. //先找有没有相同的大项费用
  416. let same = findTheSameItem(main, s);
  417. same ? await mergeItem(same, s, decimal, project._doc) : notMatchList.push(s); //如果找到,则合并,找不到就放在未匹配表
  418. }
  419. for (let n of notMatchList) {
  420. main.push(n);
  421. }
  422. return decimal;
  423. }
  424. async function mergeItem(a, b, decimal, project) {
  425. let bqDecimal = await decimal_facade.getBillsQuantityDecimal(a.projectID, a.unit, project);
  426. a.quantity = a.quantity ? scMathUtil.roundForObj(a.quantity, bqDecimal) : 0;
  427. b.quantity = b.quantity ? scMathUtil.roundForObj(b.quantity, bqDecimal) : 0;
  428. a.quantity = scMathUtil.roundForObj(a.quantity + b.quantity, decimal.process);
  429. for (let name in b.prices) {
  430. a.prices[name] = b.prices[name];
  431. a.rationCommons[name] = b.rationCommons[name];
  432. a.quantityMap[name] = b.quantityMap[name];
  433. a.unitPrices[name] = b.unitPrices[name];
  434. a.baseProgressiveFees[name] = b.baseProgressiveFees[name];
  435. }
  436. for (let name in a.quantityMap) {
  437. a.quantityMap[name] = a.quantityMap[name] ? scMathUtil.roundForObj(a.quantityMap[name], bqDecimal) : 0;
  438. }
  439. await mergeChildren(a, b, decimal, project);
  440. }
  441. async function mergeChildren(a, b, decimal, project) {
  442. let notMatchList = [];
  443. if (a.children.length > 0 && b.children.length == 0) {
  444. return;
  445. } else if (a.children.length == 0 && b.children.length > 0) {
  446. a.children = b.children;
  447. return;
  448. }
  449. //=============剩下的是两者都有的情况
  450. for (let s of b.children) {
  451. let same = findTheSameItem(a.children, s);
  452. same ? await mergeItem(same, s, decimal, project) : notMatchList.push(s); //如果找到,则合并,找不到就放在未匹配表
  453. }
  454. for (let n of notMatchList) {
  455. let match = false; //符合插入标记
  456. //对于未匹配的子项,如果是固定清单:第100章至700章清单的子项,要匹配名字中的数字来做排充
  457. if (a.flag == fixedFlag.ONE_SEVEN_BILLS) {
  458. for (let i = 0; i < a.children.length; i++) {
  459. let m_name = a.children[i].name.replace(/[^0-9]/ig, "");
  460. let s_name = n.name.replace(/[^0-9]/ig, "");
  461. m_name = parseFloat(m_name);
  462. s_name = parseFloat(s_name);
  463. if (m_name && s_name) {
  464. if (m_name == s_name) {
  465. await mergeItem(a.children[i], n, project);
  466. match = true;
  467. break;
  468. }
  469. if (m_name > s_name) { //主节点名字中的数字大于被插节点,则被插节点放在主节点前面
  470. a.children.splice(i, 0, n);
  471. match = true;
  472. break;
  473. }
  474. }
  475. }
  476. } else { //其它的子项按编号进行排序
  477. for (let i = 0; i < a.children.length; i++) {
  478. let m_code = a.children[i].code;
  479. let s_code = n.code;
  480. if (m_code && s_code && m_code != "" && s_code != "") {
  481. if (m_code > s_code) {
  482. a.children.splice(i, 0, n);
  483. match = true;
  484. break;
  485. }
  486. }
  487. }
  488. }
  489. if (match == false) a.children.push(n) //没有插入成功,直接放到最后面
  490. }
  491. }
  492. function findTheSameItem(main, item) { //编号名称单位三个相同,认为是同一条清单
  493. return _.find(main, function (tem) {
  494. return isEqual(tem.code, item.code) && isEqual(tem.name, item.name) && isEqual(tem.unit, item.unit);
  495. })
  496. }
  497. function isEqual(a, b) { //粗略匹配,null undefind "" 认为相等
  498. return getValue(a) == getValue(b);
  499. function getValue(t) {
  500. if (t == null || t == undefined || t == "") return null;
  501. return t;
  502. }
  503. }
  504. async function getBillsByProjectID(projectID) {
  505. let roots = [],
  506. parentMap = {};
  507. let bills = await bill_model.model.find({
  508. projectID: projectID
  509. }, '-_id'); //取出所有清单
  510. let project = await projectsModel.findOne({
  511. ID: projectID
  512. });
  513. if (!project) throw new Error(`找不到项目:${projectID}`);
  514. let projectName = project.name;
  515. let author = ''; //编制人
  516. let auditor = ''; //审核人
  517. let compilationScope = ''; //编制范围
  518. let engineering = ''; //养护类别
  519. let progressiveType = 0; //累进计算类型
  520. let progressiveInterval = null;
  521. if (project.property && project.property.projectFeature) {
  522. for (let f of project.property.projectFeature) {
  523. if (f.key == 'author') author = f.value;
  524. if (f.key == 'auditor') auditor = f.value;
  525. if (f.key == 'compilationScope') compilationScope = f.value;
  526. if (f.key == 'engineering') engineering = f.value;
  527. }
  528. if (project.property.progressiveType) progressiveType = project.property.progressiveType;
  529. progressiveInterval = project.property.progressiveInterval;
  530. }
  531. for (let b of bills) {
  532. let commonFee = _.find(b._doc.fees, {
  533. "fieldName": "common"
  534. });
  535. let prices = {};
  536. let quantityMap = {};
  537. let unitPrices = {};
  538. let rationCommons = {};
  539. let baseProgressiveFees = {};
  540. let rationFee = _.find(b._doc.fees, {
  541. "fieldName": "rationCommon"
  542. });
  543. if (commonFee && commonFee.tenderTotalFee) prices[projectName] = commonFee.tenderTotalFee;
  544. if (commonFee && commonFee.tenderUnitFee) unitPrices[projectName] = commonFee.tenderUnitFee;
  545. if (rationFee && rationFee.tenderTotalFee) rationCommons[projectName] = rationFee.tenderTotalFee;
  546. baseProgressiveFees[projectName] = b.baseProgressiveFee;
  547. quantityMap[projectName] = b.quantity;
  548. let flagIndex = _.find(b._doc.flags, {
  549. 'fieldName': 'fixed'
  550. });
  551. let doc = {
  552. ID: b.ID,
  553. name: b.name,
  554. code: b.code,
  555. unit: b.unit,
  556. projectID: b.projectID,
  557. ParentID: b.ParentID,
  558. NextSiblingID: b.NextSiblingID,
  559. unitPrices: unitPrices,
  560. quantity: b.quantity,
  561. prices: prices,
  562. rationCommons: rationCommons,
  563. quantityMap: quantityMap,
  564. flag: flagIndex ? flagIndex.flag : -99,
  565. remark: b.remark,
  566. calcBase: b.calcBase,
  567. baseProgressiveFees: baseProgressiveFees
  568. }; //选取有用字段
  569. if (b.ParentID == -1) roots.push(doc);
  570. parentMap[b.ParentID] ? parentMap[b.ParentID].push(doc) : parentMap[b.ParentID] = [doc];
  571. } //设置子节点
  572. for (let r of roots) {
  573. setChildren(r, parentMap);
  574. }
  575. roots = sortChildren(roots);
  576. return {
  577. name: projectName,
  578. roots: roots,
  579. author: author,
  580. auditor: auditor,
  581. compilationScope: compilationScope,
  582. ParentID: project.ParentID,
  583. prjTypeName: engineering,
  584. progressiveType: progressiveType,
  585. progressiveInterval: progressiveInterval
  586. }
  587. }
  588. function setChildren(bill, parentMap) {
  589. let children = parentMap[bill.ID];
  590. if (children) {
  591. for (let c of children) {
  592. setChildren(c, parentMap);
  593. }
  594. bill.children = children;
  595. } else {
  596. bill.children = [];
  597. }
  598. }
  599. function sortChildren(lists) {
  600. let IDMap = {},
  601. nextMap = {},
  602. firstNode = null,
  603. newList = [];
  604. for (let l of lists) {
  605. if (l.children && l.children.length > 0) l.children = sortChildren(l.children); //递规排序
  606. IDMap[l.ID] = l;
  607. if (l.NextSiblingID != -1) nextMap[l.NextSiblingID] = l;
  608. }
  609. for (let t of lists) {
  610. if (!nextMap[t.ID]) { //如果在下一节点映射没找到,则是第一个节点
  611. firstNode = t;
  612. break;
  613. }
  614. }
  615. if (firstNode) {
  616. newList.push(firstNode);
  617. delete IDMap[firstNode.ID];
  618. setNext(firstNode, newList);
  619. }
  620. //容错处理,如果链断了的情况,直接添加到后面
  621. for (let key in IDMap) {
  622. if (IDMap[key]) newList.push(IDMap[key])
  623. }
  624. return newList;
  625. function setNext(node, array) {
  626. if (node.NextSiblingID != -1) {
  627. let next = IDMap[node.NextSiblingID];
  628. if (next) {
  629. array.push(next);
  630. delete IDMap[next.ID];
  631. setNext(next, array);
  632. }
  633. }
  634. }
  635. }
  636. async function getGLJSummayDatas(projectIDs) {
  637. let projects = [];
  638. let names = [];
  639. let prjTypeNames = [];
  640. let compilationScopes = [];
  641. try {
  642. for (let ID of projectIDs) {
  643. projects.push(await getProjectData(ID));
  644. }
  645. if (projects.length == 0) {
  646. return [];
  647. }
  648. let mp = projects[0];
  649. for (let p of projects) {
  650. names.push(p.name);
  651. prjTypeNames.push(p.prjTypeName);
  652. p.gljList = await getProjectGLJData(p.ID, p.unitPriceFileId, mp.property);
  653. compilationScopes.push(p.compilationScope);
  654. }
  655. let mList = mergeGLJ(mp, projects, names, prjTypeNames);
  656. mList = gljUtil.sortProjectGLJ(mList, _);
  657. let summaryGLJDatas = getSummaryGLJDatas(mList, mp.property.decimal, names, prjTypeNames, compilationScopes);
  658. let parentProject = await projectsModel.findOne({
  659. ID: mp.ParentID
  660. });
  661. let result = {
  662. prj: {},
  663. SummaryGljAudit: {
  664. "name": parentProject ? parentProject.name : "",
  665. "编制": mp.author,
  666. "复核": mp.auditor,
  667. "编制范围": mp.compilationScope
  668. },
  669. SummaryGljAuditDetail: summaryGLJDatas
  670. };
  671. return result;
  672. } catch (e) {
  673. console.log(e);
  674. }
  675. }
  676. function getSummaryGLJDatas(gljList, decimal, nameList, prjTypeNames, compilationScopes) {
  677. let datas = [],
  678. qdecimal = decimal.glj.quantity,
  679. process = decimal.process;
  680. for (let tem of gljList) {
  681. let d = {
  682. code: tem.code,
  683. name: tem.name,
  684. type: tem.type,
  685. unit: tem.unit,
  686. specs: tem.specs,
  687. marketPrice: tem.marketPrice,
  688. prjNames: nameList,
  689. prjTypeNames: prjTypeNames,
  690. quantityList: [],
  691. '编制范围明细': compilationScopes
  692. };
  693. let totalQuantity = 0;
  694. for (let n of nameList) {
  695. let q = tem.quantityMap[n] ? scMathUtil.roundForObj(tem.quantityMap[n], qdecimal) : 0;
  696. totalQuantity = scMathUtil.roundForObj(q + totalQuantity, process);
  697. d.quantityList.push(q);
  698. }
  699. d.totalQuantity = scMathUtil.roundForObj(totalQuantity, qdecimal);
  700. datas.push(d);
  701. }
  702. return datas;
  703. }
  704. function mergeGLJ(mp, projects) {
  705. let gljMap = {},
  706. gljList = [];
  707. for (let g of mp.gljList) {
  708. g.quantityMap = {};
  709. g.quantityMap[mp.name] = g.tenderQuantity;
  710. gljMap[gljUtil.getIndex(g)] = g;
  711. gljList.push(g);
  712. }
  713. for (let i = 1; i < projects.length; i++) {
  714. let temList = projects[i].gljList;
  715. for (let t of temList) {
  716. t.quantityMap = {};
  717. t.quantityMap[projects[i].name] = t.tenderQuantity;
  718. //这里除了5个属性相同判断为同一个之外,还要判断市场价相同,才认为是同一个工料机
  719. let connect_key = gljUtil.getIndex(t);
  720. let g = gljMap[connect_key];
  721. if (g && g.marketPrice == t.marketPrice) {
  722. g.quantityMap[projects[i].name] = t.tenderQuantity;
  723. } else {
  724. gljMap[connect_key] = t;
  725. gljList.push(t);
  726. }
  727. }
  728. }
  729. return gljList;
  730. }
  731. async function getProjectGLJData(projectID, unitPriceFileId, property) {
  732. //取项目工料机数据
  733. let projectGLJDatas = await getProjectGLJPrice(projectID, unitPriceFileId, property);
  734. await calcProjectGLJQuantity(projectID, projectGLJDatas, property);
  735. _.remove(projectGLJDatas.gljList, {
  736. 'quantity': 0
  737. });
  738. return projectGLJDatas.gljList;
  739. }
  740. async function getProjectData(projectID) {
  741. let project = await projectsModel.findOne({
  742. ID: projectID
  743. });
  744. if (!project) throw new Error(`找不到项目:${projectID}`);
  745. let projectName = project.name;
  746. let author = ''; //编制人
  747. let auditor = ''; //审核人
  748. let compilationScope = ''; //编制范围
  749. let engineering = ''; //养护类别
  750. if (project.property && project.property.projectFeature) {
  751. for (let f of project.property.projectFeature) {
  752. if (f.key == 'author') author = f.value;
  753. if (f.key == 'auditor') auditor = f.value;
  754. if (f.key == 'compilationScope') compilationScope = f.value;
  755. if (f.key == 'engineering') engineering = f.value;
  756. }
  757. }
  758. if (!(project.property && project.property.unitPriceFile)) throw new Error(`找不到单价文件:${projectID}`);
  759. let unitPriceFileId = project.property.unitPriceFile.id;
  760. return {
  761. ID: projectID,
  762. name: projectName,
  763. author: author,
  764. auditor: auditor,
  765. compilationScope: compilationScope,
  766. ParentID: project.ParentID,
  767. prjTypeName: engineering,
  768. property: project.property,
  769. unitPriceFileId: unitPriceFileId
  770. }
  771. }
  772. async function getProjectGLJPrice(projectID, unitPriceFileId, property) {
  773. //取项目工料机数据
  774. let calcOptions = property.calcOptions;
  775. let decimalObj = property.decimal;
  776. let labourCoeDatas = []; //取调整价才需要用到
  777. let gljListModel = new GLJListModel();
  778. let [gljList, mixRatioConnectData, mixRatioMap, unitPriceMap] = await gljListModel.getListByProjectId(projectID, unitPriceFileId);
  779. let unitPriceFileModel = new UnitPriceFileModel();
  780. let unitFileInfo = await unitPriceFileModel.findDataByCondition({id: unitPriceFileId});
  781. let machineConstCoe = unitFileInfo.machineConstCoe?unitFileInfo.machineConstCoe:1
  782. gljList = JSON.parse(JSON.stringify(gljList));
  783. for (let glj of gljList) {
  784. let tenderCoe = gljUtil.getTenderPriceCoe(glj, property);
  785. let result = gljUtil.getGLJPrice(glj, {
  786. gljList: gljList,
  787. constData:{machineConstCoe:machineConstCoe}
  788. }, calcOptions, labourCoeDatas, decimalObj, false,tenderCoe,true);
  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. }