facades.js 44 KB

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