facades.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727
  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 getItemClassData(nodes, prefix) {
  461. const processNodes = nodes.filter(node => isProcessNode(node));
  462. const classGroups = []; // 同层必填选项的数组(二维数组)
  463. processNodes.forEach(processNode => {
  464. const classItems = [];
  465. const optionNodes = processNode.children.filter(node => isOptionNode(node));
  466. optionNodes.forEach(optionNode => {
  467. if (optionNode.parent && optionNode.parent.data.required && (!optionNode.children
  468. || !optionNode.children.length
  469. || (optionNode.children[0].data && optionNode.children[0].data.rationID)
  470. || !optionNode.children.some(node => isProcessNode(node)))) {
  471. // 必套定额
  472. const requiredRationIDs = optionNode.children && optionNode.children.length ?
  473. optionNode.children.filter(node => !!node.data.rationID).map(node => node.data.rationID) : [];
  474. classItems.push({ name: optionNode.data.name, requiredRationIDs });
  475. } else {
  476. classItems.push(...getItemClassData(optionNode.children, optionNode.parent && optionNode.parent.data.required ? optionNode.data.name : ''));
  477. }
  478. });
  479. if (classItems.length) {
  480. classGroups.push(classItems);
  481. }
  482. });
  483. // 拼接上一文本
  484. if (classGroups[0] && classGroups[0].length) {
  485. classGroups[0] = classGroups[0].map(item => {
  486. item.name = prefix ? `${prefix}@${item.name}` : item.name
  487. return item;
  488. });
  489. }
  490. // 二维数组内容排列组合
  491. while (classGroups.length > 1) {
  492. const prevClassItems = classGroups[0];
  493. const nextClassItems = classGroups[1];
  494. const mergedClassItems = [];
  495. for (let i = 0; i < prevClassItems.length; i++) {
  496. for (let j = 0; j < nextClassItems.length; j++) {
  497. // 拼接文本
  498. const mergedName = `${prevClassItems[i].name}@${nextClassItems[j].name}`;
  499. // 拼接必套定额
  500. const mergedRationIDs = [...prevClassItems[i].requiredRationIDs, ...nextClassItems[j].requiredRationIDs];
  501. mergedClassItems.push({name: mergedName, requiredRationIDs: mergedRationIDs});
  502. }
  503. }
  504. classGroups.splice(0, 2, mergedClassItems);
  505. }
  506. // 去重(类别别名要唯一)
  507. const items = classGroups[0] || [];
  508. const nameMap = {};
  509. const rst = [];
  510. items.forEach(item => {
  511. if (!nameMap[item.name]) {
  512. rst.push(item);
  513. }
  514. nameMap[item.name] = true;
  515. });
  516. return rst;
  517. }
  518. // 获取选套定额:把所有分类数据的必套定额确定好了先。选套定额就是清单下所有定额除了必套的
  519. function getOptionalRationIDs(itemClassData, allRationIDs) {
  520. // 所有必套定额
  521. let requiredRationIDs = [];
  522. itemClassData.forEach(item => {
  523. if (item.requiredRationIDs) {
  524. requiredRationIDs.push(...item.requiredRationIDs);
  525. }
  526. });
  527. requiredRationIDs = [...new Set(requiredRationIDs)];
  528. // 选套定额就是清单下所有定额除了必套的
  529. const optionalRationIDs = [];
  530. allRationIDs.forEach(rationID => {
  531. if (!requiredRationIDs.includes(rationID)) {
  532. optionalRationIDs.push(rationID);
  533. }
  534. });
  535. return [...new Set(optionalRationIDs)];
  536. }
  537. // 获取错套定额:清单下所有定额,除了分类对应的必套、选套定额
  538. function getErrorRationIDs(requiredRationIDs, optionalRationIDs, allRationIDs) {
  539. const errorRationIDs = [];
  540. allRationIDs.forEach(rationID => {
  541. if (!requiredRationIDs.includes(rationID) && !optionalRationIDs.includes(rationID)) {
  542. errorRationIDs.push(rationID);
  543. }
  544. });
  545. return [...new Set(errorRationIDs)];
  546. }
  547. // 生成清单分类
  548. async function generateClassData(libID) {
  549. const lib = await billsGuideLibModel.findOne({ ID: libID }).lean();
  550. if (!lib) {
  551. throw new Error('无有效精灵库');
  552. }
  553. const guidanceItems = await billsGuideItemsModel.find({ libID }, '-_id').lean();
  554. // 清单ID - 指引数据映射
  555. const guidanceMap = {};
  556. guidanceItems.forEach(item => {
  557. (guidanceMap[item.billsID] || (guidanceMap[item.billsID] = [])).push(item);
  558. });
  559. const bills = await stdBillsModel.find({ billsLibId: lib.billsLibId }, '-_id ID ParentID NextSiblingID name code').lean();
  560. const billTree = idTree.createNew({id: 'ID', pid: 'ParentID', nid: 'NextSiblingID', rootId: -1, autoUpdate: true});
  561. billTree.loadDatas(bills);
  562. // 叶子清单
  563. const leaves = billTree.items.filter(node => !node.children || !node.children.length);
  564. // 获取分类数据
  565. let classNum = 1;
  566. const billClassData = [];
  567. leaves.forEach(billNode => {
  568. const guidanceItems = guidanceMap[billNode.data.ID];
  569. if (!guidanceItems || !guidanceItems.length) {
  570. return;
  571. }
  572. const guidanceTree = idTree.createNew({id: 'ID', pid: 'ParentID', nid: 'NextSiblingID', rootId: -1, autoUpdate: true});
  573. guidanceTree.loadDatas(guidanceItems);
  574. const itemClassData = getItemClassData(guidanceTree.roots); // 必套定额在这个方法内就获取了,避免重复执行递归方法
  575. const allRationIDs = guidanceTree.items.filter(node => !!node.data.rationID).map(node => node.data.rationID);
  576. // 选套定额ID
  577. const optionalRationIDs = getOptionalRationIDs(itemClassData, allRationIDs);
  578. itemClassData.forEach(item => {
  579. // 错套定额
  580. const errorRationIDs = getErrorRationIDs(item.requiredRationIDs, optionalRationIDs, allRationIDs);
  581. billClassData.push({
  582. itemCharacter: item.name,
  583. class: classNum++,
  584. classCode: `${billNode.data.code}@${item.name}`,
  585. compilationID: lib.compilationId,
  586. name: billNode.data.name,
  587. code: billNode.data.code,
  588. requiredRationIDs: item.requiredRationIDs || [],
  589. optionalRationIDs,
  590. errorRationIDs,
  591. });
  592. });
  593. });
  594. console.log(`billClassData.length`);
  595. console.log(billClassData.length);
  596. // 清空旧的分类数据
  597. await billClassModel.deleteMany({ compilationID: lib.compilationId });
  598. // 之前遇到一次性插入40w条数据的情况,会卡死,循环插入速度快很多
  599. while (billClassData.length > 10000){
  600. const list = billClassData.splice(0,10000);
  601. await billClassModel.insertMany(list);
  602. }
  603. await billClassModel.insertMany(billClassData);
  604. }
  605. // 获取分类excel数据
  606. async function getClassExcelData(libID) {
  607. const lib = await billsGuideLibModel.findOne({ ID: libID }, '-_id compilationId').lean();
  608. if (!lib) {
  609. throw new Error('无有效精灵库');
  610. }
  611. console.log('start');
  612. const date = Date.now();
  613. const classData = await billClassModel.find({ compilationID: lib.compilationId }).lean();
  614. console.log('end');
  615. console.log(Date.now() -date);
  616. const excelData = [['类别', '编码', '清单名称', '必填特征排列组合', '类别别名', '必套定额', '选套定额', '错套定额']];
  617. classData.forEach(item => {
  618. const excelItem = [
  619. item.class,
  620. item.code,
  621. item.name,
  622. item.itemCharacter,
  623. item.classCode,
  624. (item.requiredRationIDs || []).join('@'),
  625. (item.optionalRationIDs || []).join('@'),
  626. (item.errorRationIDs || []).join('@'),
  627. ];
  628. excelData.push(excelItem);
  629. });
  630. return excelData;
  631. }
  632. async function testItems(libID) {
  633. let items = await billsGuideItemsModel.find({libID: libID});
  634. //删除垃圾数据
  635. let delBulk = [];
  636. let itemsMapping = {};
  637. for(let item of items){
  638. itemsMapping[item.ID] = true;
  639. }
  640. for(let item of items){
  641. if(item.ParentID != -1 && !itemsMapping[item.ParentID]){
  642. delBulk.push({
  643. deleteOne: {
  644. filter: {ID: item.ID}
  645. }
  646. });
  647. }
  648. }
  649. if(delBulk.length > 0){
  650. console.log(`delBulk.length`);
  651. console.log(delBulk.length);
  652. await billsGuideItemsModel.bulkWrite(delBulk);
  653. }
  654. /* //查找同层节点含有相同NextSiblingID的节点
  655. let rst = [];
  656. let billsGroup = {};
  657. for(let item of items){
  658. if(!billsGroup[item.billsID]){
  659. billsGroup[item.billsID] = [item];
  660. }
  661. else {
  662. billsGroup[item.billsID].push(item);
  663. }
  664. }
  665. for(let bGroup in billsGroup){
  666. let group = billsGroup[bGroup];
  667. let parentGroup = {};
  668. for(let gItem of group){
  669. if(!parentGroup[gItem.ParentID]){
  670. parentGroup[gItem.ParentID] = [gItem]
  671. }
  672. else {
  673. parentGroup[gItem.ParentID].push(gItem);
  674. }
  675. }
  676. for(let pGroup in parentGroup){
  677. let pGroupData = parentGroup[pGroup];
  678. let nextGroup = {};
  679. for(let nItem of pGroupData){
  680. let sameNext = _.filter(pGroupData, {NextSiblingID: nItem.NextSiblingID});
  681. if(sameNext.length > 1){
  682. console.log(`sameNext`);
  683. console.log(sameNext);
  684. if(!nextGroup[nItem.ParentID + nItem.NextSiblingID]){
  685. rst.push({NextSiblingID: nItem.NextSiblingID, ParentID: nItem.ParentID});
  686. nextGroup[nItem.ParentID + nItem.NextSiblingID] = 1;
  687. }
  688. }
  689. }
  690. }
  691. }*/
  692. return delBulk.length;
  693. }