facades.js 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012
  1. 'use strict';
  2. /**
  3. *
  4. *
  5. * @author Zhong
  6. * @date 2018/6/1
  7. * @version
  8. */
  9. import mongoose from 'mongoose';
  10. import CompilationModel from "../../users/models/compilation_model";
  11. import moment from 'moment';
  12. const uuidV1 = require('uuid/v1');
  13. const billsLibModel = mongoose.model('std_bills_lib_list');
  14. const billsGuideLibModel = mongoose.model('std_billsGuidance_lib');
  15. const billsGuideItemsModel = mongoose.model('std_billsGuidance_items');
  16. const stdBillsLibModel = mongoose.model('std_bills_lib_list');
  17. const stdBillsModel = mongoose.model('std_bills_lib_bills');
  18. const stdBillsJobsModel = mongoose.model('std_bills_lib_jobContent');
  19. const stdRationModel = mongoose.model('std_ration_lib_ration_items');
  20. const engLibModel = mongoose.model('engineering_lib');
  21. const compilationModel = mongoose.model('compilation');
  22. const billMaterialModel = mongoose.model('std_billsGuidance_materials');
  23. const gljModel = mongoose.model('std_glj_lib_gljList');
  24. const gljLibModel = mongoose.model('std_glj_lib_map');
  25. const billClassModel = mongoose.model('billClass');
  26. const idTree = require('../../../public/id_tree').getTree();
  27. const _ = require('lodash');
  28. const zhLibID = 'cf851660-3534-11ec-9641-2da8021b8e4e';
  29. const cqLibID = '90c51220-a740-11e8-a354-ab5db7d42428';
  30. module.exports = {
  31. handleCopyItems,
  32. getComBillsLibInfo,
  33. getBillsGuideLibs,
  34. initBillsGuideLib,
  35. updateBillsGuideLib,
  36. getLibWithBills,
  37. getItemsBybills,
  38. updateItems,
  39. getBillMaterials,
  40. editBillMaterials,
  41. generateClassData,
  42. getClassExcelData,
  43. testItems
  44. };
  45. function setChildren(bill, parentMap) {
  46. let children = parentMap[bill.ID];
  47. if (children) {
  48. for (let c of children) {
  49. setChildren(c, parentMap);
  50. }
  51. bill.children = children;
  52. } else {
  53. bill.children = [];
  54. }
  55. }
  56. function sortChildren(lists) {
  57. let IDMap = {},
  58. nextMap = {},
  59. firstNode = null,
  60. newList = [];
  61. for (let l of lists) {
  62. if (l.children && l.children.length > 0) l.children = sortChildren(l.children); //递规排序
  63. IDMap[l.ID] = l;
  64. if (l.NextSiblingID != -1) nextMap[l.NextSiblingID] = l;
  65. }
  66. for (let t of lists) {
  67. if (!nextMap[t.ID]) { //如果在下一节点映射没找到,则是第一个节点
  68. firstNode = t;
  69. break;
  70. }
  71. }
  72. if (firstNode) {
  73. newList.push(firstNode);
  74. delete IDMap[firstNode.ID];
  75. setNext(firstNode, newList);
  76. }
  77. //容错处理,如果链断了的情况,直接添加到后面
  78. for (let key in IDMap) {
  79. if (IDMap[key]) newList.push(IDMap[key])
  80. }
  81. return newList;
  82. function setNext(node, array) {
  83. if (node.NextSiblingID != -1) {
  84. let next = IDMap[node.NextSiblingID];
  85. if (next) {
  86. array.push(next);
  87. delete IDMap[next.ID];
  88. setNext(next, array);
  89. }
  90. }
  91. }
  92. }
  93. function getItemFromChildren(children, allItems) {
  94. for (let i = 0; i < children.length; i++) {
  95. const cur = children[i];
  96. const next = children[i + 1];
  97. cur.NextSiblingID = next && next.ID || -1;
  98. allItems.push(cur);
  99. if (cur.children && cur.children.length) {
  100. getItemFromChildren(cur.children, allItems);
  101. }
  102. }
  103. }
  104. function resetTreeData(billsList) {
  105. const idMapping = {};
  106. idMapping['-1'] = -1;
  107. // 建立新ID-旧ID映射
  108. billsList.forEach(bills => idMapping[bills.ID] = uuidV1());
  109. billsList.forEach(function (bills) {
  110. bills.ID = idMapping[bills.ID] ? idMapping[bills.ID] : -1;
  111. bills.ParentID = idMapping[bills.ParentID] ? idMapping[bills.ParentID] : -1;
  112. bills.NextSiblingID = idMapping[bills.NextSiblingID] ? idMapping[bills.NextSiblingID] : -1;
  113. });
  114. }
  115. // 从某库中根据清单编号拷贝工艺
  116. async function handleCopyItems(sourceGuideLibID, sourceBillsLibID, targetGuideLibID, targetBillsLibID) {
  117. const sourceBills = await stdBillsModel.find({ billsLibId: sourceBillsLibID, deleted: false }, '-_id ID code').lean();
  118. const targetBills = await stdBillsModel.find({ billsLibId: targetBillsLibID, deleted: false }, '-_id ID code').lean();
  119. const sourceItems = await billsGuideItemsModel.find({ libID: sourceGuideLibID, type: 0, deleted: false }, '-_id').lean(); // 过滤掉定额项
  120. const targetCodeIDMap = {};
  121. targetBills.forEach(bills => targetCodeIDMap[bills.code] = bills.ID);
  122. const toDeleteIDList = [];
  123. const insertBulks = [];
  124. sourceBills.forEach(bills => {
  125. const matchedItems = sourceItems.filter(item => item.billsID === bills.ID);
  126. // 重新将断缺的树结构数据整理好
  127. if (matchedItems.length) {
  128. const parentMap = {};
  129. matchedItems.forEach(item => {
  130. (parentMap[item.ParentID] || (parentMap[item.ParentID] = [])).push(item);
  131. });
  132. const roots = parentMap['-1'];
  133. roots.forEach(root => setChildren(root, parentMap));
  134. const sorted = sortChildren(roots);
  135. const newItems = [];
  136. getItemFromChildren(sorted, newItems);
  137. resetTreeData(newItems);
  138. const targetBillsID = targetCodeIDMap[bills.code];
  139. if (targetBillsID) {
  140. toDeleteIDList.push(targetBillsID);
  141. newItems.forEach(newItem => {
  142. newItem.libID = targetGuideLibID;
  143. newItem.billsID = targetBillsID;
  144. insertBulks.push({
  145. insertOne: { document: newItem }
  146. });
  147. })
  148. }
  149. }
  150. });
  151. if (toDeleteIDList.length) {
  152. await billsGuideItemsModel.remove({ libID: targetGuideLibID, billsID: { $in : toDeleteIDList } });
  153. }
  154. if (insertBulks.length) {
  155. await billsGuideItemsModel.bulkWrite(insertBulks);
  156. }
  157. }
  158. async function getCompilationList() {
  159. let compilationModel = new CompilationModel();
  160. return await compilationModel.getCompilationList();
  161. }
  162. async function getComBillsLibInfo() {
  163. let rst = {compilationList: [], billsLibs: []};
  164. let compilationList = await getCompilationList();
  165. if(compilationList.length <= 0){
  166. throw '没有数据';
  167. }
  168. else{
  169. for(let compilation of compilationList){
  170. rst.compilationList.push({_id: compilation._id, name: compilation.name});
  171. }
  172. rst.billsLibs = await billsLibModel.find({deleted: false}, '-_id billsLibId billsLibName');
  173. return rst;
  174. }
  175. }
  176. async function getBillsGuideLibs(findData, isTemporary) {
  177. if (isTemporary) {
  178. const libs = await billsGuideLibModel.find({ ID: { $in: [zhLibID, cqLibID] } }).lean();
  179. return libs;
  180. }
  181. return await billsGuideLibModel.find(findData);
  182. }
  183. // 如果是“重庆费用定额(2018)”,则默认叶子清单的项目指引窗口只有一条数据,取清单名称。
  184. async function genGuidanceItems_cq18(guidanceLibId, billsLibId) {
  185. let bills = await stdBillsModel.find({billsLibId: billsLibId, deleted: false, 'jobs.0': {$exists: true}});
  186. let insertArr = [];
  187. for(let bill of bills){
  188. let newItem = {
  189. libID: guidanceLibId,
  190. ID: uuidV1(), ParentID: -1,
  191. NextSiblingID: -1,
  192. name: bill.name,
  193. type: 0,
  194. billsID: bill.ID
  195. };
  196. insertArr.push({insertOne: {document: newItem}});
  197. }
  198. await billsGuideItemsModel.bulkWrite(insertArr);
  199. }
  200. //拷贝工作内容并转化为树结构,形成项目指引数据
  201. async function genGuidanceItems(guidanceLibId, billsLibId){
  202. let bills = await stdBillsModel.find({billsLibId: billsLibId, deleted: false, 'jobs.0': {$exists: true}});
  203. //设置工作内容数据
  204. let jobIds = [];
  205. let totalJobs = [];
  206. for(let bill of bills){
  207. for(let job of bill.jobs){
  208. jobIds.push(job.id);
  209. }
  210. }
  211. jobIds = Array.from(new Set(jobIds));
  212. if(jobIds.length > 0){
  213. totalJobs = await stdBillsJobsModel.find({deleted: false, id: {$in: jobIds}});
  214. }
  215. if(totalJobs.length > 0){
  216. let jobIdIndex = {};//id索引
  217. for(let job of totalJobs){
  218. jobIdIndex[job.id] = job;
  219. }
  220. let insertArr = [];
  221. for(let bill of bills){
  222. //排序后根据serialNo转换成NextSiblingID,倒序
  223. bill.jobs.sort(function (a, b) {
  224. let rst = 0;
  225. if(a.serialNo > b.serialNo){
  226. rst = -1;
  227. }
  228. else if(a.serialNo < b.serialNo){
  229. rst = 1;
  230. }
  231. return rst;
  232. });
  233. let jobNoIndex = {};//下标索引
  234. for(let i = 0; i < bill.jobs.length; i++){
  235. let newItem = {libID: guidanceLibId, ID: uuidV1(), ParentID: -1, NextSiblingID: jobNoIndex[i - 1] ? jobNoIndex[i - 1]['ID'] : -1,
  236. name: jobIdIndex[bill.jobs[i]['id']]['content'], type: 0, billsID: bill.ID};
  237. jobNoIndex[i] = newItem;
  238. insertArr.push({insertOne: {document: newItem}});
  239. }
  240. }
  241. await billsGuideItemsModel.bulkWrite(insertArr);
  242. }
  243. }
  244. async function initBillsGuideLib(updateData){
  245. await billsGuideLibModel.create(updateData);
  246. let compilation = await compilationModel.findOne({_id: mongoose.Types.ObjectId(updateData.compilationId)});
  247. if (compilation &&
  248. compilation.overWriteUrl &&
  249. compilation.overWriteUrl === '/web/over_write/js/chongqing_2018.js') {
  250. await genGuidanceItems_cq18(updateData.ID, updateData.billsLibId);
  251. } else {
  252. await genGuidanceItems(updateData.ID, updateData.billsLibId);
  253. }
  254. }
  255. async function updateBillsGuideLib(data) {
  256. if(data.updateType === 'delete'){
  257. //删除所有条目
  258. await billsGuideLibModel.remove(data.findData);
  259. await billsGuideItemsModel.remove({libID: data.findData.ID});
  260. }
  261. else {
  262. await billsGuideLibModel.update(data.findData, {$set: data.updateData});
  263. await engLibModel.update({'billsGuidance_lib.id': data.findData.ID}, {$set: {'billsGuidance_lib.$.name': data.updateData.name}}, {multi: true});
  264. }
  265. }
  266. async function getLibWithBills(libID){
  267. let guidanceLib = await getBillsGuideLibs({ID: libID});
  268. if(guidanceLib.length === 0){
  269. throw '不存在此指引库!';
  270. }
  271. let billsLib = await stdBillsLibModel.findOne({billsLibId: guidanceLib[0].billsLibId});
  272. if(!billsLib){
  273. throw '引用的清单规则库不存在!';
  274. }
  275. let bills = await stdBillsModel.find({billsLibId: billsLib.billsLibId}, '-_id code name ID NextSiblingID ParentID jobs items comment').lean();
  276. const guideItems = await billsGuideItemsModel.find({ libID: guidanceLib[0].ID }, '-_id billsID').lean();
  277. const billsMap = {};
  278. for (const item of guideItems) {
  279. billsMap[item.billsID] = true;
  280. }
  281. for (const item of bills) {
  282. if (billsMap[item.ID]) {
  283. item.hasGuide = true;
  284. }
  285. }
  286. return {guidanceLib: guidanceLib[0], bills};
  287. }
  288. function getAttrs(field, datas){
  289. let rst = [];
  290. for(let data of datas){
  291. if(data[field]){
  292. rst.push(data[field]);
  293. }
  294. }
  295. return rst;
  296. }
  297. //定额项目指所引用定额是否被删除
  298. function rationAllExist(rationItems, stdRationIdx) {
  299. for(let item of rationItems){
  300. if(!stdRationIdx[item.rationID]){
  301. return false;
  302. }
  303. }
  304. return true;
  305. }
  306. //将同层树结构转为顺序数组
  307. function chainToArr(nodes){
  308. let rst = [];
  309. let tempIdx = {};
  310. let nodeIdx = {};
  311. //建索引
  312. for(let node of nodes){
  313. tempIdx[node.ID] = {ID: node.ID, NextSiblingID: node.NextSiblingID, preSibling: null, nextSibling: null};
  314. nodeIdx[node.ID] = node;
  315. }
  316. //建链
  317. for(let i in tempIdx){
  318. let temp = tempIdx[i];
  319. if(temp.NextSiblingID != -1){
  320. let next = tempIdx[temp.NextSiblingID];
  321. temp.nextSibling = next;
  322. next.preSibling = temp;
  323. }
  324. }
  325. let firstNode = null;
  326. for(let i in tempIdx){
  327. if(!tempIdx[i].preSibling){
  328. firstNode = tempIdx[i];
  329. break;
  330. }
  331. }
  332. //获得顺序队列
  333. while(firstNode){
  334. rst.push(nodeIdx[firstNode.ID]);
  335. firstNode = firstNode.nextSibling;
  336. }
  337. return rst;
  338. }
  339. async function getItemsBybills(guidanceLibID, billsID){
  340. const type = {job: 0, ration: 1};
  341. let items = await billsGuideItemsModel.find({libID: guidanceLibID, billsID: billsID, deleted: false});
  342. let rationItems = _.filter(items, {type: type.ration});
  343. let rationIds = getAttrs('rationID', rationItems);
  344. let stdRations = await stdRationModel.find({ID: {$in: rationIds}, $or: [{isDeleted: null}, {isDeleted: false}]});
  345. let stdRationIndex = {};
  346. for(let stdRation of stdRations){
  347. stdRationIndex[stdRation.ID] = stdRation;
  348. }
  349. //判断定额完整性
  350. if(!rationAllExist(rationItems, stdRationIndex)){
  351. //建定额链, 排序后再清除不存在的定额,保证顺序正确性
  352. rationItems = chainToArr(rationItems);
  353. //清除已被删除的定额
  354. let removeIds = [];
  355. _.remove(rationItems, function (item) {
  356. if(!stdRationIndex[item.rationID]){
  357. removeIds.push(item.ID);
  358. return true;
  359. }
  360. return false;
  361. });
  362. _.remove(items, function (item) {
  363. return removeIds.includes(item.ID);
  364. });
  365. await billsGuideItemsModel.remove({ID: {$in: removeIds}});
  366. //重组树结构
  367. let bulkArr = [];
  368. for(let i = 0, len = rationItems.length; i < len; i++){
  369. rationItems[i].NextSiblingID = rationItems[i + 1] ? rationItems[i + 1].ID : -1;
  370. bulkArr.push({updateOne: {filter: {ID: rationItems[i].ID}, update: {$set: {NextSiblingID: rationItems[i].NextSiblingID}}}});
  371. }
  372. await billsGuideItemsModel.bulkWrite(bulkArr);
  373. }
  374. return items;
  375. }
  376. async function updateItems(updateDatas) {
  377. let bulkArr = [];
  378. for(let updateData of updateDatas){
  379. if(updateData.updateType === 'create'){
  380. bulkArr.push({insertOne: {document: updateData.updateData}});
  381. }
  382. else if(updateData.updateType === 'update'){
  383. bulkArr.push({updateOne: {filter: updateData.findData, update: {$set: updateData.updateData}}});
  384. }
  385. else{
  386. bulkArr.push({deleteOne: {filter: updateData.findData}});
  387. }
  388. }
  389. if(bulkArr.length > 0){
  390. await billsGuideItemsModel.bulkWrite(bulkArr);
  391. }
  392. }
  393. // 获取清单材料数据
  394. async function getBillMaterials(libID, billID) {
  395. // 指引下已有定额人材机(材料大类)
  396. let allGljList = [];
  397. const rationItems = await billsGuideItemsModel.find({ libID, billsID: billID, rationID: { $ne: null } }, '-_id rationID').lean();
  398. if (rationItems.length) {
  399. const rationIDs = rationItems.map(item => item.rationID);
  400. const rations = await stdRationModel.find({ ID: { $in: rationIDs } }, '-_id rationGljList');
  401. const gljIDs = [];
  402. rations.forEach(ration => {
  403. if (ration.rationGljList && ration.rationGljList.length) {
  404. gljIDs.push(...ration.rationGljList.map(rGlj => rGlj.gljId));
  405. }
  406. });
  407. if (gljIDs.length) {
  408. allGljList = await gljModel.find({ ID: { $in: [...new Set(gljIDs)] } }, '-_id ID code name specs gljType').lean();
  409. allGljList = allGljList.filter(glj => /^2/.test(glj.gljType) || [4, 5].includes(glj.gljType));
  410. }
  411. }
  412. // 清单材料
  413. let billMaterials = [];
  414. const billMaterial = await billMaterialModel.findOne({ libID, billID }).lean();
  415. if (!billMaterial || !billMaterial.materials) {
  416. return {
  417. billMaterials,
  418. allGljList
  419. };
  420. }
  421. const gljIDs = billMaterial.materials.map(m => m.gljID);
  422. const gljList = await gljModel.find({ ID: { $in: gljIDs } }, '-_id ID code name specs').lean();
  423. billMaterials = gljList.map(glj => ({ gljID: glj.ID, code: glj.code, name: glj.name, specs: glj.specs }));
  424. return {
  425. billMaterials,
  426. allGljList
  427. }
  428. }
  429. // 编辑清单材料数据,返回清单材料数据
  430. async function editBillMaterials(libID, billID, gljCodes, compilationID) {
  431. const gljLib = await gljLibModel.findOne({ compilationId: compilationID }, '-_id ID').lean();
  432. const gljList = await gljModel.find({ repositoryId: gljLib.ID, code: { $in: gljCodes }, }, '-_id ID code name specs').lean();
  433. const gljMap = {};
  434. const materials = [];
  435. gljList.forEach(glj => {
  436. materials.push({ gljID: glj.ID });
  437. gljMap[glj.code] = 1;
  438. });
  439. const missCodes = gljCodes.filter(code => !gljMap[code]);
  440. if (missCodes.length) {
  441. throw new Error(`没有找到人材机:<br/>${missCodes.join('<br/>')}`);
  442. }
  443. const billMaterial = await billMaterialModel.findOne({ libID, billID }, '-_id ID').lean();
  444. if (billMaterial) {
  445. await billMaterialModel.update({ ID: billMaterial.ID }, { $set: { materials } });
  446. } else {
  447. await billMaterialModel.create({ libID, billID, ID: uuidV1(), materials });
  448. }
  449. return gljList.map(glj => ({ gljID: glj.ID, code: glj.code, name: glj.name, specs: glj.specs }));
  450. }
  451. // 是否为工序行
  452. function isProcessNode(node) {
  453. return node && node.depth() % 2 === 0 && node.data.type === 0
  454. }
  455. // 是否是选项行
  456. function isOptionNode(node) {
  457. return node && node.depth() % 2 === 1 && node.data.type === 0
  458. }
  459. // 判断蓝色子项和孙子项是否打勾了必填
  460. function hasRequireData(node) {
  461. const requiredList = node.getPosterity().filter(subNode =>
  462. subNode.data.required === true
  463. );
  464. if (requiredList.length) { return true }
  465. return false;
  466. }
  467. // 这里判断有无无定额的情况,有的就返回true,没有就返回false
  468. function isAllRationData(node) {
  469. let isRequired = true;
  470. if (node.children && node.children.length) {
  471. node.children.forEach(subNode => {
  472. if (!subNode.children || !subNode.children.length) {
  473. isRequired = false;
  474. }
  475. })
  476. }
  477. //这里是兼容第一层直接是定额的白色节点
  478. if (node.children && node.children.length) {
  479. node.children.forEach(subNode => {
  480. if (subNode.data.rationID) {
  481. isRequired = true;
  482. }
  483. })
  484. }
  485. return isRequired;
  486. }
  487. // 获取选套定额
  488. function getOptionalData(node, list = []) {
  489. if (isProcessNode(node)) {
  490. node.children.forEach(element => {
  491. if (element.children && element.children.length) {
  492. element.children.forEach(item => {
  493. if (item.data.rationID) {
  494. list.push(item.data.rationID);
  495. } else if (isProcessNode(item)) {
  496. getOptionalData(item, list)
  497. }
  498. })
  499. }
  500. });
  501. } else {
  502. node.children.forEach(element => {
  503. if (element.data.rationID) {
  504. list.push(element.data.rationID);
  505. }
  506. });
  507. }
  508. return list;
  509. }
  510. function getItemData(nodes, requireRationData={}, optionalRationData={}, classGroups={}, prefixID = '', prefixSonID = '',IDData={}) {
  511. const processNodes = nodes.filter(node => isProcessNode(node));
  512. // const classGroups = []; // 同层必填选项的数组(二维数组)
  513. processNodes.forEach(processNode => {
  514. // 蓝色节点,必填
  515. if (processNode.data.required) {
  516. // 白色节点
  517. const optionNodes = processNode.children.filter(node => isOptionNode(node));
  518. optionNodes.forEach(optionNode => {
  519. if (!requireRationData[optionNode.data.ID]) requireRationData[optionNode.data.ID] = [];
  520. if (!optionalRationData[optionNode.data.ID]) optionalRationData[optionNode.data.ID] = [];
  521. //白色节点下没有蓝色节点,就是到底了
  522. if (!optionNode.children.some(subOptionNode => isProcessNode(subOptionNode))) {
  523. // 是否必套定额
  524. if (isAllRationData(optionNode)) {
  525. optionNode.children.forEach(subOptionNode => {
  526. requireRationData[optionNode.data.ID].push([subOptionNode.data.rationID]);
  527. })
  528. } else {
  529. optionalRationData[optionNode.data.ID] = getOptionalData(optionNode);
  530. }
  531. const kV = {};
  532. kV[optionNode.data.ID] = optionNode.data.name;
  533. Object.assign(classGroups, kV);
  534. } else {
  535. const kV = {};
  536. kV[optionNode.data.ID] = optionNode.data.name;
  537. Object.assign(classGroups, kV);
  538. // 后代项是否有必填
  539. if (hasRequireData(optionNode)) {
  540. //后代项有必填
  541. prefixSonID='';
  542. getItemData(optionNode.children, requireRationData, optionalRationData, classGroups, optionNode.data.ID,prefixSonID,IDData);
  543. } else {
  544. //后代项无必填
  545. optionNode.children.forEach(subOptionNode => {
  546. // 是否必套定额
  547. if (isAllRationData(optionNode)) {
  548. if (!requireRationData[subOptionNode.parent.data.ID]) requireRationData[subOptionNode.parent.data.ID] = [];
  549. requireRationData[subOptionNode.parent.data.ID].push(getOptionalData(subOptionNode));
  550. } else {
  551. if (!optionalRationData[subOptionNode.parent.data.ID]) optionalRationData[subOptionNode.parent.data.ID] = [];
  552. optionalRationData[subOptionNode.parent.data.ID].push(...getOptionalData(subOptionNode));
  553. }
  554. })
  555. }
  556. }
  557. })
  558. } else {
  559. // 蓝色节点,非必填
  560. if (hasRequireData(processNode)) {
  561. //后代项有必填
  562. if(isProcessNode(processNode)){
  563. //蓝色
  564. processNode.children.forEach((subProcessNode)=>{
  565. subProcessNode.children.forEach((sSubProcessNode)=>{
  566. //这里是特殊处理,因为原来的逻辑是直接把定额绑到必填白色选项中下面的,每个蓝色的一组,但是这样是不对的,需要绑定在必填白色选项下的蓝色节点,所以这里就需要传入蓝色节点的id
  567. const requireChildrenID=sSubProcessNode.parent.data.required?prefixSonID:sSubProcessNode.data.ID;
  568. IDData[sSubProcessNode.data.ID]=prefixID;
  569. getItemData(
  570. [sSubProcessNode],
  571. requireRationData,
  572. optionalRationData,
  573. classGroups,
  574. prefixID,
  575. requireChildrenID,
  576. IDData
  577. )
  578. })
  579. })
  580. }
  581. } else {
  582. let key = processNode.data.ID;
  583. if (prefixID) key = prefixID;
  584. if (prefixSonID) key = prefixSonID;
  585. // 是否必套定额
  586. if (isAllRationData(processNode)) {
  587. if (!requireRationData[key]) requireRationData[key] = [];
  588. requireRationData[key].push(getOptionalData(processNode));
  589. } else {
  590. if (!optionalRationData[key]) optionalRationData[key] = [];
  591. optionalRationData[key].push(...getOptionalData(processNode));
  592. }
  593. }
  594. }
  595. })
  596. return { requireRationData, optionalRationData, classGroups,IDData}
  597. }
  598. // 从指引节点,获取分类特征、必套定额数据
  599. function getItemClassData(nodes, prefix,
  600. prefixID) {
  601. const processNodes = nodes.filter(node => isProcessNode(node));
  602. const classGroups = []; // 同层必填选项的数组(二维数组)
  603. processNodes.forEach(processNode => {
  604. const classItems = [];
  605. const optionNodes = processNode.children.filter(node => isOptionNode(node));
  606. optionNodes.forEach(optionNode => {
  607. // const name = prefix ? `${prefix}@${optionNode.data.name}` : optionNode.data.name;
  608. if (optionNode.parent && optionNode.parent.data.required && (!optionNode.children
  609. || !optionNode.children.length
  610. || (optionNode.children[0].data && optionNode.children[0].data.rationID)
  611. || !optionNode.children.some(node => isProcessNode(node)))) {
  612. // 必套定额
  613. classItems.push({ name: optionNode.data.name, ID: optionNode.data.ID });
  614. } else {
  615. // classItems.push(...getItemCharacterData(optionNode.children, optionNode.parent && optionNode.parent.data.required ? optionNode.data.name : ''));
  616. const childrenClassItem = getItemClassData(
  617. optionNode.children,
  618. optionNode.parent && optionNode.parent.data.required ? optionNode.data.name : '' ,
  619. optionNode.parent && optionNode.parent.data.required ? optionNode.data.ID : ''
  620. );
  621. //如果返回的子项为空,但是父项又勾选了必填,则要把本身存入数组
  622. if (optionNode.parent
  623. && optionNode.parent.data.required
  624. && childrenClassItem.length === 0
  625. ) {
  626. classItems.push({ name: optionNode.data.name,ID: optionNode.data.ID });
  627. } else {
  628. classItems.push(...childrenClassItem);
  629. }
  630. }
  631. });
  632. if (classItems.length) {
  633. classGroups.push(classItems);
  634. }
  635. });
  636. // 拼接上一文本
  637. if (classGroups[0] && classGroups[0].length) {
  638. // classGroups[0] = classGroups[0].map(name => prefix ? `${prefix}@${name}` : name);
  639. classGroups[0] = classGroups[0].map(item => {
  640. item.name = prefix ? `${prefix}@${item.name}` : item.name
  641. item.ID = prefixID ? `${prefixID}@${item.ID}` : item.ID
  642. return item;
  643. });
  644. }
  645. // 二维数组内容排列组合
  646. while (classGroups.length > 1) {
  647. const prevClassItems = classGroups[0];
  648. const nextClassItems = classGroups[1];
  649. const mergedClassItems = [];
  650. for (let i = 0; i < prevClassItems.length; i++) {
  651. for (let j = 0; j < nextClassItems.length; j++) {
  652. // 拼接文本
  653. const mergedName = `${prevClassItems[i].name}@${nextClassItems[j].name}`;
  654. const mergedID = `${prevClassItems[i].ID}@${nextClassItems[j].ID}`;
  655. mergedClassItems.push({ name: mergedName,ID:mergedID});
  656. }
  657. }
  658. classGroups.splice(0, 2, mergedClassItems);
  659. }
  660. // 去重(类别别名要唯一)
  661. const items = classGroups[0] || [];
  662. const nameMap = {};
  663. const rst = [];
  664. items.forEach(item => {
  665. if (!nameMap[item.name]) {
  666. rst.push(item);
  667. }
  668. nameMap[item.name] = true;
  669. });
  670. return rst;
  671. }
  672. // 获取选套定额:把所有分类数据的必套定额确定好了先。选套定额就是清单下所有定额除了必套的
  673. function getOptionalRationIDs(optionalRationData) {
  674. const optionalRationIDs=[];
  675. Object.values(optionalRationData).forEach(optionalRation=>{
  676. if(optionalRation.length) optionalRationIDs.push(...optionalRation);
  677. })
  678. return [...new Set(optionalRationIDs)];
  679. }
  680. // 获取错套定额:清单下所有定额,除了分类对应的必套、选套定额
  681. function getErrorRationIDs(requiredRationIDList, optionalRationIDs, allRationIDs) {
  682. const finRequireData=[];
  683. requiredRationIDList.forEach(requiredRationIDs=>{
  684. finRequireData.push(...requiredRationIDs);
  685. })
  686. const errorRationIDs = [];
  687. allRationIDs.forEach(rationID => {
  688. if (!finRequireData.includes(rationID) && !optionalRationIDs.includes(rationID)) {
  689. errorRationIDs.push(rationID);
  690. }
  691. });
  692. return [...new Set(errorRationIDs)];
  693. }
  694. //把classcode和必套选套定额结合在一起
  695. function combineData(codeData, requireRationData, optionalRationData, classGroups, IDData) {
  696. // 这里要记录下已经被绑定的选套定额,因为没有被用的定额需要绑定到各个classcode下
  697. const matchRationList = [];
  698. //这里需要把绑定在子节点的定额更新到必填的白色选项中(classcode的值)
  699. const requireCombineData = {};
  700. const optionCombineData = {};
  701. Object.keys(IDData).forEach(key => {
  702. if (!requireCombineData[IDData[key]]) requireCombineData[IDData[key]] = new Set();
  703. if (!optionCombineData[IDData[key]]) optionCombineData[IDData[key]] = new Set();
  704. if (requireRationData[key]) {
  705. requireRationData[key].forEach(subData => {
  706. subData.forEach(subItem => {
  707. requireCombineData[IDData[key]].add(subItem);
  708. })
  709. })
  710. }
  711. if (optionalRationData[key]) {
  712. optionalRationData[key].forEach(subData => {
  713. optionCombineData[IDData[key]].add(subData);
  714. })
  715. }
  716. })
  717. const finData = codeData.map(classCodeData => {
  718. const errorRationIDs = [];
  719. const optionalRationIDs = [];
  720. const requiredRationIDs = [];
  721. let name = '';
  722. const classCodeIDs = classCodeData.ID;
  723. if (/@/.test(classCodeIDs)) {
  724. classCodeIDs.split('@').forEach((classCodeID) => {
  725. if (name) {
  726. name = name + '@' + classGroups[classCodeID]
  727. } else {
  728. name = classGroups[classCodeID]
  729. };
  730. // 一组的必套定额,先去重
  731. const unitRation = [];
  732. requireRationData[classCodeID].forEach(subItem => {
  733. unitRation.push(...new Set(subItem));
  734. })
  735. // 这里是必填选项下绑定必套定额
  736. if (requireRationData[classCodeID] && requireRationData[classCodeID].length) {
  737. requiredRationIDs.push(unitRation);
  738. }
  739. //这里是必填选项下绑定在蓝色节点下的必套定额
  740. if (requireCombineData[classCodeID] && requireCombineData[classCodeID].size) {
  741. requiredRationIDs.push([...requireCombineData[classCodeID]]);
  742. }
  743. // 这里是必填选项下绑定选套定额
  744. if (optionalRationData[classCodeID] && optionalRationData[classCodeID].length) {
  745. optionalRationIDs.push(...optionalRationData[classCodeID]);
  746. matchRationList.push(...optionalRationData[classCodeID]);
  747. }
  748. //这里是必填选项下绑定在蓝色节点下的选套定额,下同
  749. if (optionCombineData[classCodeID] && optionCombineData[classCodeID].size) {
  750. optionalRationIDs.push(...optionCombineData[classCodeID]);
  751. matchRationList.push(...optionCombineData[classCodeID]);
  752. }
  753. })
  754. return { name, requiredRationIDs, optionalRationIDs: [...new Set(optionalRationIDs)], errorRationIDs }
  755. } else {
  756. const unitRation = [];
  757. requireRationData[classCodeIDs].forEach(subItem => {
  758. unitRation.push(...new Set(subItem));
  759. })
  760. name = classGroups[classCodeIDs];
  761. if (requireRationData[classCodeIDs] && requireRationData[classCodeIDs].length) requiredRationIDs.push(unitRation);
  762. if (requireCombineData[classCodeIDs] && requireCombineData[classCodeIDs].size) requiredRationIDs.push([...requireCombineData[classCodeIDs]]);
  763. if (optionalRationData[classCodeIDs] && optionalRationData[classCodeIDs].length) {
  764. optionalRationIDs.push(...optionalRationData[classCodeIDs]);
  765. matchRationList.push(...optionalRationData[classCodeIDs]);
  766. }
  767. if (optionCombineData[classCodeIDs] && optionCombineData[classCodeIDs].size) {
  768. optionalRationIDs.push(...optionCombineData[classCodeIDs]);
  769. matchRationList.push(...optionalRationData[classCodeIDs]);
  770. }
  771. return { name, requiredRationIDs, optionalRationIDs: [...new Set(optionalRationIDs)], errorRationIDs }
  772. }
  773. })
  774. const unMatchRation = [];
  775. Object.values(optionalRationData).forEach(data => {
  776. data.forEach((rationID) => {
  777. if (!matchRationList.includes(rationID)) {
  778. unMatchRation.push(rationID);
  779. }
  780. })
  781. })
  782. return { itemClassData: finData, unMatchRation };
  783. }
  784. // 生成清单分类
  785. async function generateClassData(libID) {
  786. const lib = await billsGuideLibModel.findOne({ ID: libID }).lean();
  787. if (!lib) {
  788. throw new Error('无有效精灵库');
  789. }
  790. const guidanceItems = await billsGuideItemsModel.find({ libID }, '-_id').lean();
  791. // 清单ID - 指引数据映射
  792. const guidanceMap = {};
  793. guidanceItems.forEach(item => {
  794. (guidanceMap[item.billsID] || (guidanceMap[item.billsID] = [])).push(item);
  795. });
  796. const bills = await stdBillsModel.find({ billsLibId: lib.billsLibId }, '-_id ID ParentID NextSiblingID name code').lean();
  797. const billTree = idTree.createNew({id: 'ID', pid: 'ParentID', nid: 'NextSiblingID', rootId: -1, autoUpdate: true});
  798. billTree.loadDatas(bills);
  799. // 叶子清单
  800. const leaves = billTree.items.filter(node => !node.children || !node.children.length);
  801. // 获取分类数据
  802. let classNum = 1;
  803. const billClassData = [];
  804. for(let billNode of leaves){
  805. const guidanceItems = guidanceMap[billNode.data.ID];
  806. if (!guidanceItems || !guidanceItems.length) {
  807. continue;
  808. }
  809. if(billNode.data.code.startsWith('03')) continue;//先屏蔽掉03开头的清单
  810. const guidanceTree = idTree.createNew({id: 'ID', pid: 'ParentID', nid: 'NextSiblingID', rootId: -1, autoUpdate: true});
  811. guidanceTree.loadDatas(guidanceItems);
  812. //console.log('getItemClassData start',billNode.data.name,billNode.data.code,billNode.data.ID);
  813. const classCodeData = getItemClassData(guidanceTree.roots); // 必套定额在这个方法内就获取了,避免重复执行递归方法
  814. const {requireRationData,optionalRationData,classGroups,IDData} = getItemData(guidanceTree.roots);
  815. const {itemClassData,unMatchRation}= combineData(classCodeData,requireRationData,optionalRationData,classGroups,IDData);
  816. const allRationIDs = guidanceTree.items.filter(node => !!node.data.rationID).map(node => node.data.rationID);
  817. // 选套定额ID
  818. const optionalRationIDs = getOptionalRationIDs(itemClassData, allRationIDs);
  819. //if(itemClassData.length > 1000) console.log('getItemClassData end',billNode.data.name,billNode.data.code,billNode.data.ID,itemClassData.length)
  820. itemClassData.forEach(item => {
  821. // 错套定额
  822. item.optionalRationIDs.push(...unMatchRation);
  823. const errorRationIDs = getErrorRationIDs(item.requiredRationIDs, item.optionalRationIDs, allRationIDs);
  824. if(billNode.data.ID == '1d32fa34-0a9b-11ea-a33d-5388f9783b09') console.log(item.name)
  825. billClassData.push({
  826. itemCharacter: item.name,
  827. class: classNum++,
  828. classCode: `${billNode.data.code}@${item.name}`,
  829. compilationID: lib.compilationId,
  830. name: billNode.data.name,
  831. code: billNode.data.code,
  832. requiredRationIDs: item.requiredRationIDs || [],
  833. optionalRationIDs:item.optionalRationIDs || [],
  834. errorRationIDs,
  835. });
  836. });
  837. //新增无必填时的情况
  838. if(itemClassData.length===0){
  839. Object.keys(requireRationData).forEach((key)=>{
  840. requireRationData[key].forEach(data=>{
  841. if(data.length) optionalRationIDs.push(...data);
  842. })
  843. })
  844. const errorRationIDs = getErrorRationIDs([], optionalRationIDs, allRationIDs);
  845. billClassData.push({
  846. itemCharacter: '',
  847. class: classNum++,
  848. classCode: `${billNode.data.code}`,
  849. compilationID: lib.compilationId,
  850. name: billNode.data.name,
  851. code: billNode.data.code,
  852. requiredRationIDs: [],
  853. optionalRationIDs:optionalRationIDs || [],
  854. errorRationIDs,
  855. });
  856. }
  857. }
  858. console.log(`billClassData.length`);
  859. console.log(billClassData.length);
  860. // 清空旧的分类数据
  861. await billClassModel.deleteMany({ compilationID: lib.compilationId });
  862. // 之前遇到一次性插入40w条数据的情况,会卡死,循环插入速度快很多
  863. while (billClassData.length > 10000){
  864. const list = billClassData.splice(0,10000);
  865. await billClassModel.insertMany(list);
  866. }
  867. await billClassModel.insertMany(billClassData);
  868. }
  869. // 获取分类excel数据
  870. async function getClassExcelData(libID) {
  871. const lib = await billsGuideLibModel.findOne({ ID: libID }, '-_id compilationId').lean();
  872. if (!lib) {
  873. throw new Error('无有效精灵库');
  874. }
  875. console.log('start');
  876. const date = Date.now();
  877. const classData = await billClassModel.find({ compilationID: lib.compilationId }).lean();
  878. console.log('end');
  879. console.log(Date.now() -date);
  880. const excelData = [['类别', '编码', '清单名称', '必填特征排列组合', '类别别名', '必套定额', '选套定额', '错套定额']];
  881. classData.forEach(item => {
  882. const excelItem = [
  883. item.class,
  884. item.code,
  885. item.name,
  886. item.itemCharacter,
  887. item.classCode,
  888. (item.requiredRationIDs || []).join('@'),
  889. (item.optionalRationIDs || []).join('@'),
  890. (item.errorRationIDs || []).join('@'),
  891. ];
  892. excelData.push(excelItem);
  893. });
  894. return excelData;
  895. }
  896. async function testItems(libID) {
  897. let items = await billsGuideItemsModel.find({libID: libID});
  898. //删除垃圾数据
  899. let delBulk = [];
  900. let itemsMapping = {};
  901. for(let item of items){
  902. itemsMapping[item.ID] = true;
  903. }
  904. for(let item of items){
  905. if(item.ParentID != -1 && !itemsMapping[item.ParentID]){
  906. delBulk.push({
  907. deleteOne: {
  908. filter: {ID: item.ID}
  909. }
  910. });
  911. }
  912. }
  913. if(delBulk.length > 0){
  914. console.log(`delBulk.length`);
  915. console.log(delBulk.length);
  916. await billsGuideItemsModel.bulkWrite(delBulk);
  917. }
  918. /* //查找同层节点含有相同NextSiblingID的节点
  919. let rst = [];
  920. let billsGroup = {};
  921. for(let item of items){
  922. if(!billsGroup[item.billsID]){
  923. billsGroup[item.billsID] = [item];
  924. }
  925. else {
  926. billsGroup[item.billsID].push(item);
  927. }
  928. }
  929. for(let bGroup in billsGroup){
  930. let group = billsGroup[bGroup];
  931. let parentGroup = {};
  932. for(let gItem of group){
  933. if(!parentGroup[gItem.ParentID]){
  934. parentGroup[gItem.ParentID] = [gItem]
  935. }
  936. else {
  937. parentGroup[gItem.ParentID].push(gItem);
  938. }
  939. }
  940. for(let pGroup in parentGroup){
  941. let pGroupData = parentGroup[pGroup];
  942. let nextGroup = {};
  943. for(let nItem of pGroupData){
  944. let sameNext = _.filter(pGroupData, {NextSiblingID: nItem.NextSiblingID});
  945. if(sameNext.length > 1){
  946. console.log(`sameNext`);
  947. console.log(sameNext);
  948. if(!nextGroup[nItem.ParentID + nItem.NextSiblingID]){
  949. rst.push({NextSiblingID: nItem.NextSiblingID, ParentID: nItem.ParentID});
  950. nextGroup[nItem.ParentID + nItem.NextSiblingID] = 1;
  951. }
  952. }
  953. }
  954. }
  955. }*/
  956. return delBulk.length;
  957. }