project_facade.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  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. };
  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 bill_model = require('../models/bills');
  21. let consts = require('../models/project_consts');
  22. let projectConsts = consts.projectConst;
  23. let ration_glj_model = mongoose.model('ration_glj');
  24. let rationTemplateModel = mongoose.model('ration_template');
  25. let project_glj_model = mongoose.model('glj_list');
  26. let ration_glj_facade = require("../../ration_glj/facade/ration_glj_facade");
  27. const uuidV1 = require('uuid/v1');
  28. const gljUtil = require('../../../public/gljUtil');
  29. let stdColSettingModel = mongoose.model('std_main_col_lib');
  30. let decimal_facade = require('../../main/facade/decimal_facade');
  31. const scMathUtil = require('../../../public/scMathUtil').getUtil();
  32. import fixedFlag from '../../common/const/bills_fixed';
  33. const projectDao = require('../../pm/models/project_model').project;
  34. async function calcInstallationFee(data) {
  35. let result={};
  36. let billTasks = generateTasks(data.bills,data.useID);
  37. let rationTasks = generateTasks(data.ration,data.useID);
  38. if(billTasks.length>0){
  39. await bill_model.model.bulkWrite(billTasks);
  40. }
  41. console.log(rationTasks);
  42. if(rationTasks.length>0){
  43. await ration_model.model.bulkWrite(rationTasks);
  44. }
  45. //如果删除定额,需要删除对应的工料机
  46. if(data.ration.delete.length>0){
  47. let rationIDS = _.map(data.ration.delete,'ID');
  48. await ration_glj_model.deleteMany({projectID: data.ration.delete[0].projectID, rationID: {"$in": rationIDS}});//删除定额工料机
  49. }
  50. let rationGLJTasks = [];
  51. let updateList = [];
  52. if(data.ration.update.length>0){//如果有需要更新的定额工料机
  53. for(let ur of data.ration.update){
  54. for(let g of ur.glj){
  55. let gTasks = {
  56. updateOne:{
  57. filter:{
  58. ID:g.ID,
  59. projectID:g.projectID
  60. },
  61. update :{
  62. quantity:g.quantity,
  63. rationItemQuantity:g.rationItemQuantity
  64. }
  65. }
  66. };
  67. rationGLJTasks.push(gTasks);
  68. updateList.push(g);
  69. }
  70. }
  71. }
  72. if(rationGLJTasks.length>0){
  73. await ration_glj_model.bulkWrite(rationGLJTasks);
  74. }
  75. let newGljList = [];
  76. if(data.ration.add.length>0){//新增的安装子目要增加对应的工料机
  77. for(let nr of data.ration.add){
  78. for(let tkey in nr.glj){
  79. newGljList.push(await addInstallationGLJ(nr.glj[tkey]));
  80. }
  81. }
  82. }
  83. if(newGljList.length>0){
  84. await ration_glj_model.insertMany(newGljList);
  85. }
  86. result.update = updateList;
  87. result.add = newGljList;
  88. return result;
  89. }
  90. async function addInstallationGLJ(glj) {
  91. glj.ID = uuidV1();
  92. let info = await ration_glj_facade.getInfoFromProjectGLJ(glj);
  93. let newRecode = ration_glj_facade.createNewRecord(info);
  94. return newRecode;
  95. }
  96. function generateTasks(data,userID) {
  97. let tasks=[];
  98. let deleteInfo={deleted: true, deleteDateTime: new Date(), deleteBy: userID};
  99. if(data.delete && data.delete.length > 0){
  100. for(let bd of data.delete){
  101. //原先是假删除,现在改成真删除
  102. let task = {
  103. deleteOne:{
  104. filter:{
  105. ID:bd.ID,
  106. projectID:bd.projectID
  107. }
  108. }
  109. };
  110. /* let task={
  111. updateOne:{
  112. filter:{
  113. ID:bd.ID,
  114. projectID:bd.projectID
  115. },
  116. update :{
  117. deleteInfo:deleteInfo
  118. }
  119. }
  120. };*/
  121. tasks.push(task);
  122. }
  123. }
  124. if(data.add && data.add.length > 0){
  125. for(let n_data of data.add){
  126. let task = {
  127. insertOne :{
  128. document:n_data
  129. }
  130. };
  131. tasks.push(task);
  132. }
  133. }
  134. return tasks;
  135. }
  136. async function updateNodes(datas){
  137. let nodeGroups = _.groupBy(datas,'type');
  138. let rationTasks = [];
  139. let billTasks = [];
  140. let rationGLJTasks = [];
  141. let projectGLJTasks = [];
  142. let projectTasks = [];
  143. let rationTemplateTasks = [];
  144. let asyncTasks = [];
  145. for(let type in nodeGroups){
  146. for(let node of nodeGroups[type]){
  147. if(type == projectConsts.BILLS){
  148. billTasks.push(getTask(node));
  149. }else if(type == projectConsts.RATION){
  150. rationTasks.push(getTask(node));
  151. }else if(type == projectConsts.RATION_GLJ){
  152. rationGLJTasks.push(getTask(node));
  153. }else if(type == projectConsts.PROJECTGLJ){
  154. projectGLJTasks.push(getTask(node,'id'));
  155. }else if(type == projectConsts.PROJECT){
  156. projectTasks.push(getTask(node));
  157. }else if(type == projectConsts.RATION_TEMPLATE){
  158. rationTemplateTasks.push(getTask(node))
  159. }
  160. }
  161. }
  162. rationTasks.length>0?asyncTasks.push(ration_model.model.bulkWrite(rationTasks)):'';
  163. billTasks.length>0?asyncTasks.push(bill_model.model.bulkWrite(billTasks)):"";
  164. rationGLJTasks.length>0?asyncTasks.push(ration_glj_model.bulkWrite(rationGLJTasks)):"";
  165. projectGLJTasks.length>0?asyncTasks.push(project_glj_model.bulkWrite(projectGLJTasks)):"";
  166. projectTasks.length>0?asyncTasks.push(projectsModel.bulkWrite(projectTasks)):"";
  167. rationTemplateTasks.length>0?asyncTasks.push(rationTemplateModel.bulkWrite(rationTemplateTasks)):"";
  168. return asyncTasks.length>0?await Promise.all(asyncTasks):"";
  169. function getTask(node,idFiled = 'ID') {
  170. let task={
  171. updateOne:{
  172. filter:{},
  173. update :_.cloneDeep(node.data)
  174. }
  175. };
  176. task.updateOne.filter[idFiled] = node.data[idFiled];//现在复制项目也重新生成一个新的ID了,所以ID是唯一的
  177. delete task.updateOne.update[idFiled];//防止误操作
  178. return task;
  179. }
  180. }
  181. /*function updateNodes(datas,callback) {
  182. let tasks = [];
  183. for(let node of datas){
  184. tasks.push(updateOne(node))
  185. }
  186. async_n.parallel(tasks, function(err, results) {
  187. if (!err){
  188. callback(0, '', results);
  189. }
  190. else{
  191. console.log(err);
  192. callback(1, 'save project failed'+err.message, null);
  193. }
  194. });
  195. function updateOne(node) {
  196. if(node.type == projectConsts.BILLS){
  197. return function (asCallback) {
  198. bill_model.model.findOneAndUpdate({projectID: node.data.projectID, ID: node.data.ID,deleteInfo: null}, node.data,{new: true}, asCallback);
  199. }
  200. }else if(node.type ==projectConsts.RATION){
  201. return function (asCallback) {
  202. ration_model.model.findOneAndUpdate({projectID: node.data.projectID, ID: node.data.ID,deleteInfo: null}, node.data,{new: true}, asCallback);
  203. }
  204. }
  205. }
  206. }*/
  207. //data = {feeRateID:111111,projectID:1245}; type = feeRate
  208. async function markUpdateProject(data,type) {
  209. let query = {deleteInfo:null};
  210. if(type=="feeRate"){//更改了费率
  211. query['property.feeFile.id'] = data.feeRateID;
  212. }
  213. if(type=="unitFile"){//更改了单价文件
  214. query['property.unitPriceFile.id'] = data.unitFileID;//unitPriceFile
  215. }
  216. let projects = await projectsModel.find(query);
  217. return await markProjectsToChange(projects,type,data.projectID);
  218. }
  219. async function markProjectsToChange(projects,type,extProjectID){
  220. let tasks=[];
  221. for(let p of projects){
  222. if(extProjectID && p.ID===extProjectID) continue;//排除当前项目
  223. tasks.push(generateMarkTask(type,p.ID));
  224. }
  225. return tasks.length>0 ? await projectsModel.bulkWrite(tasks):null;
  226. }
  227. async function removeProjectMark(projectID) {
  228. return await projectsModel.findOneAndUpdate({ID:projectID},{"$unset":{"changeMark":1}});
  229. }
  230. function generateMarkTask(value,projectID) {
  231. let task = {
  232. updateOne:{
  233. filter:{
  234. ID:projectID
  235. },
  236. update:{
  237. changeMark:value
  238. }
  239. }
  240. };
  241. return task
  242. }
  243. // {projectID: 5, propertyName: 'aaa', propertyValue: 1}
  244. function saveProperty(data, callback){
  245. let obj = {};
  246. let pn = 'property.' + data.propertyName;
  247. obj[pn] = data.propertyValue;
  248. projectsModel.update({"ID": data.projectID}, obj, function (err) {
  249. if (err) {
  250. logger.err(pn + ' save error: ' + err);
  251. callback(err, null)
  252. } else {
  253. logger.info(pn + ' saved.');
  254. callback('', null);
  255. }}
  256. );
  257. }
  258. async function getDefaultColSetting(libID){
  259. return await stdColSettingModel.findOne({ID: libID, deleted: false}, '-_id main_tree_col');
  260. }
  261. async function getBudgetSummayDatas(projectIDs){
  262. try {
  263. let projects = [];
  264. let names = [];
  265. let prjTypeNames = [];
  266. let compilationScopes = [];
  267. let decimal = null;
  268. for(let ID of projectIDs){
  269. projects.push(await getBillsByProjectID(ID)) ;
  270. }
  271. if(projects.length == 0){
  272. return [];
  273. }
  274. let mp = projects[0];
  275. names.push(mp.name);
  276. prjTypeNames.push(mp.prjTypeName);
  277. compilationScopes.push(mp.compilationScope);
  278. for(let i = 1;i<projects.length;i++){
  279. names.push(projects[i].name);
  280. prjTypeNames.push(projects[i].prjTypeName);
  281. compilationScopes.push(projects[i].compilationScope);
  282. decimal = await mergeProject(mp.roots,projects[i].roots)
  283. }
  284. let SummaryAuditDetail = getReportData(names,mp.roots,prjTypeNames,compilationScopes,decimal);
  285. let parentProject = await projectsModel.findOne({ID:mp.ParentID});
  286. let result = {
  287. prj: {},
  288. SummaryAudit:{
  289. "name": parentProject?parentProject.name:"",
  290. "编制": mp.author,
  291. "复核": mp.auditor,
  292. "编制范围":mp.compilationScope
  293. },
  294. SummaryAuditDetail:SummaryAuditDetail
  295. };
  296. return result;
  297. }catch (e){
  298. console.log(e)
  299. }
  300. }
  301. function getReportData(nameList,items,prjTypeNames,compilationScopes,decimal) {
  302. let datas = [],totalItem = null;
  303. setChildrenDatas(items,datas);
  304. for(let d of datas){
  305. if(d.billsTtlPrice&&totalItem.billsTtlPrice){
  306. d['各项费用比例'] = scMathUtil.roundForObj(d.billsTtlPrice/totalItem.billsTtlPrice * 100,2)
  307. }
  308. d['prjNames'] = nameList;
  309. d['prjTypeNames'] = prjTypeNames;
  310. d['编制范围明细'] = compilationScopes;
  311. }
  312. return datas;
  313. function setChildrenDatas(children,arr,level = 0) {
  314. for(let c of children){
  315. arr.push(getBillDatas(c,level));
  316. setChildrenDatas(c.children,arr,level+1);
  317. }
  318. }
  319. function getBillDatas(bills,level) {
  320. let tem = {
  321. billsName:bills.name,
  322. billsCode:bills.code,
  323. billsUnit:bills.unit,
  324. billsTtlAmt:bills.quantity,
  325. billsPrices:[],
  326. billsAmounts:[],
  327. '技术经济指标':[],
  328. billsLevel:level,
  329. billsMemos:bills.remark
  330. };
  331. let total = 0;
  332. for(let n of nameList){
  333. let p = 0;
  334. if(bills.prices[n]){
  335. p = scMathUtil.roundForObj(bills.prices[n],decimal.bills.totalPrice);
  336. total = scMathUtil.roundForObj(p+total,decimal.process);
  337. }
  338. tem.billsPrices.push(p);
  339. if(bills.quantityMap[n]){
  340. tem.billsAmounts.push(bills.quantityMap[n]);
  341. tem['技术经济指标'].push(scMathUtil.roundForObj(p/bills.quantityMap[n],2));
  342. }else {
  343. tem.billsAmounts.push(0);
  344. tem['技术经济指标'].push(0);
  345. }
  346. }
  347. tem.billsTtlPrice = scMathUtil.roundForObj(total,decimal.bills.totalPrice);
  348. tem['技术经济综合指标'] = tem.billsTtlAmt?scMathUtil.roundForObj(tem.billsTtlPrice/tem.billsTtlAmt,2):0;
  349. if(bills.flag == fixedFlag.TOTAL_COST) totalItem = tem;
  350. return tem
  351. }
  352. }
  353. async function mergeProject(main,sub) {//合并两个项目
  354. let decimal = await decimal_facade.getProjectDecimal(main[0].projectID);
  355. let project = await projectsModel.findOne({ID:main[0].projectID});
  356. let notMatchList = [];
  357. for(let s of sub){
  358. //先找有没有相同的大项费用
  359. let same = findTheSameItem(main,s);
  360. same?await mergeItem(same,s,decimal,project._doc):notMatchList.push(s);//如果找到,则合并,找不到就放在未匹配表
  361. }
  362. for(let n of notMatchList){
  363. main.push(n);
  364. }
  365. return decimal;
  366. }
  367. async function mergeItem(a,b,decimal,project) {
  368. let bqDecimal = await decimal_facade.getBillsQuantityDecimal(a.projectID,a.unit,project);
  369. a.quantity = a.quantity?scMathUtil.roundForObj(a.quantity,bqDecimal):0;
  370. b.quantity = b.quantity?scMathUtil.roundForObj(b.quantity,bqDecimal):0;
  371. a.quantity = scMathUtil.roundForObj(a.quantity+b.quantity,decimal.process);
  372. for(let name in b.prices){
  373. a.prices[name] = b.prices[name];
  374. a.quantityMap[name] = b.quantityMap[name];
  375. }
  376. for(let name in a.quantityMap){
  377. a.quantityMap[name] = a.quantityMap[name]?scMathUtil.roundForObj(a.quantityMap[name],bqDecimal):0;
  378. }
  379. await mergeChildren(a,b,decimal,project);
  380. }
  381. async function mergeChildren(a,b,decimal,project) {
  382. let notMatchList = [];
  383. if(a.children.length > 0 && b.children.length ==0){
  384. return;
  385. }else if(a.children.length == 0 && b.children.length > 0){
  386. a.children = b.children;
  387. return;
  388. }
  389. //=============剩下的是两者都有的情况
  390. for(let s of b.children){
  391. let same = findTheSameItem(a.children,s);
  392. same?await mergeItem(same,s,decimal,project):notMatchList.push(s);//如果找到,则合并,找不到就放在未匹配表
  393. }
  394. for(let n of notMatchList){
  395. let match = false;//符合插入标记
  396. //对于未匹配的子项,如果是固定清单:第100章至700章清单的子项,要匹配名字中的数字来做排充
  397. if(a.flag == fixedFlag.ONE_SEVEN_BILLS){
  398. for(let i = 0;i< a.children.length;i++){
  399. let m_name = a.children[i].name.replace(/[^0-9]/ig,"");
  400. let s_name = n.name.replace(/[^0-9]/ig,"");
  401. m_name = parseFloat(m_name);
  402. s_name = parseFloat(s_name);
  403. if(m_name&&s_name){
  404. if(m_name == s_name){
  405. await mergeItem(a.children[i],n,project);
  406. match = true;
  407. break;
  408. }
  409. if(m_name > s_name){//主节点名字中的数字大于被插节点,则被插节点放在主节点前面
  410. a.children.splice(i,0,n);
  411. match = true;
  412. break;
  413. }
  414. }
  415. }
  416. }else {//其它的子项按编号进行排序
  417. for(let i = 0;i< a.children.length ; i++){
  418. let m_code = a.children[i].code;
  419. let s_code = n.code;
  420. if(m_code && s_code && m_code!=""&&s_code!=""){
  421. if(m_code > s_code){
  422. a.children.splice(i,0,n);
  423. match = true;
  424. break;
  425. }
  426. }
  427. }
  428. }
  429. if(match == false)a.children.push(n) //没有插入成功,直接放到最后面
  430. }
  431. }
  432. function findTheSameItem(main,item) {//编号名称单位三个相同,认为是同一条清单
  433. return _.find(main,function (tem) {
  434. return isEqual(tem.code,item.code)&&isEqual(tem.name,item.name)&&isEqual(tem.unit,item.unit);
  435. })
  436. }
  437. function isEqual(a,b) {//粗略匹配,null undefind "" 认为相等
  438. return getValue(a)==getValue(b);
  439. function getValue(t) {
  440. if(t==null||t==undefined||t=="") return null;
  441. return t;
  442. }
  443. }
  444. async function getBillsByProjectID(projectID){
  445. let roots=[],parentMap={};
  446. let bills = await bill_model.model.find({projectID: projectID}, '-_id');//取出所有清单
  447. let project = await projectsModel.findOne({ID:projectID});
  448. if(!project) throw new Error(`找不到项目:${projectID}`);
  449. let projectName = project.name;
  450. let author='';//编制人
  451. let auditor='';//审核人
  452. let compilationScope='';//编制范围
  453. let engineering='';//养护类别
  454. if(project.property&&project.property.projectFeature){
  455. for(let f of project.property.projectFeature){
  456. if(f.key == 'author') author = f.value;
  457. if(f.key == 'auditor') auditor = f.value;
  458. if(f.key =='compilationScope') compilationScope = f.value;
  459. if(f.key == 'engineering') engineering = f.value;
  460. }
  461. }
  462. for(let b of bills){
  463. let commonFee =_.find(b._doc.fees,{"fieldName":"common"});
  464. let prices = {};
  465. let quantityMap={};
  466. if(commonFee&&commonFee.totalFee) prices[projectName] = commonFee.totalFee;
  467. quantityMap[projectName] = b.quantity;
  468. let flagIndex = _.find(b._doc.flags,{'fieldName':'fixed'});
  469. let doc = {ID:b.ID,name:b.name,code:b.code,unit:b.unit,projectID:b.projectID, ParentID:b.ParentID,NextSiblingID:b.NextSiblingID,quantity:b.quantity,prices:prices,quantityMap:quantityMap,flag:flagIndex?flagIndex.flag:-99,remark:b.remark};//选取有用字段
  470. if(b.ParentID == -1) roots.push(doc);
  471. parentMap[b.ParentID]?parentMap[b.ParentID].push(doc):parentMap[b.ParentID]=[doc];
  472. }//设置子节点
  473. for(let r of roots){
  474. setChildren(r,parentMap,1);
  475. }
  476. roots = sortChildren(roots);
  477. return {name:projectName,roots:roots,author:author,auditor:auditor,compilationScope:compilationScope,ParentID:project.ParentID,prjTypeName:engineering}
  478. }
  479. function setChildren(bill,parentMap,level) {
  480. let children = parentMap[bill.ID];
  481. if(children){
  482. for(let c of children){
  483. setChildren(c,parentMap,level+1)
  484. }
  485. bill.children = children;
  486. }else {
  487. bill.children = [];
  488. }
  489. }
  490. function sortChildren(lists) {
  491. let IDMap ={},nextMap = {}, firstNode = null,newList=[];
  492. for(let l of lists){
  493. if(l.children&&l.children.length > 0) l.children = sortChildren(l.children);//递规排序
  494. IDMap[l.ID] = l;
  495. if(l.NextSiblingID!=-1) nextMap[l.NextSiblingID] = l;
  496. }
  497. for(let t of lists){
  498. if(!nextMap[t.ID]){ //如果在下一节点映射没找到,则是第一个节点
  499. firstNode = t;
  500. break;
  501. }
  502. }
  503. if(firstNode){
  504. newList.push(firstNode);
  505. delete IDMap[firstNode.ID];
  506. setNext(firstNode,newList);
  507. }
  508. //容错处理,如果链断了的情况,直接添加到后面
  509. for(let key in IDMap){
  510. if(IDMap[key]) newList.push(IDMap[key])
  511. }
  512. return newList;
  513. function setNext(node,array) {
  514. if(node.NextSiblingID != -1){
  515. let next = IDMap[node.NextSiblingID];
  516. if(next){
  517. array.push(next);
  518. delete IDMap[next.ID];
  519. setNext(next,array);
  520. }
  521. }
  522. }
  523. }