project_facade.js 29 KB

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