project_facade.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
  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. import fixedFlag from '../../common/const/bills_fixed';
  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. billsAmounts:[],
  335. '技术经济指标':[],
  336. billsLevel:level,
  337. billsMemos:bills.remark
  338. };
  339. let total = 0;
  340. for(let n of nameList){
  341. let p = 0;//金额
  342. let up =0;//单价
  343. if(bills.unitPrices[n]) up = scMathUtil.roundForObj(bills.unitPrices[n],decimal.bills.unitPrice);
  344. tem.billsUnitPrices.push(up);
  345. if(bills.prices[n]){
  346. p = scMathUtil.roundForObj(bills.prices[n],decimal.bills.totalPrice);
  347. total = scMathUtil.roundForObj(p+total,decimal.process);
  348. }
  349. tem.billsPrices.push(p);
  350. if(bills.quantityMap[n] && parseFloat(bills.quantityMap[n]) !== 0){
  351. tem.billsAmounts.push(bills.quantityMap[n]);
  352. tem['技术经济指标'].push(scMathUtil.roundForObj(p/bills.quantityMap[n],2));
  353. }else {
  354. tem.billsAmounts.push(0);
  355. tem['技术经济指标'].push(scMathUtil.roundForObj(p,2));
  356. }
  357. }
  358. tem.billsTtlPrice = scMathUtil.roundForObj(total,decimal.bills.totalPrice);
  359. tem['技术经济综合指标'] = (tem.billsTtlAmt && parseFloat(tem.billsTtlAmt) !== 0)?scMathUtil.roundForObj(tem.billsTtlPrice/tem.billsTtlAmt,2):scMathUtil.roundForObj(tem.billsTtlPrice,2);
  360. if(bills.flag == fixedFlag.TOTAL_COST) totalItem = tem;
  361. return tem
  362. }
  363. }
  364. async function mergeProject(main,sub) {//合并两个项目
  365. let decimal = await decimal_facade.getProjectDecimal(main[0].projectID);
  366. let project = await projectsModel.findOne({ID:main[0].projectID});
  367. let notMatchList = [];
  368. for(let s of sub){
  369. //先找有没有相同的大项费用
  370. let same = findTheSameItem(main,s);
  371. same?await mergeItem(same,s,decimal,project._doc):notMatchList.push(s);//如果找到,则合并,找不到就放在未匹配表
  372. }
  373. for(let n of notMatchList){
  374. main.push(n);
  375. }
  376. return decimal;
  377. }
  378. async function mergeItem(a,b,decimal,project) {
  379. let bqDecimal = await decimal_facade.getBillsQuantityDecimal(a.projectID,a.unit,project);
  380. a.quantity = a.quantity?scMathUtil.roundForObj(a.quantity,bqDecimal):0;
  381. b.quantity = b.quantity?scMathUtil.roundForObj(b.quantity,bqDecimal):0;
  382. a.quantity = scMathUtil.roundForObj(a.quantity+b.quantity,decimal.process);
  383. for(let name in b.prices){
  384. a.prices[name] = b.prices[name];
  385. a.quantityMap[name] = b.quantityMap[name];
  386. a.unitPrices[name]=b.unitPrices[name];
  387. }
  388. for(let name in a.quantityMap){
  389. a.quantityMap[name] = a.quantityMap[name]?scMathUtil.roundForObj(a.quantityMap[name],bqDecimal):0;
  390. }
  391. await mergeChildren(a,b,decimal,project);
  392. }
  393. async function mergeChildren(a,b,decimal,project) {
  394. let notMatchList = [];
  395. if(a.children.length > 0 && b.children.length ==0){
  396. return;
  397. }else if(a.children.length == 0 && b.children.length > 0){
  398. a.children = b.children;
  399. return;
  400. }
  401. //=============剩下的是两者都有的情况
  402. for(let s of b.children){
  403. let same = findTheSameItem(a.children,s);
  404. same?await mergeItem(same,s,decimal,project):notMatchList.push(s);//如果找到,则合并,找不到就放在未匹配表
  405. }
  406. for(let n of notMatchList){
  407. let match = false;//符合插入标记
  408. //对于未匹配的子项,如果是固定清单:第100章至700章清单的子项,要匹配名字中的数字来做排充
  409. if(a.flag == fixedFlag.ONE_SEVEN_BILLS){
  410. for(let i = 0;i< a.children.length;i++){
  411. let m_name = a.children[i].name.replace(/[^0-9]/ig,"");
  412. let s_name = n.name.replace(/[^0-9]/ig,"");
  413. m_name = parseFloat(m_name);
  414. s_name = parseFloat(s_name);
  415. if(m_name&&s_name){
  416. if(m_name == s_name){
  417. await mergeItem(a.children[i],n,project);
  418. match = true;
  419. break;
  420. }
  421. if(m_name > s_name){//主节点名字中的数字大于被插节点,则被插节点放在主节点前面
  422. a.children.splice(i,0,n);
  423. match = true;
  424. break;
  425. }
  426. }
  427. }
  428. }else {//其它的子项按编号进行排序
  429. for(let i = 0;i< a.children.length ; i++){
  430. let m_code = a.children[i].code;
  431. let s_code = n.code;
  432. if(m_code && s_code && m_code!=""&&s_code!=""){
  433. if(m_code > s_code){
  434. a.children.splice(i,0,n);
  435. match = true;
  436. break;
  437. }
  438. }
  439. }
  440. }
  441. if(match == false)a.children.push(n) //没有插入成功,直接放到最后面
  442. }
  443. }
  444. function findTheSameItem(main,item) {//编号名称单位三个相同,认为是同一条清单
  445. return _.find(main,function (tem) {
  446. return isEqual(tem.code,item.code)&&isEqual(tem.name,item.name)&&isEqual(tem.unit,item.unit);
  447. })
  448. }
  449. function isEqual(a,b) {//粗略匹配,null undefind "" 认为相等
  450. return getValue(a)==getValue(b);
  451. function getValue(t) {
  452. if(t==null||t==undefined||t=="") return null;
  453. return t;
  454. }
  455. }
  456. async function getBillsByProjectID(projectID){
  457. let roots=[],parentMap={};
  458. let bills = await bill_model.model.find({projectID: projectID}, '-_id');//取出所有清单
  459. let project = await projectsModel.findOne({ID:projectID});
  460. if(!project) throw new Error(`找不到项目:${projectID}`);
  461. let projectName = project.name;
  462. let author='';//编制人
  463. let auditor='';//审核人
  464. let compilationScope='';//编制范围
  465. let engineering='';//养护类别
  466. if(project.property&&project.property.projectFeature){
  467. for(let f of project.property.projectFeature){
  468. if(f.key == 'author') author = f.value;
  469. if(f.key == 'auditor') auditor = f.value;
  470. if(f.key =='compilationScope') compilationScope = f.value;
  471. if(f.key == 'engineering') engineering = f.value;
  472. }
  473. }
  474. for(let b of bills){
  475. let commonFee =_.find(b._doc.fees,{"fieldName":"common"});
  476. let prices = {};
  477. let quantityMap={};
  478. let unitPrices ={};
  479. if(commonFee&&commonFee.totalFee) prices[projectName] = commonFee.totalFee;
  480. if (commonFee&&commonFee.unitFee) unitPrices[projectName] = commonFee.unitFee;
  481. quantityMap[projectName] = b.quantity;
  482. let flagIndex = _.find(b._doc.flags,{'fieldName':'fixed'});
  483. 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,quantityMap:quantityMap,flag:flagIndex?flagIndex.flag:-99,remark:b.remark};//选取有用字段
  484. if(b.ParentID == -1) roots.push(doc);
  485. parentMap[b.ParentID]?parentMap[b.ParentID].push(doc):parentMap[b.ParentID]=[doc];
  486. }//设置子节点
  487. for(let r of roots){
  488. setChildren(r,parentMap,1);
  489. }
  490. roots = sortChildren(roots);
  491. return {name:projectName,roots:roots,author:author,auditor:auditor,compilationScope:compilationScope,ParentID:project.ParentID,prjTypeName:engineering}
  492. }
  493. function setChildren(bill,parentMap,level) {
  494. let children = parentMap[bill.ID];
  495. if(children){
  496. for(let c of children){
  497. setChildren(c,parentMap,level+1)
  498. }
  499. bill.children = children;
  500. }else {
  501. bill.children = [];
  502. }
  503. }
  504. function sortChildren(lists) {
  505. let IDMap ={},nextMap = {}, firstNode = null,newList=[];
  506. for(let l of lists){
  507. if(l.children&&l.children.length > 0) l.children = sortChildren(l.children);//递规排序
  508. IDMap[l.ID] = l;
  509. if(l.NextSiblingID!=-1) nextMap[l.NextSiblingID] = l;
  510. }
  511. for(let t of lists){
  512. if(!nextMap[t.ID]){ //如果在下一节点映射没找到,则是第一个节点
  513. firstNode = t;
  514. break;
  515. }
  516. }
  517. if(firstNode){
  518. newList.push(firstNode);
  519. delete IDMap[firstNode.ID];
  520. setNext(firstNode,newList);
  521. }
  522. //容错处理,如果链断了的情况,直接添加到后面
  523. for(let key in IDMap){
  524. if(IDMap[key]) newList.push(IDMap[key])
  525. }
  526. return newList;
  527. function setNext(node,array) {
  528. if(node.NextSiblingID != -1){
  529. let next = IDMap[node.NextSiblingID];
  530. if(next){
  531. array.push(next);
  532. delete IDMap[next.ID];
  533. setNext(next,array);
  534. }
  535. }
  536. }
  537. }
  538. async function getGLJSummayDatas(projectIDs) {
  539. let projects = [];
  540. let names = [];
  541. let prjTypeNames = [];
  542. try {
  543. for(let ID of projectIDs){
  544. projects.push(await getProjectData(ID)) ;
  545. }
  546. if(projects.length == 0){
  547. return [];
  548. }
  549. let mp = projects[0];
  550. for(let p of projects){
  551. names.push(p.name);
  552. prjTypeNames.push(p.prjTypeName);
  553. p.gljList = await getProjectGLJData(p.ID,p.unitPriceFileId,mp.property);
  554. }
  555. let mList = mergeGLJ(mp,projects,names,prjTypeNames);
  556. mList = gljUtil.sortProjectGLJ(mList,_);
  557. let summaryGLJDatas = getSummaryGLJDatas(mList,mp.property.decimal,names,prjTypeNames);
  558. let parentProject = await projectsModel.findOne({ID:mp.ParentID});
  559. let result = {
  560. prj: {},
  561. SummaryAudit:{
  562. "name": parentProject?parentProject.name:"",
  563. "编制": mp.author,
  564. "复核": mp.auditor,
  565. "编制范围":mp.compilationScope
  566. },
  567. SummaryAuditDetail:summaryGLJDatas
  568. };
  569. return result;
  570. }catch (e){
  571. console.log(e);
  572. }
  573. }
  574. function getSummaryGLJDatas(gljList,decimal,nameList,prjTypeNames) {
  575. let datas = [],qdecimal = decimal.glj.quantity,process = decimal.process;
  576. for(let tem of gljList){
  577. let d = {
  578. code:tem.code,
  579. name:tem.name,
  580. type:tem.type,
  581. unit:tem.unit,
  582. specs:tem.specs,
  583. marketPrice:tem.marketPrice,
  584. prjNames:nameList,
  585. prjTypeNames:prjTypeNames,
  586. quantityList:[]
  587. };
  588. let totalQuantity = 0;
  589. for(let n of nameList){
  590. let q = tem.quantityMap[n]?scMathUtil.roundForObj(tem.quantityMap[n],qdecimal):0;
  591. totalQuantity = scMathUtil.roundForObj(q+totalQuantity,process);
  592. d.quantityList.push(q);
  593. }
  594. d.totalQuantity = scMathUtil.roundForObj(totalQuantity,qdecimal);
  595. datas.push(d);
  596. }
  597. return datas;
  598. }
  599. function mergeGLJ(mp,projects) {
  600. let gljMap = {},gljList=[];
  601. for(let g of mp.gljList){
  602. g.quantityMap={};
  603. g.quantityMap[mp.name] = g.quantity;
  604. gljMap[gljUtil.getIndex(g)] = g;
  605. gljList.push(g);
  606. }
  607. for(let i = 1;i<projects.length;i++){
  608. let temList = projects[i].gljList;
  609. for(let t of temList){
  610. t.quantityMap={};
  611. t.quantityMap[projects[i].name] = t.quantity;
  612. //这里除了5个属性相同判断为同一个之外,还要判断市场价相同,才认为是同一个工料机
  613. let connect_key = gljUtil.getIndex(t);
  614. let g = gljMap[connect_key];
  615. if(g&&g.marketPrice == t.marketPrice){
  616. g.quantityMap[projects[i].name] = t.quantity;
  617. }else {
  618. gljMap[connect_key] = t;
  619. gljList.push(t);
  620. }
  621. }
  622. }
  623. return gljList;
  624. }
  625. async function getProjectGLJData(projectID,unitPriceFileId,property){
  626. //取项目工料机数据
  627. let projectGLJDatas = await getProjectGLJPrice(projectID,unitPriceFileId,property);
  628. await calcProjectGLJQuantity(projectID,projectGLJDatas,property);
  629. _.remove(projectGLJDatas.gljList,{'quantity':0});
  630. return projectGLJDatas.gljList;
  631. }
  632. async function getProjectData(projectID){
  633. let project = await projectsModel.findOne({ID:projectID});
  634. if(!project) throw new Error(`找不到项目:${projectID}`);
  635. let projectName = project.name;
  636. let author='';//编制人
  637. let auditor='';//审核人
  638. let compilationScope='';//编制范围
  639. let engineering='';//养护类别
  640. if(project.property&&project.property.projectFeature){
  641. for(let f of project.property.projectFeature){
  642. if(f.key == 'author') author = f.value;
  643. if(f.key == 'auditor') auditor = f.value;
  644. if(f.key =='compilationScope') compilationScope = f.value;
  645. if(f.key == 'engineering') engineering = f.value;
  646. }
  647. }
  648. if(!(project.property&&project.property.unitPriceFile)) throw new Error(`找不到单价文件:${projectID}`);
  649. let unitPriceFileId = project.property.unitPriceFile.id;
  650. return {ID:projectID,name:projectName,author:author,auditor:auditor,compilationScope:compilationScope,ParentID:project.ParentID,prjTypeName:engineering,property:project.property,unitPriceFileId:unitPriceFileId}
  651. }
  652. async function getProjectGLJPrice(projectID,unitPriceFileId,property){
  653. //取项目工料机数据
  654. let calcOptions=property.calcOptions;
  655. let decimalObj = property.decimal;
  656. let labourCoeDatas = [];//取调整价才需要用到
  657. let gljListModel = new GLJListModel();
  658. let [gljList, mixRatioConnectData,mixRatioMap,unitPriceMap] = await gljListModel.getListByProjectId(projectID, unitPriceFileId);
  659. gljList = JSON.parse(JSON.stringify(gljList));
  660. for(let glj of gljList){
  661. let result = gljUtil.getGLJPrice(glj,{gljList:gljList},calcOptions,labourCoeDatas,decimalObj,false,_,scMathUtil);
  662. glj.marketPrice = result.marketPrice;
  663. glj.basePrice = result.basePrice;
  664. }
  665. return {gljList:gljList,mixRatioMap:mixRatioMap};
  666. }
  667. async function calcProjectGLJQuantity(projectID,projectGLJDatas,property){
  668. let q_decimal = property.decimal.glj.quantity;
  669. let rationGLJDatas = await ration_glj_model.find({'projectID':projectID});
  670. let rationDatas = await ration_model.model.find({'projectID':projectID});
  671. gljUtil.calcProjectGLJQuantity(projectGLJDatas,rationGLJDatas,rationDatas,[],q_decimal)
  672. }