project_facade.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866
  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 calcTotal = calcUtil.getProgressiveFee(baseTotal, baseArr[0], progressiveInterval, decimal.bills.totalPrice, overWrite ? overWrite.deficiency : undefined);
  392. tem.billsTtlPrice = calcTotal;
  393. let rate = scMathUtil.roundForObj(calcTotal * 100 / baseTotal, decimal.feeRate);
  394. tem.billsMemos = "费率:" + rate + "%";
  395. //“费率:n%”,n为汇总后重算的金额/汇总后的基数
  396. }
  397. }
  398. tem.rationTotal = scMathUtil.roundForObj(rationTotal, decimal.bills.totalPrice); //定额总建安费
  399. tem['技术经济综合指标'] = (tem.billsTtlAmt && parseFloat(tem.billsTtlAmt) !== 0) ? scMathUtil.roundForObj(tem.billsTtlPrice / tem.billsTtlAmt, 2) : scMathUtil.roundForObj(tem.billsTtlPrice, 2);
  400. if (bills.flag == fixedFlag.TOTAL_COST) totalItem = tem;
  401. if (bills.flag == fixedFlag.ONE_TO_FOUR_TOTAL) one_to_four_Item = tem;
  402. return tem
  403. }
  404. }
  405. async function mergeProject(main, sub) { //合并两个项目
  406. let decimal = await decimal_facade.getProjectDecimal(main[0].projectID);
  407. let project = await projectsModel.findOne({
  408. ID: main[0].projectID
  409. });
  410. let notMatchList = [];
  411. for (let s of sub) {
  412. //先找有没有相同的大项费用
  413. let same = findTheSameItem(main, s);
  414. same ? await mergeItem(same, s, decimal, project._doc) : notMatchList.push(s); //如果找到,则合并,找不到就放在未匹配表
  415. }
  416. for (let n of notMatchList) {
  417. main.push(n);
  418. }
  419. return decimal;
  420. }
  421. async function mergeItem(a, b, decimal, project) {
  422. let bqDecimal = await decimal_facade.getBillsQuantityDecimal(a.projectID, a.unit, project);
  423. a.quantity = a.quantity ? scMathUtil.roundForObj(a.quantity, bqDecimal) : 0;
  424. b.quantity = b.quantity ? scMathUtil.roundForObj(b.quantity, bqDecimal) : 0;
  425. a.quantity = scMathUtil.roundForObj(a.quantity + b.quantity, decimal.process);
  426. for (let name in b.prices) {
  427. a.prices[name] = b.prices[name];
  428. a.rationCommons[name] = b.rationCommons[name];
  429. a.quantityMap[name] = b.quantityMap[name];
  430. a.unitPrices[name] = b.unitPrices[name];
  431. a.baseProgressiveFees[name] = b.baseProgressiveFees[name];
  432. }
  433. for (let name in a.quantityMap) {
  434. a.quantityMap[name] = a.quantityMap[name] ? scMathUtil.roundForObj(a.quantityMap[name], bqDecimal) : 0;
  435. }
  436. await mergeChildren(a, b, decimal, project);
  437. }
  438. async function mergeChildren(a, b, decimal, project) {
  439. let notMatchList = [];
  440. if (a.children.length > 0 && b.children.length == 0) {
  441. return;
  442. } else if (a.children.length == 0 && b.children.length > 0) {
  443. a.children = b.children;
  444. return;
  445. }
  446. //=============剩下的是两者都有的情况
  447. for (let s of b.children) {
  448. let same = findTheSameItem(a.children, s);
  449. same ? await mergeItem(same, s, decimal, project) : notMatchList.push(s); //如果找到,则合并,找不到就放在未匹配表
  450. }
  451. for (let n of notMatchList) {
  452. let match = false; //符合插入标记
  453. //对于未匹配的子项,如果是固定清单:第100章至700章清单的子项,要匹配名字中的数字来做排充
  454. if (a.flag == fixedFlag.ONE_SEVEN_BILLS) {
  455. for (let i = 0; i < a.children.length; i++) {
  456. let m_name = a.children[i].name.replace(/[^0-9]/ig, "");
  457. let s_name = n.name.replace(/[^0-9]/ig, "");
  458. m_name = parseFloat(m_name);
  459. s_name = parseFloat(s_name);
  460. if (m_name && s_name) {
  461. if (m_name == s_name) {
  462. await mergeItem(a.children[i], n, project);
  463. match = true;
  464. break;
  465. }
  466. if (m_name > s_name) { //主节点名字中的数字大于被插节点,则被插节点放在主节点前面
  467. a.children.splice(i, 0, n);
  468. match = true;
  469. break;
  470. }
  471. }
  472. }
  473. } else { //其它的子项按编号进行排序
  474. for (let i = 0; i < a.children.length; i++) {
  475. let m_code = a.children[i].code;
  476. let s_code = n.code;
  477. if (m_code && s_code && m_code != "" && s_code != "") {
  478. if (m_code > s_code) {
  479. a.children.splice(i, 0, n);
  480. match = true;
  481. break;
  482. }
  483. }
  484. }
  485. }
  486. if (match == false) a.children.push(n) //没有插入成功,直接放到最后面
  487. }
  488. }
  489. function findTheSameItem(main, item) { //编号名称单位三个相同,认为是同一条清单
  490. return _.find(main, function (tem) {
  491. return isEqual(tem.code, item.code) && isEqual(tem.name, item.name) && isEqual(tem.unit, item.unit);
  492. })
  493. }
  494. function isEqual(a, b) { //粗略匹配,null undefind "" 认为相等
  495. return getValue(a) == getValue(b);
  496. function getValue(t) {
  497. if (t == null || t == undefined || t == "") return null;
  498. return t;
  499. }
  500. }
  501. async function getBillsByProjectID(projectID) {
  502. let roots = [],
  503. parentMap = {};
  504. let bills = await bill_model.model.find({
  505. projectID: projectID
  506. }, '-_id'); //取出所有清单
  507. let project = await projectsModel.findOne({
  508. ID: projectID
  509. });
  510. if (!project) throw new Error(`找不到项目:${projectID}`);
  511. let projectName = project.name;
  512. let author = ''; //编制人
  513. let auditor = ''; //审核人
  514. let compilationScope = ''; //编制范围
  515. let engineering = ''; //养护类别
  516. let progressiveType = 0; //累进计算类型
  517. let progressiveInterval = null;
  518. if (project.property && project.property.projectFeature) {
  519. for (let f of project.property.projectFeature) {
  520. if (f.key == 'author') author = f.value;
  521. if (f.key == 'auditor') auditor = f.value;
  522. if (f.key == 'compilationScope') compilationScope = f.value;
  523. if (f.key == 'engineering') engineering = f.value;
  524. }
  525. if (project.property.progressiveType) progressiveType = project.property.progressiveType;
  526. progressiveInterval = project.property.progressiveInterval;
  527. }
  528. for (let b of bills) {
  529. let commonFee = _.find(b._doc.fees, {
  530. "fieldName": "common"
  531. });
  532. let prices = {};
  533. let quantityMap = {};
  534. let unitPrices = {};
  535. let rationCommons = {};
  536. let baseProgressiveFees = {};
  537. let rationFee = _.find(b._doc.fees, {
  538. "fieldName": "rationCommon"
  539. });
  540. if (commonFee && commonFee.tenderTotalFee) prices[projectName] = commonFee.tenderTotalFee;
  541. if (commonFee && commonFee.tenderUnitFee) unitPrices[projectName] = commonFee.tenderUnitFee;
  542. if (rationFee && rationFee.tenderTotalFee) rationCommons[projectName] = rationFee.tenderTotalFee;
  543. baseProgressiveFees[projectName] = b.baseProgressiveFee;
  544. quantityMap[projectName] = b.quantity;
  545. let flagIndex = _.find(b._doc.flags, {
  546. 'fieldName': 'fixed'
  547. });
  548. let doc = {
  549. ID: b.ID,
  550. name: b.name,
  551. code: b.code,
  552. unit: b.unit,
  553. projectID: b.projectID,
  554. ParentID: b.ParentID,
  555. NextSiblingID: b.NextSiblingID,
  556. unitPrices: unitPrices,
  557. quantity: b.quantity,
  558. prices: prices,
  559. rationCommons: rationCommons,
  560. quantityMap: quantityMap,
  561. flag: flagIndex ? flagIndex.flag : -99,
  562. remark: b.remark,
  563. calcBase: b.calcBase,
  564. baseProgressiveFees: baseProgressiveFees
  565. }; //选取有用字段
  566. if (b.ParentID == -1) roots.push(doc);
  567. parentMap[b.ParentID] ? parentMap[b.ParentID].push(doc) : parentMap[b.ParentID] = [doc];
  568. } //设置子节点
  569. for (let r of roots) {
  570. setChildren(r, parentMap);
  571. }
  572. roots = sortChildren(roots);
  573. return {
  574. name: projectName,
  575. roots: roots,
  576. author: author,
  577. auditor: auditor,
  578. compilationScope: compilationScope,
  579. ParentID: project.ParentID,
  580. prjTypeName: engineering,
  581. progressiveType: progressiveType,
  582. progressiveInterval: progressiveInterval
  583. }
  584. }
  585. function setChildren(bill, parentMap) {
  586. let children = parentMap[bill.ID];
  587. if (children) {
  588. for (let c of children) {
  589. setChildren(c, parentMap);
  590. }
  591. bill.children = children;
  592. } else {
  593. bill.children = [];
  594. }
  595. }
  596. function sortChildren(lists) {
  597. let IDMap = {},
  598. nextMap = {},
  599. firstNode = null,
  600. newList = [];
  601. for (let l of lists) {
  602. if (l.children && l.children.length > 0) l.children = sortChildren(l.children); //递规排序
  603. IDMap[l.ID] = l;
  604. if (l.NextSiblingID != -1) nextMap[l.NextSiblingID] = l;
  605. }
  606. for (let t of lists) {
  607. if (!nextMap[t.ID]) { //如果在下一节点映射没找到,则是第一个节点
  608. firstNode = t;
  609. break;
  610. }
  611. }
  612. if (firstNode) {
  613. newList.push(firstNode);
  614. delete IDMap[firstNode.ID];
  615. setNext(firstNode, newList);
  616. }
  617. //容错处理,如果链断了的情况,直接添加到后面
  618. for (let key in IDMap) {
  619. if (IDMap[key]) newList.push(IDMap[key])
  620. }
  621. return newList;
  622. function setNext(node, array) {
  623. if (node.NextSiblingID != -1) {
  624. let next = IDMap[node.NextSiblingID];
  625. if (next) {
  626. array.push(next);
  627. delete IDMap[next.ID];
  628. setNext(next, array);
  629. }
  630. }
  631. }
  632. }
  633. async function getGLJSummayDatas(projectIDs) {
  634. let projects = [];
  635. let names = [];
  636. let prjTypeNames = [];
  637. let compilationScopes = [];
  638. try {
  639. for (let ID of projectIDs) {
  640. projects.push(await getProjectData(ID));
  641. }
  642. if (projects.length == 0) {
  643. return [];
  644. }
  645. let mp = projects[0];
  646. for (let p of projects) {
  647. names.push(p.name);
  648. prjTypeNames.push(p.prjTypeName);
  649. p.gljList = await getProjectGLJData(p.ID, p.unitPriceFileId, mp.property);
  650. compilationScopes.push(p.compilationScope);
  651. }
  652. let mList = mergeGLJ(mp, projects, names, prjTypeNames);
  653. mList = gljUtil.sortProjectGLJ(mList, _);
  654. let summaryGLJDatas = getSummaryGLJDatas(mList, mp.property.decimal, names, prjTypeNames, compilationScopes);
  655. let parentProject = await projectsModel.findOne({
  656. ID: mp.ParentID
  657. });
  658. let result = {
  659. prj: {},
  660. SummaryGljAudit: {
  661. "name": parentProject ? parentProject.name : "",
  662. "编制": mp.author,
  663. "复核": mp.auditor,
  664. "编制范围": mp.compilationScope
  665. },
  666. SummaryGljAuditDetail: summaryGLJDatas
  667. };
  668. return result;
  669. } catch (e) {
  670. console.log(e);
  671. }
  672. }
  673. function getSummaryGLJDatas(gljList, decimal, nameList, prjTypeNames, compilationScopes) {
  674. let datas = [],
  675. qdecimal = decimal.glj.quantity,
  676. process = decimal.process;
  677. for (let tem of gljList) {
  678. let d = {
  679. code: tem.code,
  680. name: tem.name,
  681. type: tem.type,
  682. unit: tem.unit,
  683. specs: tem.specs,
  684. marketPrice: tem.marketPrice,
  685. prjNames: nameList,
  686. prjTypeNames: prjTypeNames,
  687. quantityList: [],
  688. '编制范围明细': compilationScopes
  689. };
  690. let totalQuantity = 0;
  691. for (let n of nameList) {
  692. let q = tem.quantityMap[n] ? scMathUtil.roundForObj(tem.quantityMap[n], qdecimal) : 0;
  693. totalQuantity = scMathUtil.roundForObj(q + totalQuantity, process);
  694. d.quantityList.push(q);
  695. }
  696. d.totalQuantity = scMathUtil.roundForObj(totalQuantity, qdecimal);
  697. datas.push(d);
  698. }
  699. return datas;
  700. }
  701. function mergeGLJ(mp, projects) {
  702. let gljMap = {},
  703. gljList = [];
  704. for (let g of mp.gljList) {
  705. g.quantityMap = {};
  706. g.quantityMap[mp.name] = g.tenderQuantity;
  707. gljMap[gljUtil.getIndex(g)] = g;
  708. gljList.push(g);
  709. }
  710. for (let i = 1; i < projects.length; i++) {
  711. let temList = projects[i].gljList;
  712. for (let t of temList) {
  713. t.quantityMap = {};
  714. t.quantityMap[projects[i].name] = t.tenderQuantity;
  715. //这里除了5个属性相同判断为同一个之外,还要判断市场价相同,才认为是同一个工料机
  716. let connect_key = gljUtil.getIndex(t);
  717. let g = gljMap[connect_key];
  718. if (g && g.marketPrice == t.marketPrice) {
  719. g.quantityMap[projects[i].name] = t.tenderQuantity;
  720. } else {
  721. gljMap[connect_key] = t;
  722. gljList.push(t);
  723. }
  724. }
  725. }
  726. return gljList;
  727. }
  728. async function getProjectGLJData(projectID, unitPriceFileId, property) {
  729. //取项目工料机数据
  730. let projectGLJDatas = await getProjectGLJPrice(projectID, unitPriceFileId, property);
  731. await calcProjectGLJQuantity(projectID, projectGLJDatas, property);
  732. _.remove(projectGLJDatas.gljList, {
  733. 'quantity': 0
  734. });
  735. return projectGLJDatas.gljList;
  736. }
  737. async function getProjectData(projectID) {
  738. let project = await projectsModel.findOne({
  739. ID: projectID
  740. });
  741. if (!project) throw new Error(`找不到项目:${projectID}`);
  742. let projectName = project.name;
  743. let author = ''; //编制人
  744. let auditor = ''; //审核人
  745. let compilationScope = ''; //编制范围
  746. let engineering = ''; //养护类别
  747. if (project.property && project.property.projectFeature) {
  748. for (let f of project.property.projectFeature) {
  749. if (f.key == 'author') author = f.value;
  750. if (f.key == 'auditor') auditor = f.value;
  751. if (f.key == 'compilationScope') compilationScope = f.value;
  752. if (f.key == 'engineering') engineering = f.value;
  753. }
  754. }
  755. if (!(project.property && project.property.unitPriceFile)) throw new Error(`找不到单价文件:${projectID}`);
  756. let unitPriceFileId = project.property.unitPriceFile.id;
  757. return {
  758. ID: projectID,
  759. name: projectName,
  760. author: author,
  761. auditor: auditor,
  762. compilationScope: compilationScope,
  763. ParentID: project.ParentID,
  764. prjTypeName: engineering,
  765. property: project.property,
  766. unitPriceFileId: unitPriceFileId
  767. }
  768. }
  769. async function getProjectGLJPrice(projectID, unitPriceFileId, property) {
  770. //取项目工料机数据
  771. let calcOptions = property.calcOptions;
  772. let decimalObj = property.decimal;
  773. let labourCoeDatas = []; //取调整价才需要用到
  774. let gljListModel = new GLJListModel();
  775. let [gljList, mixRatioConnectData, mixRatioMap, unitPriceMap] = await gljListModel.getListByProjectId(projectID, unitPriceFileId);
  776. gljList = JSON.parse(JSON.stringify(gljList));
  777. for (let glj of gljList) {
  778. let tenderCoe = gljUtil.getTenderPriceCoe(glj, property);
  779. let result = gljUtil.getGLJPrice(glj, {
  780. gljList: gljList
  781. }, calcOptions, labourCoeDatas, decimalObj, false,tenderCoe,true);
  782. glj.marketPrice = result.marketPrice;
  783. glj.basePrice = result.basePrice;
  784. }
  785. return {
  786. gljList: gljList,
  787. mixRatioMap: mixRatioMap
  788. };
  789. }
  790. async function calcProjectGLJQuantity(projectID, projectGLJDatas, property) {
  791. let q_decimal = property.decimal.glj.quantity;
  792. let rationGLJDatas = await ration_glj_model.find({
  793. 'projectID': projectID
  794. });
  795. let rationDatas = await ration_model.model.find({
  796. 'projectID': projectID
  797. });
  798. gljUtil.calcProjectGLJQuantity(projectGLJDatas, rationGLJDatas, rationDatas, [], q_decimal)
  799. }