facades.js 50 KB

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