facades.js 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091
  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 = {
  236. libID: guidanceLibId, ID: uuidV1(), ParentID: -1, NextSiblingID: jobNoIndex[i - 1] ? jobNoIndex[i - 1]['ID'] : -1,
  237. name: jobIdIndex[bill.jobs[i]['id']]['content'], type: 0, billsID: bill.ID
  238. };
  239. jobNoIndex[i] = newItem;
  240. insertArr.push({ insertOne: { document: newItem } });
  241. }
  242. }
  243. await billsGuideItemsModel.bulkWrite(insertArr);
  244. }
  245. }
  246. async function initBillsGuideLib(updateData) {
  247. await billsGuideLibModel.create(updateData);
  248. let compilation = await compilationModel.findOne({ _id: mongoose.Types.ObjectId(updateData.compilationId) });
  249. if (compilation &&
  250. compilation.overWriteUrl &&
  251. compilation.overWriteUrl === '/web/over_write/js/chongqing_2018.js') {
  252. await genGuidanceItems_cq18(updateData.ID, updateData.billsLibId);
  253. } else {
  254. await genGuidanceItems(updateData.ID, updateData.billsLibId);
  255. }
  256. }
  257. async function updateBillsGuideLib(data) {
  258. if (data.updateType === 'delete') {
  259. //删除所有条目
  260. await billsGuideLibModel.remove(data.findData);
  261. await billsGuideItemsModel.remove({ libID: data.findData.ID });
  262. }
  263. else {
  264. await billsGuideLibModel.update(data.findData, { $set: data.updateData });
  265. await engLibModel.update({ 'billsGuidance_lib.id': data.findData.ID }, { $set: { 'billsGuidance_lib.$.name': data.updateData.name } }, { multi: true });
  266. }
  267. }
  268. async function getLibWithBills(libID) {
  269. let guidanceLib = await getBillsGuideLibs({ ID: libID });
  270. if (guidanceLib.length === 0) {
  271. throw '不存在此指引库!';
  272. }
  273. let billsLib = await stdBillsLibModel.findOne({ billsLibId: guidanceLib[0].billsLibId });
  274. if (!billsLib) {
  275. throw '引用的清单规则库不存在!';
  276. }
  277. let bills = await stdBillsModel.find({ billsLibId: billsLib.billsLibId }, '-_id code name ID NextSiblingID ParentID jobs items comment').lean();
  278. const guideItems = await billsGuideItemsModel.find({ libID: guidanceLib[0].ID }, '-_id billsID').lean();
  279. const billsMap = {};
  280. for (const item of guideItems) {
  281. billsMap[item.billsID] = true;
  282. }
  283. for (const item of bills) {
  284. if (billsMap[item.ID]) {
  285. item.hasGuide = true;
  286. }
  287. }
  288. return { guidanceLib: guidanceLib[0], bills };
  289. }
  290. function getAttrs(field, datas) {
  291. let rst = [];
  292. for (let data of datas) {
  293. if (data[field]) {
  294. rst.push(data[field]);
  295. }
  296. }
  297. return rst;
  298. }
  299. //定额项目指所引用定额是否被删除
  300. function rationAllExist(rationItems, stdRationIdx) {
  301. for (let item of rationItems) {
  302. if (!stdRationIdx[item.rationID]) {
  303. return false;
  304. }
  305. }
  306. return true;
  307. }
  308. //将同层树结构转为顺序数组
  309. function chainToArr(nodes) {
  310. let rst = [];
  311. let tempIdx = {};
  312. let nodeIdx = {};
  313. //建索引
  314. for (let node of nodes) {
  315. tempIdx[node.ID] = { ID: node.ID, NextSiblingID: node.NextSiblingID, preSibling: null, nextSibling: null };
  316. nodeIdx[node.ID] = node;
  317. }
  318. //建链
  319. for (let i in tempIdx) {
  320. let temp = tempIdx[i];
  321. if (temp.NextSiblingID != -1) {
  322. let next = tempIdx[temp.NextSiblingID];
  323. temp.nextSibling = next;
  324. next.preSibling = temp;
  325. }
  326. }
  327. let firstNode = null;
  328. for (let i in tempIdx) {
  329. if (!tempIdx[i].preSibling) {
  330. firstNode = tempIdx[i];
  331. break;
  332. }
  333. }
  334. //获得顺序队列
  335. while (firstNode) {
  336. rst.push(nodeIdx[firstNode.ID]);
  337. firstNode = firstNode.nextSibling;
  338. }
  339. return rst;
  340. }
  341. async function getItemsBybills(guidanceLibID, billsID) {
  342. const type = { job: 0, ration: 1 };
  343. let items = await billsGuideItemsModel.find({ libID: guidanceLibID, billsID: billsID, deleted: false });
  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. return items;
  377. }
  378. async function updateItems(updateDatas) {
  379. let bulkArr = [];
  380. for (let updateData of updateDatas) {
  381. if (updateData.updateType === 'create') {
  382. bulkArr.push({ insertOne: { document: updateData.updateData } });
  383. }
  384. else if (updateData.updateType === 'update') {
  385. bulkArr.push({ updateOne: { filter: updateData.findData, update: { $set: updateData.updateData } } });
  386. }
  387. else {
  388. bulkArr.push({ deleteOne: { filter: updateData.findData } });
  389. }
  390. }
  391. if (bulkArr.length > 0) {
  392. await billsGuideItemsModel.bulkWrite(bulkArr);
  393. }
  394. }
  395. // 获取清单材料数据
  396. async function getBillMaterials(libID, billID) {
  397. // 指引下已有定额人材机(材料大类)
  398. let allGljList = [];
  399. const rationItems = await billsGuideItemsModel.find({ libID, billsID: billID, rationID: { $ne: null } }, '-_id rationID').lean();
  400. if (rationItems.length) {
  401. const rationIDs = rationItems.map(item => item.rationID);
  402. const rations = await stdRationModel.find({ ID: { $in: rationIDs } }, '-_id rationGljList');
  403. const gljIDs = [];
  404. rations.forEach(ration => {
  405. if (ration.rationGljList && ration.rationGljList.length) {
  406. gljIDs.push(...ration.rationGljList.map(rGlj => rGlj.gljId));
  407. }
  408. });
  409. if (gljIDs.length) {
  410. allGljList = await gljModel.find({ ID: { $in: [...new Set(gljIDs)] } }, '-_id ID code name specs gljType').lean();
  411. allGljList = allGljList.filter(glj => /^2/.test(glj.gljType) || [4, 5].includes(glj.gljType));
  412. }
  413. }
  414. // 清单材料
  415. let billMaterials = [];
  416. const billMaterial = await billMaterialModel.findOne({ libID, billID }).lean();
  417. if (!billMaterial || !billMaterial.materials) {
  418. return {
  419. billMaterials,
  420. allGljList
  421. };
  422. }
  423. const gljIDs = billMaterial.materials.map(m => m.gljID);
  424. const gljList = await gljModel.find({ ID: { $in: gljIDs } }, '-_id ID code name specs').lean();
  425. billMaterials = gljList.map(glj => ({ gljID: glj.ID, code: glj.code, name: glj.name, specs: glj.specs }));
  426. return {
  427. billMaterials,
  428. allGljList
  429. }
  430. }
  431. // 编辑清单材料数据,返回清单材料数据
  432. async function editBillMaterials(libID, billID, gljCodes, compilationID) {
  433. const gljLib = await gljLibModel.findOne({ compilationId: compilationID }, '-_id ID').lean();
  434. const gljList = await gljModel.find({ repositoryId: gljLib.ID, code: { $in: gljCodes }, }, '-_id ID code name specs').lean();
  435. const gljMap = {};
  436. const materials = [];
  437. gljList.forEach(glj => {
  438. materials.push({ gljID: glj.ID });
  439. gljMap[glj.code] = 1;
  440. });
  441. const missCodes = gljCodes.filter(code => !gljMap[code]);
  442. if (missCodes.length) {
  443. throw new Error(`没有找到人材机:<br/>${missCodes.join('<br/>')}`);
  444. }
  445. const billMaterial = await billMaterialModel.findOne({ libID, billID }, '-_id ID').lean();
  446. if (billMaterial) {
  447. await billMaterialModel.update({ ID: billMaterial.ID }, { $set: { materials } });
  448. } else {
  449. await billMaterialModel.create({ libID, billID, ID: uuidV1(), materials });
  450. }
  451. return gljList.map(glj => ({ gljID: glj.ID, code: glj.code, name: glj.name, specs: glj.specs }));
  452. }
  453. // 是否为工序行
  454. function isProcessNode(node) {
  455. return node && node.depth() % 2 === 0 && node.data.type === 0
  456. }
  457. // 是否是选项行
  458. function isOptionNode(node) {
  459. return node && node.depth() % 2 === 1 && node.data.type === 0
  460. }
  461. // 判断蓝色子项和孙子项是否打勾了必填
  462. function hasRequireData(node) {
  463. const requiredList = node.getPosterity().filter(subNode =>
  464. subNode.data.required === true
  465. );
  466. if (requiredList.length) { return true }
  467. return false;
  468. }
  469. // 这里判断有无无定额的情况,有的就返回true,没有就返回false
  470. function isAllRationData(node) {
  471. let isRequired = true;
  472. if (node.children && node.children.length) {
  473. node.children.forEach(subNode => {
  474. if (!subNode.children || !subNode.children.length) {
  475. isRequired = false;
  476. }
  477. })
  478. }
  479. //这里是兼容第一层直接是定额的白色节点
  480. if (node.children && node.children.length) {
  481. node.children.forEach(subNode => {
  482. if (subNode.data.rationID) {
  483. isRequired = true;
  484. }
  485. })
  486. }
  487. return isRequired;
  488. }
  489. // 获取选套定额
  490. function getOptionalData(node, list = []) {
  491. if (isProcessNode(node)) {
  492. node.children.forEach(element => {
  493. if (element.children && element.children.length) {
  494. element.children.forEach(item => {
  495. if (item.data.rationID) {
  496. list.push(item.data.rationID);
  497. } else if (isProcessNode(item)) {
  498. getOptionalData(item, list)
  499. }
  500. })
  501. }
  502. });
  503. } else {
  504. node.children.forEach(element => {
  505. if (element.data.rationID) {
  506. list.push(element.data.rationID);
  507. }
  508. });
  509. }
  510. return list;
  511. }
  512. // 获取必填项下的ID和name的键值对
  513. function getClassCodeStrData(nodes,data={classGroups:{},keyGroup:{}}){
  514. nodes.forEach(node=>{
  515. if (isProcessNode(node)&&node.data.required) {
  516. node.children.forEach(subNode=>{
  517. data.classGroups[subNode.data.ID]=subNode.data.name;
  518. data.keyGroup[subNode.data.ID]=`${subNode.parent.data.name}:${subNode.data.name}`;
  519. })
  520. }
  521. getClassCodeStrData(node.children,data);
  522. })
  523. return data;
  524. }
  525. //获取定额数据
  526. // requireRationData必套定额对象
  527. // optionalRationData 选逃定额对象
  528. // classGroups classCode文字和id键值对
  529. // classCodeList 各个classCode的pID和ID的关系
  530. function getItemData(nodes, requireRationData = {}, optionalRationData = {}, classGroups = {}, prefixID = '', prefixSonID = '', IDData = {}, keyGroup={}) {
  531. const processNodes = nodes.filter(node => isProcessNode(node));
  532. // const classGroups = []; // 同层必填选项的数组(二维数组)
  533. processNodes.forEach(processNode => {
  534. // 蓝色节点,必填
  535. if (processNode.data.required) {
  536. // 白色节点
  537. const optionNodes = processNode.children.filter(node => isOptionNode(node));
  538. optionNodes.forEach(optionNode => {
  539. if (!requireRationData[optionNode.data.ID]) requireRationData[optionNode.data.ID] = [];
  540. if (!optionalRationData[optionNode.data.ID]) optionalRationData[optionNode.data.ID] = [];
  541. //白色节点下没有蓝色节点,就是到底了
  542. if (!optionNode.children.some(subOptionNode => isProcessNode(subOptionNode))) {
  543. // 是否必套定额
  544. if (isAllRationData(optionNode)) {
  545. optionNode.children.forEach(subOptionNode => {
  546. requireRationData[optionNode.data.ID].push([subOptionNode.data.rationID]);
  547. })
  548. } else {
  549. optionalRationData[optionNode.data.ID] = getOptionalData(optionNode);
  550. }
  551. const kV = {};
  552. kV[optionNode.data.ID] = optionNode.data.name;
  553. Object.assign(classGroups, kV);
  554. const keyData={};
  555. keyData[optionNode.data.ID] = `${optionNode.parent.data.name}:${optionNode.data.name}`;
  556. Object.assign(keyGroup,keyData);
  557. } else {
  558. const kV = {};
  559. kV[optionNode.data.ID] = optionNode.data.name;
  560. Object.assign(classGroups, kV);
  561. const keyData={};
  562. keyData[optionNode.data.ID] = `${optionNode.parent.data.name}:${optionNode.data.name}`;
  563. Object.assign(keyGroup,keyData);
  564. // 后代项是否有必填
  565. if (hasRequireData(optionNode)) {
  566. //后代项有必填
  567. prefixSonID = '';
  568. getItemData(optionNode.children, requireRationData, optionalRationData, classGroups, optionNode.data.ID, prefixSonID, IDData, keyGroup);
  569. } else {
  570. //后代项无必填
  571. optionNode.children.forEach(subOptionNode => {
  572. // 是否必套定额
  573. if (isAllRationData(optionNode)) {
  574. if (!requireRationData[subOptionNode.parent.data.ID]) requireRationData[subOptionNode.parent.data.ID] = [];
  575. requireRationData[subOptionNode.parent.data.ID].push(getOptionalData(subOptionNode));
  576. } else {
  577. if (!optionalRationData[subOptionNode.parent.data.ID]) optionalRationData[subOptionNode.parent.data.ID] = [];
  578. optionalRationData[subOptionNode.parent.data.ID].push(...getOptionalData(subOptionNode));
  579. }
  580. })
  581. }
  582. }
  583. })
  584. } else {
  585. // 蓝色节点,非必填
  586. if (hasRequireData(processNode)) {
  587. //后代项有必填
  588. if (isProcessNode(processNode)) {
  589. //蓝色
  590. // 是否必套定额
  591. if (isAllRationData(processNode)) {
  592. processNode.children.forEach((subProcessNode) => {
  593. subProcessNode.children.forEach((sSubProcessNode) => {
  594. //这里是特殊处理,因为原来的逻辑是直接把定额绑到必填白色选项中下面的,每个蓝色的一组,但是这样是不对的,需要绑定在必填白色选项下的蓝色节点,所以这里就需要传入蓝色节点的id
  595. const requireChildrenID = sSubProcessNode.parent.data.required ? prefixSonID : sSubProcessNode.data.ID;
  596. IDData[sSubProcessNode.data.ID] = prefixID;
  597. getItemData(
  598. [sSubProcessNode],
  599. requireRationData,
  600. optionalRationData,
  601. classGroups,
  602. prefixID,
  603. requireChildrenID,
  604. IDData,
  605. keyGroup
  606. )
  607. })
  608. })
  609. } else {
  610. // 全部选套就不用走循环了,直接按照选套执行
  611. let key = processNode.data.ID;
  612. if (prefixID) key = prefixID;
  613. if (prefixSonID) key = prefixSonID;
  614. if (!optionalRationData[key]) optionalRationData[key] = [];
  615. optionalRationData[key].push(...getOptionalData(processNode));
  616. // 因为这里没有按照走整个流程,所以文字和ID的关系需要获取补充
  617. if(hasRequireData(processNode)){
  618. const result =getClassCodeStrData(processNode.children)
  619. Object.assign(classGroups,result.classGroups);
  620. Object.assign(keyGroup,result.keyGroup);
  621. }
  622. }
  623. }
  624. } else {
  625. let key = processNode.data.ID;
  626. if (prefixID) key = prefixID;
  627. if (prefixSonID) key = prefixSonID;
  628. // 是否必套定额
  629. if (isAllRationData(processNode)) {
  630. if (!requireRationData[key]) requireRationData[key] = [];
  631. requireRationData[key].push(getOptionalData(processNode));
  632. } else {
  633. if (!optionalRationData[key]) optionalRationData[key] = [];
  634. optionalRationData[key].push(...getOptionalData(processNode));
  635. }
  636. }
  637. }
  638. })
  639. return { requireRationData, optionalRationData, classGroups, IDData, keyGroup}
  640. }
  641. // 从指引节点,获取分类特征、必套定额数据
  642. function getItemClassData(nodes, prefix,
  643. prefixID) {
  644. const processNodes = nodes.filter(node => isProcessNode(node));
  645. const classGroups = []; // 同层必填选项的数组(二维数组)
  646. processNodes.forEach(processNode => {
  647. const classItems = [];
  648. const optionNodes = processNode.children.filter(node => isOptionNode(node));
  649. optionNodes.forEach(optionNode => {
  650. // const name = prefix ? `${prefix}@${optionNode.data.name}` : optionNode.data.name;
  651. if (optionNode.parent && optionNode.parent.data.required && (!optionNode.children
  652. || !optionNode.children.length
  653. || (optionNode.children[0].data && optionNode.children[0].data.rationID)
  654. || !optionNode.children.some(node => isProcessNode(node)))) {
  655. // 必套定额
  656. classItems.push({ name: optionNode.data.name, ID: optionNode.data.ID });
  657. } else {
  658. // classItems.push(...getItemCharacterData(optionNode.children, optionNode.parent && optionNode.parent.data.required ? optionNode.data.name : ''));
  659. const childrenClassItem = getItemClassData(
  660. optionNode.children,
  661. optionNode.parent && optionNode.parent.data.required ? optionNode.data.name : '',
  662. optionNode.parent && optionNode.parent.data.required ? optionNode.data.ID : ''
  663. );
  664. //如果返回的子项为空,但是父项又勾选了必填,则要把本身存入数组
  665. if (optionNode.parent
  666. && optionNode.parent.data.required
  667. && childrenClassItem.length === 0
  668. ) {
  669. classItems.push({ name: optionNode.data.name, ID: optionNode.data.ID });
  670. } else {
  671. classItems.push(...childrenClassItem);
  672. }
  673. }
  674. });
  675. if (classItems.length) {
  676. classGroups.push(classItems);
  677. }
  678. });
  679. // 拼接上一文本
  680. if (classGroups[0] && classGroups[0].length) {
  681. // classGroups[0] = classGroups[0].map(name => prefix ? `${prefix}@${name}` : name);
  682. classGroups[0] = classGroups[0].map(item => {
  683. item.name = prefix ? `${prefix}@${item.name}` : item.name
  684. item.ID = prefixID ? `${prefixID}@${item.ID}` : item.ID
  685. return item;
  686. });
  687. }
  688. // 二维数组内容排列组合
  689. while (classGroups.length > 1) {
  690. const prevClassItems = classGroups[0];
  691. const nextClassItems = classGroups[1];
  692. const mergedClassItems = [];
  693. for (let i = 0; i < prevClassItems.length; i++) {
  694. for (let j = 0; j < nextClassItems.length; j++) {
  695. // 拼接文本
  696. const mergedName = `${prevClassItems[i].name}@${nextClassItems[j].name}`;
  697. const mergedID = `${prevClassItems[i].ID}@${nextClassItems[j].ID}`;
  698. mergedClassItems.push({ name: mergedName, ID: mergedID });
  699. }
  700. }
  701. classGroups.splice(0, 2, mergedClassItems);
  702. }
  703. // 去重(类别别名要唯一)
  704. const items = classGroups[0] || [];
  705. const nameMap = {};
  706. const rst = [];
  707. items.forEach(item => {
  708. if (!nameMap[item.name]) {
  709. rst.push(item);
  710. }
  711. nameMap[item.name] = true;
  712. });
  713. return rst;
  714. }
  715. // 获取选套定额:把所有分类数据的必套定额确定好了先。选套定额就是清单下所有定额除了必套的
  716. function getOptionalRationIDs(optionalRationData) {
  717. const optionalRationIDs = [];
  718. Object.values(optionalRationData).forEach(optionalRation => {
  719. if (optionalRation.length) optionalRationIDs.push(...optionalRation);
  720. })
  721. return [...new Set(optionalRationIDs)];
  722. }
  723. // 获取错套定额:清单下所有定额,除了分类对应的必套、选套定额
  724. function getErrorRationIDs(requiredRationIDList, optionalRationIDs, allRationIDs) {
  725. const finRequireData = [];
  726. requiredRationIDList.forEach(requiredRationIDs => {
  727. finRequireData.push(...requiredRationIDs);
  728. })
  729. const errorRationIDs = [];
  730. allRationIDs.forEach(rationID => {
  731. if (!finRequireData.includes(rationID) && !optionalRationIDs.includes(rationID)) {
  732. errorRationIDs.push(rationID);
  733. }
  734. });
  735. return [...new Set(errorRationIDs)];
  736. }
  737. //把classcode和必套选套定额结合在一起
  738. function combineData(codeData, requireRationData, optionalRationData, classGroups, IDData, keyGroup) {
  739. // 这里要记录下已经被绑定的选套定额,因为没有被用的定额需要绑定到各个classcode下
  740. const matchRationList = [];
  741. //这里需要把绑定在子节点的定额更新到必填的白色选项中(classcode的值)
  742. const requireCombineData = {};
  743. const optionCombineData = {};
  744. Object.keys(IDData).forEach(key => {
  745. if (!requireCombineData[IDData[key]]) requireCombineData[IDData[key]] = new Set();
  746. if (!optionCombineData[IDData[key]]) optionCombineData[IDData[key]] = new Set();
  747. if (requireRationData[key]) {
  748. requireRationData[key].forEach(subData => {
  749. subData.forEach(subItem => {
  750. requireCombineData[IDData[key]].add(subItem);
  751. })
  752. })
  753. }
  754. if (optionalRationData[key]) {
  755. optionalRationData[key].forEach(subData => {
  756. optionCombineData[IDData[key]].add(subData);
  757. })
  758. }
  759. })
  760. const finData = codeData.map(classCodeData => {
  761. const errorRationIDs = [];
  762. const optionalRationIDs = [];
  763. const requiredRationIDs = [];
  764. let name = '';
  765. let key = '';
  766. const classCodeIDs = classCodeData.ID;
  767. if (/@/.test(classCodeIDs)) {
  768. classCodeIDs.split('@').forEach((classCodeID) => {
  769. if (name) {
  770. name = name + '@' + classGroups[classCodeID];
  771. key += keyGroup[classCodeID];
  772. } else {
  773. name = classGroups[classCodeID];
  774. key = keyGroup[classCodeID];
  775. };
  776. // 一组的必套定额,先去重
  777. const unitRation = [];
  778. // 这里是必填选项下绑定必套定额
  779. if (requireRationData[classCodeID] && requireRationData[classCodeID].length) {
  780. requireRationData[classCodeID].forEach(subItem => {
  781. unitRation.push(...new Set(subItem));
  782. })
  783. requiredRationIDs.push(unitRation);
  784. // 这里也要把用过的必套定额先存起来
  785. matchRationList.push(...unitRation);
  786. }
  787. //这里是必填选项下绑定在蓝色节点下的必套定额
  788. if (requireCombineData[classCodeID] && requireCombineData[classCodeID].size) {
  789. requiredRationIDs.push([...requireCombineData[classCodeID]]);
  790. // 这里也要把用过的必套定额先存起来
  791. matchRationList.push(...requireCombineData[classCodeID]);
  792. }
  793. // 这里是必填选项下绑定选套定额
  794. if (optionalRationData[classCodeID] && optionalRationData[classCodeID].length) {
  795. optionalRationIDs.push(...optionalRationData[classCodeID]);
  796. matchRationList.push(...optionalRationData[classCodeID]);
  797. }
  798. //这里是必填选项下绑定在蓝色节点下的选套定额,下同
  799. if (optionCombineData[classCodeID] && optionCombineData[classCodeID].size) {
  800. optionalRationIDs.push(...optionCombineData[classCodeID]);
  801. matchRationList.push(...optionCombineData[classCodeID]);
  802. }
  803. })
  804. return { name, key, requiredRationIDs, optionalRationIDs: [...new Set(optionalRationIDs)], errorRationIDs }
  805. } else {
  806. const unitRation = [];
  807. name = classGroups[classCodeIDs];
  808. key = keyGroup[classCodeIDs];
  809. if (requireRationData[classCodeIDs] && requireRationData[classCodeIDs].length){
  810. requireRationData[classCodeIDs].forEach(subItem => {
  811. unitRation.push(...new Set(subItem));
  812. })
  813. requiredRationIDs.push(unitRation);
  814. // 这里也要把用过的必套定额先存起来
  815. matchRationList.push(...unitRation);
  816. }
  817. if (requireCombineData[classCodeIDs] && requireCombineData[classCodeIDs].size) {
  818. requiredRationIDs.push([...requireCombineData[classCodeIDs]])
  819. // 这里也要把用过的必套定额先存起来
  820. matchRationList.push(...requireCombineData[classCodeIDs]);
  821. };
  822. if (optionalRationData[classCodeIDs] && optionalRationData[classCodeIDs].length) {
  823. optionalRationIDs.push(...optionalRationData[classCodeIDs]);
  824. matchRationList.push(...optionalRationData[classCodeIDs]);
  825. }
  826. if (optionCombineData[classCodeIDs] && optionCombineData[classCodeIDs].size) {
  827. optionalRationIDs.push(...optionCombineData[classCodeIDs]);
  828. matchRationList.push(...optionalRationData[classCodeIDs]);
  829. }
  830. return { name,key, requiredRationIDs, optionalRationIDs: [...new Set(optionalRationIDs)], errorRationIDs }
  831. }
  832. })
  833. const unMatchRation = [];
  834. Object.values(optionalRationData).forEach(data => {
  835. data.forEach((rationID) => {
  836. if (!matchRationList.includes(rationID)) {
  837. unMatchRation.push(rationID);
  838. }
  839. })
  840. })
  841. // 这里把没有使用过的必套定额也丢到了选套里面
  842. Object.values(requireRationData).forEach(data => {
  843. data.forEach((rationData) => {
  844. rationData.forEach(rationID=>{
  845. if (!matchRationList.includes(rationID)) {
  846. unMatchRation.push(rationID);
  847. }
  848. })
  849. })
  850. })
  851. return { itemClassData: finData, unMatchRation };
  852. }
  853. // 生成清单分类
  854. async function generateClassData(libID) {
  855. const lib = await billsGuideLibModel.findOne({ ID: libID }).lean();
  856. if (!lib) {
  857. throw new Error('无有效精灵库');
  858. }
  859. const guidanceItems = await billsGuideItemsModel.find({ libID }, '-_id').lean();
  860. // 清单ID - 指引数据映射
  861. const guidanceMap = {};
  862. guidanceItems.forEach(item => {
  863. (guidanceMap[item.billsID] || (guidanceMap[item.billsID] = [])).push(item);
  864. });
  865. const bills = await stdBillsModel.find({ billsLibId: lib.billsLibId }, '-_id ID ParentID NextSiblingID name code unit').lean();
  866. const billTree = idTree.createNew({ id: 'ID', pid: 'ParentID', nid: 'NextSiblingID', rootId: -1, autoUpdate: true });
  867. billTree.loadDatas(bills);
  868. // 叶子清单
  869. const leaves = billTree.items.filter(node => !node.children || !node.children.length);
  870. // 获取分类数据
  871. let classNum = 1;
  872. const billClassData = [];
  873. for (let billNode of leaves) {
  874. const guidanceItems = guidanceMap[billNode.data.ID];
  875. if (!guidanceItems || !guidanceItems.length) {
  876. continue;
  877. }
  878. // if (billNode.data.code.startsWith('03')) continue;//先屏蔽掉03开头的清单
  879. const guidanceTree = idTree.createNew({ id: 'ID', pid: 'ParentID', nid: 'NextSiblingID', rootId: -1, autoUpdate: true });
  880. guidanceTree.loadDatas(guidanceItems);
  881. //console.log('getItemClassData start',billNode.data.name,billNode.data.code,billNode.data.ID);
  882. const classCodeData = getItemClassData(guidanceTree.roots); // 必套定额在这个方法内就获取了,避免重复执行递归方法
  883. const { requireRationData, optionalRationData, classGroups, IDData, keyGroup } = getItemData(guidanceTree.roots);
  884. const { itemClassData, unMatchRation } = combineData(classCodeData, requireRationData, optionalRationData, classGroups, IDData, keyGroup);
  885. const allRationIDs = guidanceTree.items.filter(node => !!node.data.rationID).map(node => node.data.rationID);
  886. // 选套定额ID
  887. const optionalRationIDs = getOptionalRationIDs(optionalRationData);
  888. //if(itemClassData.length > 1000) console.log('getItemClassData end',billNode.data.name,billNode.data.code,billNode.data.ID,itemClassData.length)
  889. itemClassData.forEach(item => {
  890. // 错套定额
  891. item.optionalRationIDs.push(...unMatchRation);
  892. const errorRationIDs = getErrorRationIDs(item.requiredRationIDs, item.optionalRationIDs, allRationIDs);
  893. billClassData.push({
  894. itemCharacter: item.name,
  895. class: classNum++,
  896. classCode: `${billNode.data.code}@${item.name}`,
  897. compilationID: lib.compilationId,
  898. name: billNode.data.name,
  899. key: `${billNode.data.code}${billNode.data.name}${billNode.data.unit}${item.key}`,
  900. code: billNode.data.code,
  901. requiredRationIDs: item.requiredRationIDs || [],
  902. optionalRationIDs: item.optionalRationIDs || [],
  903. errorRationIDs,
  904. });
  905. });
  906. //新增无必填时的情况
  907. if (itemClassData.length === 0) {
  908. Object.keys(requireRationData).forEach((key) => {
  909. requireRationData[key].forEach(data => {
  910. if (data.length) optionalRationIDs.push(...data);
  911. })
  912. })
  913. const errorRationIDs = getErrorRationIDs([], optionalRationIDs, allRationIDs);
  914. billClassData.push({
  915. itemCharacter: '',
  916. class: classNum++,
  917. classCode: `${billNode.data.code}`,
  918. compilationID: lib.compilationId,
  919. name: billNode.data.name,
  920. key:`${billNode.data.code}${billNode.data.name}${billNode.data.unit}`,
  921. code: billNode.data.code,
  922. requiredRationIDs: [],
  923. optionalRationIDs: optionalRationIDs || [],
  924. errorRationIDs,
  925. });
  926. }
  927. }
  928. console.log(`billClassData.length`);
  929. console.log(billClassData.length);
  930. // 清空旧的分类数据
  931. await billClassModel.deleteMany({ compilationID: lib.compilationId });
  932. // 之前遇到一次性插入40w条数据的情况,会卡死,循环插入速度快很多
  933. while (billClassData.length > 10000) {
  934. const list = billClassData.splice(0, 10000);
  935. await billClassModel.insertMany(list);
  936. }
  937. await billClassModel.insertMany(billClassData);
  938. }
  939. // 获取分类excel数据
  940. async function getClassExcelData(libID) {
  941. const lib = await billsGuideLibModel.findOne({ ID: libID }, '-_id compilationId').lean();
  942. if (!lib) {
  943. throw new Error('无有效精灵库');
  944. }
  945. console.log('start');
  946. const date = Date.now();
  947. const classData = await billClassModel.find({ compilationID: lib.compilationId }).lean();
  948. console.log('end');
  949. console.log(Date.now() - date);
  950. const excelData = [['类别', '编码', '清单名称', '必填特征排列组合', '类别别名', '必套定额', '选套定额', '错套定额','基础样本']];
  951. classData.forEach(item => {
  952. const excelItem = [
  953. item.class,
  954. item.code,
  955. item.name,
  956. item.itemCharacter,
  957. item.classCode,
  958. (item.requiredRationIDs || []).join('@'),
  959. (item.optionalRationIDs || []).join('@'),
  960. (item.errorRationIDs || []).join('@'),
  961. item.key,
  962. ];
  963. excelData.push(excelItem);
  964. });
  965. return excelData;
  966. }
  967. async function testItems(libID) {
  968. let items = await billsGuideItemsModel.find({ libID: libID });
  969. //删除垃圾数据
  970. let delBulk = [];
  971. let itemsMapping = {};
  972. for (let item of items) {
  973. itemsMapping[item.ID] = true;
  974. }
  975. for (let item of items) {
  976. if (item.ParentID != -1 && !itemsMapping[item.ParentID]) {
  977. delBulk.push({
  978. deleteOne: {
  979. filter: { ID: item.ID }
  980. }
  981. });
  982. }
  983. }
  984. if (delBulk.length > 0) {
  985. console.log(`delBulk.length`);
  986. console.log(delBulk.length);
  987. await billsGuideItemsModel.bulkWrite(delBulk);
  988. }
  989. /* //查找同层节点含有相同NextSiblingID的节点
  990. let rst = [];
  991. let billsGroup = {};
  992. for(let item of items){
  993. if(!billsGroup[item.billsID]){
  994. billsGroup[item.billsID] = [item];
  995. }
  996. else {
  997. billsGroup[item.billsID].push(item);
  998. }
  999. }
  1000. for(let bGroup in billsGroup){
  1001. let group = billsGroup[bGroup];
  1002. let parentGroup = {};
  1003. for(let gItem of group){
  1004. if(!parentGroup[gItem.ParentID]){
  1005. parentGroup[gItem.ParentID] = [gItem]
  1006. }
  1007. else {
  1008. parentGroup[gItem.ParentID].push(gItem);
  1009. }
  1010. }
  1011. for(let pGroup in parentGroup){
  1012. let pGroupData = parentGroup[pGroup];
  1013. let nextGroup = {};
  1014. for(let nItem of pGroupData){
  1015. let sameNext = _.filter(pGroupData, {NextSiblingID: nItem.NextSiblingID});
  1016. if(sameNext.length > 1){
  1017. console.log(`sameNext`);
  1018. console.log(sameNext);
  1019. if(!nextGroup[nItem.ParentID + nItem.NextSiblingID]){
  1020. rst.push({NextSiblingID: nItem.NextSiblingID, ParentID: nItem.ParentID});
  1021. nextGroup[nItem.ParentID + nItem.NextSiblingID] = 1;
  1022. }
  1023. }
  1024. }
  1025. }
  1026. }*/
  1027. return delBulk.length;
  1028. }