project_facade.js 28 KB

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