project_facade.js 26 KB

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