project_facade.js 31 KB

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