project_facade.js 31 KB

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