project_facade.js 31 KB

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