project_facade.js 27 KB

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