project_facade.js 28 KB

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