project_facade.js 30 KB

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