project_facade.js 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808
  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 calcUtil = require('../../../public/calculate_util')
  34. const { fixedFlag } = require('../../../public/common_constants');
  35. import GLJListModel from "../../glj/models/glj_list_model";
  36. const projectDao = require('../../pm/models/project_model').project;
  37. async function calcInstallationFee(data) {
  38. let result={};
  39. let projectGLJList = [];
  40. let billTasks = generateTasks(data.bills,data.useID);
  41. let rationTasks = generateTasks(data.ration,data.useID);
  42. if(billTasks.length>0){
  43. await bill_model.model.bulkWrite(billTasks);
  44. }
  45. console.log(rationTasks);
  46. if(rationTasks.length>0){
  47. await ration_model.model.bulkWrite(rationTasks);
  48. }
  49. //如果删除定额,需要删除对应的工料机
  50. if(data.ration.delete.length>0){
  51. let rationIDS = _.map(data.ration.delete,'ID');
  52. await ration_glj_model.deleteMany({projectID: data.ration.delete[0].projectID, rationID: {"$in": rationIDS}});//删除定额工料机
  53. }
  54. let rationGLJTasks = [];
  55. let updateList = [];
  56. if(data.ration.update.length>0){//如果有需要更新的定额工料机
  57. for(let ur of data.ration.update){
  58. for(let g of ur.glj){
  59. let gTasks = {
  60. updateOne:{
  61. filter:{
  62. ID:g.ID,
  63. projectID:g.projectID
  64. },
  65. update :{
  66. quantity:g.quantity,
  67. rationItemQuantity:g.rationItemQuantity
  68. }
  69. }
  70. };
  71. rationGLJTasks.push(gTasks);
  72. updateList.push(g);
  73. }
  74. }
  75. }
  76. if(rationGLJTasks.length>0){
  77. await ration_glj_model.bulkWrite(rationGLJTasks);
  78. }
  79. let newGljList = [];
  80. if(data.ration.add.length>0){//新增的安装子目要增加对应的工料机
  81. for(let nr of data.ration.add){
  82. for(let tkey in nr.glj){
  83. let [newRecode,projectGLJ] = await addInstallationGLJ(nr.glj[tkey]);
  84. newGljList.push(newRecode);
  85. }
  86. }
  87. }
  88. if(newGljList.length>0){
  89. await ration_glj_model.insertMany(newGljList);
  90. }
  91. result.update = updateList;
  92. result.add = newGljList;
  93. return result;
  94. }
  95. async function addInstallationGLJ(glj) {
  96. glj.ID = uuidV1();
  97. let [info,projectGLJ ] = await ration_glj_facade.getInfoFromProjectGLJ(glj);
  98. let newRecode = ration_glj_facade.createNewRecord(info);
  99. return [newRecode,projectGLJ];
  100. }
  101. function generateTasks(data,userID) {
  102. let tasks=[];
  103. let deleteInfo={deleted: true, deleteDateTime: new Date(), deleteBy: userID};
  104. if(data.delete && data.delete.length > 0){
  105. for(let bd of data.delete){
  106. //原先是假删除,现在改成真删除
  107. let task = {
  108. deleteOne:{
  109. filter:{
  110. ID:bd.ID,
  111. projectID:bd.projectID
  112. }
  113. }
  114. };
  115. /* let task={
  116. updateOne:{
  117. filter:{
  118. ID:bd.ID,
  119. projectID:bd.projectID
  120. },
  121. update :{
  122. deleteInfo:deleteInfo
  123. }
  124. }
  125. };*/
  126. tasks.push(task);
  127. }
  128. }
  129. if(data.add && data.add.length > 0){
  130. for(let n_data of data.add){
  131. let task = {
  132. insertOne :{
  133. document:n_data
  134. }
  135. };
  136. tasks.push(task);
  137. }
  138. }
  139. return tasks;
  140. }
  141. async function updateNodes(datas){
  142. let nodeGroups = _.groupBy(datas,'type');
  143. let rationTasks = [];
  144. let billTasks = [];
  145. let rationGLJTasks = [];
  146. let projectGLJTasks = [];
  147. let projectTasks = [];
  148. let rationTemplateTasks = [];
  149. let asyncTasks = [];
  150. for(let type in nodeGroups){
  151. for(let node of nodeGroups[type]){
  152. if(type == projectConsts.BILLS){
  153. billTasks.push(getTask(node));
  154. }else if(type == projectConsts.RATION){
  155. rationTasks.push(getTask(node));
  156. }else if(type == projectConsts.RATION_GLJ){
  157. rationGLJTasks.push(getTask(node));
  158. }else if(type == projectConsts.PROJECTGLJ){
  159. projectGLJTasks.push(getTask(node,'id'));
  160. }else if(type == projectConsts.PROJECT){
  161. projectTasks.push(getTask(node));
  162. }else if(type == projectConsts.RATION_TEMPLATE){
  163. rationTemplateTasks.push(getTask(node))
  164. }
  165. }
  166. }
  167. rationTasks.length>0?asyncTasks.push(ration_model.model.bulkWrite(rationTasks)):'';
  168. billTasks.length>0?asyncTasks.push(bill_model.model.bulkWrite(billTasks)):"";
  169. rationGLJTasks.length>0?asyncTasks.push(ration_glj_model.bulkWrite(rationGLJTasks)):"";
  170. projectGLJTasks.length>0?asyncTasks.push(project_glj_model.bulkWrite(projectGLJTasks)):"";
  171. projectTasks.length>0?asyncTasks.push(projectsModel.bulkWrite(projectTasks)):"";
  172. rationTemplateTasks.length>0?asyncTasks.push(rationTemplateModel.bulkWrite(rationTemplateTasks)):"";
  173. return asyncTasks.length>0?await Promise.all(asyncTasks):"";
  174. function getTask(node,idFiled = 'ID') {
  175. let task={
  176. updateOne:{
  177. filter:{},
  178. update :_.cloneDeep(node.data)
  179. }
  180. };
  181. task.updateOne.filter[idFiled] = node.data[idFiled];//现在复制项目也重新生成一个新的ID了,所以ID是唯一的
  182. delete task.updateOne.update[idFiled];//防止误操作
  183. return task;
  184. }
  185. }
  186. /*function updateNodes(datas,callback) {
  187. let tasks = [];
  188. for(let node of datas){
  189. tasks.push(updateOne(node))
  190. }
  191. async_n.parallel(tasks, function(err, results) {
  192. if (!err){
  193. callback(0, '', results);
  194. }
  195. else{
  196. console.log(err);
  197. callback(1, 'save project failed'+err.message, null);
  198. }
  199. });
  200. function updateOne(node) {
  201. if(node.type == projectConsts.BILLS){
  202. return function (asCallback) {
  203. bill_model.model.findOneAndUpdate({projectID: node.data.projectID, ID: node.data.ID,deleteInfo: null}, node.data,{new: true}, asCallback);
  204. }
  205. }else if(node.type ==projectConsts.RATION){
  206. return function (asCallback) {
  207. ration_model.model.findOneAndUpdate({projectID: node.data.projectID, ID: node.data.ID,deleteInfo: null}, node.data,{new: true}, asCallback);
  208. }
  209. }
  210. }
  211. }*/
  212. //data = {feeRateID:111111,projectID:1245}; type = feeRate
  213. async function markUpdateProject(data,type) {
  214. let query = {deleteInfo:null};
  215. if(type=="feeRate"){//更改了费率
  216. query['property.feeFile.id'] = data.feeRateID;
  217. }
  218. if(type=="unitFile"){//更改了单价文件
  219. query['property.unitPriceFile.id'] = data.unitFileID;//unitPriceFile
  220. }
  221. let projects = await projectsModel.find(query);
  222. return await markProjectsToChange(projects,type,data.projectID,data.isInclude);
  223. }
  224. async function markProjectsToChange(projects,type,extProjectID,isInclude){
  225. let tasks=[];
  226. for(let p of projects){
  227. if(isInclude!= true ){
  228. if(extProjectID && p.ID===extProjectID) continue;//排除当前项目
  229. }
  230. tasks.push(generateMarkTask(type,p.ID));
  231. }
  232. return tasks.length>0 ? await projectsModel.bulkWrite(tasks):null;
  233. }
  234. async function removeProjectMark(projectID) {
  235. return await projectsModel.findOneAndUpdate({ID:projectID},{"$unset":{"changeMark":1}});
  236. }
  237. function generateMarkTask(value,projectID) {
  238. let task = {
  239. updateOne:{
  240. filter:{
  241. ID:projectID
  242. },
  243. update:{
  244. changeMark:value
  245. }
  246. }
  247. };
  248. return task
  249. }
  250. // {projectID: 5, propertyName: 'aaa', propertyValue: 1}
  251. function saveProperty(data, callback){
  252. let obj = {};
  253. let pn = 'property.' + data.propertyName;
  254. obj[pn] = data.propertyValue;
  255. projectsModel.update({"ID": data.projectID}, obj, function (err) {
  256. if (err) {
  257. logger.err(pn + ' save error: ' + err);
  258. callback(err, null)
  259. } else {
  260. logger.info(pn + ' saved.');
  261. callback('', null);
  262. }}
  263. );
  264. }
  265. async function getDefaultColSetting(libID){
  266. return await stdColSettingModel.findOne({ID: libID, deleted: false}, '-_id main_tree_col');
  267. }
  268. async function getBudgetSummayDatas(projectIDs,overWriteUrl){
  269. try {
  270. let projects = [];
  271. let names = [];
  272. let prjTypeNames = [];
  273. let compilationScopes = [];
  274. let decimal = null;
  275. let isProgressiveType = false;
  276. for(let ID of projectIDs){
  277. projects.push(await getBillsByProjectID(ID)) ;
  278. }
  279. if(projects.length == 0){
  280. return [];
  281. }
  282. let mp = projects[0];
  283. names.push(mp.name);
  284. prjTypeNames.push(mp.prjTypeName);
  285. compilationScopes.push(mp.compilationScope);
  286. if(projects.length == 1) decimal = await decimal_facade.getProjectDecimal(projectIDs[0]);//如果只有一个项目,则没走合并的那一步,decimal会为空,从面报错
  287. for(let i = 1;i<projects.length;i++){
  288. names.push(projects[i].name);
  289. prjTypeNames.push(projects[i].prjTypeName);
  290. compilationScopes.push(projects[i].compilationScope);
  291. decimal = await mergeProject(mp.roots,projects[i].roots);
  292. if(projects[i].progressiveType == 0) isProgressiveType = true;
  293. }
  294. let SummaryAuditDetail = getReportData(names,mp.roots,prjTypeNames,compilationScopes,decimal,isProgressiveType,mp.progressiveInterval,overWriteUrl);
  295. let parentProject = await projectsModel.findOne({ID:mp.ParentID});
  296. let result = {
  297. prj: {},
  298. SummaryAudit:{
  299. "name": parentProject?parentProject.name:"",
  300. "编制": mp.author,
  301. "复核": mp.auditor,
  302. "编制范围":mp.compilationScope
  303. },
  304. SummaryAuditDetail:SummaryAuditDetail
  305. };
  306. return result;
  307. }catch (e){
  308. console.log(e)
  309. }
  310. }
  311. function getReportData(nameList,items,prjTypeNames,compilationScopes,decimal,isProgressiveType,progressiveInterval,overWriteUrl) {
  312. let datas = [],totalItem = null;
  313. let overWrite = null;
  314. if(overWriteUrl && overWriteUrl!=""){
  315. overWrite = require("../../.."+overWriteUrl);
  316. }
  317. setChildrenDatas(items,datas);
  318. let totalExp = totalItem.calcBase;
  319. if(isProgressiveType&&progressiveInterval){
  320. for(let t of datas){
  321. totalExp = totalExp.replace(t.ID,t.billsTtlPrice+"");
  322. }
  323. totalExp = totalExp.replace(/@/g,"");
  324. let nTotal = eval(totalExp);
  325. totalItem.billsTtlPrice = scMathUtil.roundForObj(nTotal,decimal.bills.totalPrice);
  326. }
  327. for(let d of datas){
  328. if(d.billsTtlPrice&&totalItem.billsTtlPrice){
  329. d['各项费用比例'] = scMathUtil.roundForObj(d.billsTtlPrice/totalItem.billsTtlPrice * 100,2)
  330. }
  331. d['prjNames'] = nameList;
  332. d['prjTypeNames'] = prjTypeNames;
  333. d['编制范围明细'] = compilationScopes;
  334. }
  335. return datas;
  336. function setChildrenDatas(children,arr,level = 0,rootFlag) {
  337. let temTotalPrice = 0;
  338. for(let c of children){
  339. if(level == 0) rootFlag = c.flag;//取最顶层节点的固定清单类别
  340. let tbill = getBillDatas(c,level,rootFlag);
  341. arr.push(tbill);
  342. let sumChildren = setChildrenDatas(c.children,arr,level+1,rootFlag);
  343. if(isProgressiveType && progressiveInterval && rootFlag == fixedFlag.MAINTENANCE_EXPENSES){//如果要累进的,父节点要重新汇总
  344. if(level>0) temTotalPrice = scMathUtil.roundForObj(tbill.billsTtlPrice + temTotalPrice,decimal.bills.totalPrice);
  345. if(c.children.length > 0) tbill.billsTtlPrice = sumChildren;
  346. }
  347. }
  348. return temTotalPrice;
  349. }
  350. function getBillDatas(bills,level,rootFlag) {
  351. let tem = {
  352. ID:bills.ID,
  353. billsName:bills.name,
  354. billsCode:bills.code,
  355. billsUnit:bills.unit,
  356. billsTtlAmt:bills.quantity,
  357. billsPrices:[],
  358. billsUnitPrices:[],
  359. rationCommons:[],
  360. billsAmounts:[],
  361. '技术经济指标':[],
  362. billsLevel:level,
  363. calcBase:bills.calcBase,
  364. billsMemos:bills.remark
  365. };
  366. let total = 0;
  367. let rationTotal =0;
  368. let baseTotal = 0;
  369. for(let n of nameList){
  370. let p = 0;//金额
  371. let up =0;//单价
  372. let ra = 0;//定额建安费
  373. let bt = 0; //累计相关
  374. if(bills.unitPrices[n]) up = scMathUtil.roundForObj(bills.unitPrices[n],decimal.bills.unitPrice);
  375. tem.billsUnitPrices.push(up);
  376. if(bills.prices[n]){
  377. p = scMathUtil.roundForObj(bills.prices[n],decimal.bills.totalPrice);
  378. total = scMathUtil.roundForObj(p+total,decimal.process);
  379. }
  380. tem.billsPrices.push(p);
  381. if(bills.rationCommons[n]){
  382. ra = scMathUtil.roundForObj(bills.rationCommons[n],decimal.bills.totalPrice);
  383. rationTotal = scMathUtil.roundForObj(ra+rationTotal,decimal.process);
  384. }
  385. tem.rationCommons.push(ra);
  386. if(bills.quantityMap[n] && parseFloat(bills.quantityMap[n]) !== 0){
  387. tem.billsAmounts.push(bills.quantityMap[n]);
  388. tem['技术经济指标'].push(scMathUtil.roundForObj(p/bills.quantityMap[n],2));
  389. }else {
  390. tem.billsAmounts.push(0);
  391. tem['技术经济指标'].push(scMathUtil.roundForObj(p,2));
  392. }
  393. if(rootFlag == fixedFlag.MAINTENANCE_EXPENSES){//如果是第三部分下的子清单,才要计算累计的相关信息
  394. if(bills.baseProgressiveFees[n]){
  395. bt = scMathUtil.roundForObj(bills.baseProgressiveFees[n],decimal.bills.totalPrice);
  396. baseTotal = scMathUtil.roundForObj(bt+baseTotal,decimal.process);
  397. }
  398. }
  399. }
  400. tem.billsTtlPrice = scMathUtil.roundForObj(total,decimal.bills.totalPrice);
  401. if(progressiveInterval && isProgressiveType && rootFlag == fixedFlag.MAINTENANCE_EXPENSES){
  402. let baseArr = calcUtil.getProgressive(bills.calcBase,overWrite?overWrite.progression:undefined);
  403. if(baseArr.length > 0){
  404. let calcTotal = calcUtil.getProgressiveFee(baseTotal,baseArr[0],progressiveInterval,decimal.bills.totalPrice,overWrite?overWrite.deficiency:undefined);
  405. tem.billsTtlPrice = calcTotal;
  406. let rate = scMathUtil.roundForObj(calcTotal * 100/baseTotal,decimal.feeRate);
  407. tem.billsMemos = "费率:"+rate+"%";
  408. //“费率:n%”,n为汇总后重算的金额/汇总后的基数
  409. }
  410. }
  411. tem.rationTotal = scMathUtil.roundForObj(rationTotal,decimal.bills.totalPrice);//定额总建安费
  412. tem['技术经济综合指标'] = (tem.billsTtlAmt && parseFloat(tem.billsTtlAmt) !== 0)?scMathUtil.roundForObj(tem.billsTtlPrice/tem.billsTtlAmt,2):scMathUtil.roundForObj(tem.billsTtlPrice,2);
  413. if(bills.flag == fixedFlag.TOTAL_COST) totalItem = tem;
  414. return tem
  415. }
  416. }
  417. async function mergeProject(main,sub) {//合并两个项目
  418. let decimal = await decimal_facade.getProjectDecimal(main[0].projectID);
  419. let project = await projectsModel.findOne({ID:main[0].projectID});
  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=[],parentMap={};
  513. let bills = await bill_model.model.find({projectID: projectID}, '-_id');//取出所有清单
  514. let project = await projectsModel.findOne({ID:projectID});
  515. if(!project) throw new Error(`找不到项目:${projectID}`);
  516. let projectName = project.name;
  517. let author='';//编制人
  518. let auditor='';//审核人
  519. let compilationScope='';//编制范围
  520. let engineering='';//养护类别
  521. let progressiveType = 0;//累进计算类型
  522. let progressiveInterval = null;
  523. if(project.property&&project.property.projectFeature){
  524. for(let f of project.property.projectFeature){
  525. if(f.key == 'author') author = f.value;
  526. if(f.key == 'auditor') auditor = f.value;
  527. if(f.key =='compilationScope') compilationScope = f.value;
  528. if(f.key == 'engineering') engineering = f.value;
  529. }
  530. if(project.property.progressiveType) progressiveType = project.property.progressiveType;
  531. progressiveInterval = project.property.progressiveInterval;
  532. }
  533. for(let b of bills){
  534. let commonFee =_.find(b._doc.fees,{"fieldName":"common"});
  535. let prices = {};
  536. let quantityMap={};
  537. let unitPrices ={};
  538. let rationCommons={};
  539. let baseProgressiveFees ={};
  540. let rationFee = _.find(b._doc.fees,{"fieldName":"rationCommon"});
  541. if(commonFee&&commonFee.totalFee) prices[projectName] = commonFee.totalFee;
  542. if(commonFee&&commonFee.unitFee) unitPrices[projectName] = commonFee.unitFee;
  543. if(rationFee&&rationFee.totalFee) rationCommons[projectName] = rationFee.totalFee;
  544. baseProgressiveFees[projectName] = b.baseProgressiveFee;
  545. quantityMap[projectName] = b.quantity;
  546. let flagIndex = _.find(b._doc.flags,{'fieldName':'fixed'});
  547. 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,calcBase:b.calcBase,baseProgressiveFees:baseProgressiveFees};//选取有用字段
  548. if(b.ParentID == -1) roots.push(doc);
  549. parentMap[b.ParentID]?parentMap[b.ParentID].push(doc):parentMap[b.ParentID]=[doc];
  550. }//设置子节点
  551. for(let r of roots){
  552. setChildren(r,parentMap,1);
  553. }
  554. roots = sortChildren(roots);
  555. return {name:projectName,roots:roots,author:author,auditor:auditor,compilationScope:compilationScope,ParentID:project.ParentID,prjTypeName:engineering,progressiveType:progressiveType,progressiveInterval:progressiveInterval}
  556. }
  557. function setChildren(bill,parentMap,level) {
  558. let children = parentMap[bill.ID];
  559. if(children){
  560. for(let c of children){
  561. setChildren(c,parentMap,level+1)
  562. }
  563. bill.children = children;
  564. }else {
  565. bill.children = [];
  566. }
  567. }
  568. function sortChildren(lists) {
  569. let IDMap ={},nextMap = {}, firstNode = null,newList=[];
  570. for(let l of lists){
  571. if(l.children&&l.children.length > 0) l.children = sortChildren(l.children);//递规排序
  572. IDMap[l.ID] = l;
  573. if(l.NextSiblingID!=-1) nextMap[l.NextSiblingID] = l;
  574. }
  575. for(let t of lists){
  576. if(!nextMap[t.ID]){ //如果在下一节点映射没找到,则是第一个节点
  577. firstNode = t;
  578. break;
  579. }
  580. }
  581. if(firstNode){
  582. newList.push(firstNode);
  583. delete IDMap[firstNode.ID];
  584. setNext(firstNode,newList);
  585. }
  586. //容错处理,如果链断了的情况,直接添加到后面
  587. for(let key in IDMap){
  588. if(IDMap[key]) newList.push(IDMap[key])
  589. }
  590. return newList;
  591. function setNext(node,array) {
  592. if(node.NextSiblingID != -1){
  593. let next = IDMap[node.NextSiblingID];
  594. if(next){
  595. array.push(next);
  596. delete IDMap[next.ID];
  597. setNext(next,array);
  598. }
  599. }
  600. }
  601. }
  602. async function getGLJSummayDatas(projectIDs) {
  603. let projects = [];
  604. let names = [];
  605. let prjTypeNames = [];
  606. let compilationScopes = [];
  607. try {
  608. for(let ID of projectIDs){
  609. projects.push(await getProjectData(ID)) ;
  610. }
  611. if(projects.length == 0){
  612. return [];
  613. }
  614. let mp = projects[0];
  615. for(let p of projects){
  616. names.push(p.name);
  617. prjTypeNames.push(p.prjTypeName);
  618. p.gljList = await getProjectGLJData(p.ID,p.unitPriceFileId,mp.property);
  619. compilationScopes.push(p.compilationScope);
  620. }
  621. let mList = mergeGLJ(mp,projects,names,prjTypeNames);
  622. mList = gljUtil.sortProjectGLJ(mList,_);
  623. let summaryGLJDatas = getSummaryGLJDatas(mList,mp.property.decimal,names,prjTypeNames,compilationScopes);
  624. let parentProject = await projectsModel.findOne({ID:mp.ParentID});
  625. let result = {
  626. prj: {},
  627. SummaryGljAudit:{
  628. "name": parentProject?parentProject.name:"",
  629. "编制": mp.author,
  630. "复核": mp.auditor,
  631. "编制范围":mp.compilationScope
  632. },
  633. SummaryGljAuditDetail:summaryGLJDatas
  634. };
  635. return result;
  636. }catch (e){
  637. console.log(e);
  638. }
  639. }
  640. function getSummaryGLJDatas(gljList,decimal,nameList,prjTypeNames,compilationScopes) {
  641. let datas = [],qdecimal = decimal.glj.quantity,process = decimal.process;
  642. for(let tem of gljList){
  643. let d = {
  644. code:tem.code,
  645. name:tem.name,
  646. type:tem.type,
  647. unit:tem.unit,
  648. specs:tem.specs,
  649. marketPrice:tem.marketPrice,
  650. prjNames:nameList,
  651. prjTypeNames:prjTypeNames,
  652. quantityList:[],
  653. '编制范围明细':compilationScopes
  654. };
  655. let totalQuantity = 0;
  656. for(let n of nameList){
  657. let q = tem.quantityMap[n]?scMathUtil.roundForObj(tem.quantityMap[n],qdecimal):0;
  658. totalQuantity = scMathUtil.roundForObj(q+totalQuantity,process);
  659. d.quantityList.push(q);
  660. }
  661. d.totalQuantity = scMathUtil.roundForObj(totalQuantity,qdecimal);
  662. datas.push(d);
  663. }
  664. return datas;
  665. }
  666. function mergeGLJ(mp,projects) {
  667. let gljMap = {},gljList=[];
  668. for(let g of mp.gljList){
  669. g.quantityMap={};
  670. g.quantityMap[mp.name] = g.quantity;
  671. gljMap[gljUtil.getIndex(g)] = g;
  672. gljList.push(g);
  673. }
  674. for(let i = 1;i<projects.length;i++){
  675. let temList = projects[i].gljList;
  676. for(let t of temList){
  677. t.quantityMap={};
  678. t.quantityMap[projects[i].name] = t.quantity;
  679. //这里除了5个属性相同判断为同一个之外,还要判断市场价相同,才认为是同一个工料机
  680. let connect_key = gljUtil.getIndex(t);
  681. let g = gljMap[connect_key];
  682. if(g&&g.marketPrice == t.marketPrice){
  683. g.quantityMap[projects[i].name] = t.quantity;
  684. }else {
  685. gljMap[connect_key] = t;
  686. gljList.push(t);
  687. }
  688. }
  689. }
  690. return gljList;
  691. }
  692. async function getProjectGLJData(projectID,unitPriceFileId,property){
  693. //取项目工料机数据
  694. let projectGLJDatas = await getProjectGLJPrice(projectID,unitPriceFileId,property);
  695. await calcProjectGLJQuantity(projectID,projectGLJDatas,property);
  696. _.remove(projectGLJDatas.gljList,{'quantity':0});
  697. return projectGLJDatas.gljList;
  698. }
  699. async function getProjectData(projectID){
  700. let project = await projectsModel.findOne({ID:projectID});
  701. if(!project) throw new Error(`找不到项目:${projectID}`);
  702. let projectName = project.name;
  703. let author='';//编制人
  704. let auditor='';//审核人
  705. let compilationScope='';//编制范围
  706. let engineering='';//养护类别
  707. if(project.property&&project.property.projectFeature){
  708. for(let f of project.property.projectFeature){
  709. if(f.key == 'author') author = f.value;
  710. if(f.key == 'auditor') auditor = f.value;
  711. if(f.key =='compilationScope') compilationScope = f.value;
  712. if(f.key == 'engineering') engineering = f.value;
  713. }
  714. }
  715. if(!(project.property&&project.property.unitPriceFile)) throw new Error(`找不到单价文件:${projectID}`);
  716. let unitPriceFileId = project.property.unitPriceFile.id;
  717. return {ID:projectID,name:projectName,author:author,auditor:auditor,compilationScope:compilationScope,ParentID:project.ParentID,prjTypeName:engineering,property:project.property,unitPriceFileId:unitPriceFileId}
  718. }
  719. async function getProjectGLJPrice(projectID,unitPriceFileId,property){
  720. //取项目工料机数据
  721. let calcOptions=property.calcOptions;
  722. let decimalObj = property.decimal;
  723. let labourCoeDatas = [];//取调整价才需要用到
  724. let gljListModel = new GLJListModel();
  725. let [gljList, mixRatioConnectData,mixRatioMap,unitPriceMap] = await gljListModel.getListByProjectId(projectID, unitPriceFileId);
  726. gljList = JSON.parse(JSON.stringify(gljList));
  727. for(let glj of gljList){
  728. let result = gljUtil.getGLJPrice(glj,{gljList:gljList},calcOptions,labourCoeDatas,decimalObj,false,_,scMathUtil);
  729. glj.marketPrice = result.marketPrice;
  730. glj.basePrice = result.basePrice;
  731. }
  732. return {gljList:gljList,mixRatioMap:mixRatioMap};
  733. }
  734. async function calcProjectGLJQuantity(projectID,projectGLJDatas,property){
  735. let q_decimal = property.decimal.glj.quantity;
  736. let rationGLJDatas = await ration_glj_model.find({'projectID':projectID});
  737. let rationDatas = await ration_model.model.find({'projectID':projectID});
  738. gljUtil.calcProjectGLJQuantity(projectGLJDatas,rationGLJDatas,rationDatas,[],q_decimal)
  739. }