index.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786
  1. const mongoose = require('mongoose');
  2. const uuidV1 = require('uuid/v1');
  3. const _ = require('lodash');
  4. const scMathUtil = require('../../../public/scMathUtil').getUtil();
  5. const { CRAWL_LOG_KEY, ProcessStatus } = require('../../../public/constants/price_info_constant');
  6. const priceInfoLibModel = mongoose.model('std_price_info_lib');
  7. const priceInfoClassModel = mongoose.model('std_price_info_class');
  8. const priceInfoItemModel = mongoose.model('std_price_info_items');
  9. const priceInfoAreaModel = mongoose.model('std_price_info_areas');
  10. const compilationModel = mongoose.model('compilation');
  11. const importLogsModel = mongoose.model('import_logs');
  12. const priceInfoIndexModel = mongoose.model('std_price_info_index');
  13. const priceInfoSummaryModel = mongoose.model('std_price_info_summary');
  14. const { getWordArray, alias } = require('../../../public/cut_word/segmentit');
  15. const SMS = require('../../users/models/sms');
  16. const sms = new SMS();
  17. async function getLibs(query) {
  18. return await priceInfoLibModel.find(query).sort({ period: 1 }).lean();
  19. }
  20. // 获取费用定额的信息价库
  21. async function getAllLibs() {
  22. const libs = await priceInfoLibModel.find({}, '-_id').lean();
  23. const groupData = _.groupBy(libs, 'compilationID');
  24. const rst = [];
  25. Object.keys(groupData).forEach(key => {
  26. const items = groupData[key];
  27. items.sort((a, b) => a.period.localeCompare(b.period));
  28. rst.push(...items);
  29. });
  30. return rst;
  31. }
  32. async function createLib(name, period, compilationID) {
  33. // 将2020-01变成2020年01月
  34. const reg = /(\d{4})-(\d{2})/;
  35. const formattedPeriod = period.replace(reg, '$1年-$2月');
  36. const lib = {
  37. ID: uuidV1(),
  38. name,
  39. period: formattedPeriod,
  40. compilationID,
  41. createDate: Date.now(),
  42. };
  43. await priceInfoLibModel.create(lib);
  44. return lib;
  45. }
  46. async function updateLib(query, updateData) {
  47. await priceInfoLibModel.update(query, updateData);
  48. }
  49. async function deleteLib(libID) {
  50. await priceInfoClassModel.remove({ libID });
  51. await priceInfoItemModel.remove({ libID });
  52. await priceInfoLibModel.remove({ ID: libID });
  53. }
  54. async function processChecking(key) {
  55. const logData = key
  56. ? await importLogsModel.findOne({ key })
  57. : await importLogsModel.findOne({ key: CRAWL_LOG_KEY });
  58. if (!logData) {
  59. return { status: ProcessStatus.FINISH };
  60. }
  61. if (logData.status === ProcessStatus.FINISH || logData.status === ProcessStatus.ERROR) {
  62. await importLogsModel.remove({ key: logData.key });
  63. }
  64. return { status: logData.status, errorMsg: logData.errorMsg || '', key: logData.key };
  65. }
  66. // 爬取数据
  67. async function crawlDataByCompilation(compilationID, from, to) {
  68. if (!compilationID) {
  69. throw '无有效费用定额。';
  70. }
  71. const compilationData = await compilationModel.findOne({ _id: mongoose.Types.ObjectId(compilationID) }, 'overWriteUrl').lean();
  72. if (!compilationData || !compilationData.overWriteUrl) {
  73. throw '无有效费用定额。';
  74. }
  75. // 从overWriteUrl提取并组装爬虫文件
  76. const reg = /\/([^/]+)\.js/;
  77. const matched = compilationData.overWriteUrl.match(reg);
  78. const crawlURL = `${matched[1]}_price_crawler.js`;
  79. let crawlData;
  80. try {
  81. const crawler = require(`../../../web/over_write/crawler/${crawlURL}`);
  82. crawlData = crawler.crawlData;
  83. } catch (e) {
  84. console.log(e);
  85. throw '该费用定额无可用爬虫方法。'
  86. }
  87. //await crawlData(from, to);
  88. // 异步不等结果,结果由checking来获取
  89. crawlDataByMiddleware(crawlData, from, to, compilationID);
  90. }
  91. // 爬取数据中间件,主要处理checking初始化
  92. async function crawlDataByMiddleware(crawlFunc, from, to, compilationID) {
  93. const logUpdateData = { status: ProcessStatus.FINISH };
  94. try {
  95. const logData = {
  96. key: CRAWL_LOG_KEY,
  97. content: '正在爬取数据,请稍候……',
  98. status: ProcessStatus.START,
  99. create_time: Date.now()
  100. };
  101. await importLogsModel.create(logData);
  102. await crawlFunc(from, to, compilationID);
  103. } catch (err) {
  104. console.log(err);
  105. logUpdateData.errorMsg = String(err);
  106. logUpdateData.status = ProcessStatus.ERROR;
  107. } finally {
  108. await importLogsModel.update({ key: CRAWL_LOG_KEY }, logUpdateData);
  109. }
  110. }
  111. // 导入excel数据,格式如下
  112. // 格式1:
  113. //地区 分类 编码 名称 规格型号 单位 不含税价 含税价
  114. //江北区 黑色及有色金属 热轧光圆钢筋 φ6(6.5) 3566.37 4030
  115. //江北区 木、竹材料及其制品 柏木门套线 60×10 8.76 9.9
  116. // 格式2:
  117. //地区 分类 编码 名称 规格型号 不含税价 含税价
  118. //江北区 黑色及有色金属 热轧光圆钢筋 φ6(6.5) 3566.37 4030
  119. // 柏木门套线 60×10 8.76 9.9
  120. // 沥青混凝土 AC-13 982.3 1110
  121. //
  122. //北碚区 木、竹材料及其制品 热轧光圆钢筋 φ6(6.5) 3566.37 4030
  123. async function importExcelData(libID, sheetData) {
  124. const libs = await getLibs({ ID: libID });
  125. const compilationID = libs[0].compilationID;
  126. // 建立区映射表:名称-ID映射、ID-名称映射
  127. const areaList = await getAreas(compilationID);
  128. const areaMap = {};
  129. areaList.forEach(({ ID, name }) => {
  130. areaMap[name] = ID;
  131. areaMap[ID] = name;
  132. });
  133. // 建立分类映射表:地区名称@分类名称:ID映射
  134. /* const classMap = {};
  135. const classList = await getClassData(libID);
  136. classList.forEach(({ ID, areaID, name }) => {
  137. const areaName = areaMap[areaID] || '';
  138. classMap[`${areaName}@${name}`] = ID;
  139. }); */
  140. // 第一行获取行映射
  141. const colMap = {};
  142. for (let col = 0; col < sheetData[0].length; col++) {
  143. const cellText = sheetData[0][col];
  144. switch (cellText) {
  145. case '地区':
  146. colMap.area = col;
  147. break;
  148. case '分类':
  149. colMap.class = col;
  150. break;
  151. case '编码':
  152. colMap.code = col;
  153. break;
  154. case '名称':
  155. colMap.name = col;
  156. break;
  157. case '规格型号':
  158. colMap.specs = col;
  159. break;
  160. case '单位':
  161. colMap.unit = col;
  162. break;
  163. case '不含税价':
  164. colMap.noTaxPrice = col;
  165. break;
  166. case '含税价':
  167. colMap.taxPrice = col;
  168. break;
  169. }
  170. }
  171. // 提取数据
  172. const data = [];
  173. const classData = [];
  174. const areaClassDataMap = {};
  175. let curAreaName;
  176. let curClassName;
  177. let curClassID;
  178. for (let row = 1; row < sheetData.length; row++) {
  179. const areaName = sheetData[row][colMap.area] || '';
  180. const className = sheetData[row][colMap.class] || '';
  181. const code = sheetData[row][colMap.code] ? sheetData[row][colMap.code].trim() : '';
  182. const name = sheetData[row][colMap.name] ? sheetData[row][colMap.name].trim() : '';
  183. const specs = sheetData[row][colMap.specs] ? sheetData[row][colMap.specs].trim() : '';
  184. const unit = sheetData[row][colMap.unit] ? sheetData[row][colMap.unit].trim() : '';
  185. const noTaxPrice = sheetData[row][colMap.noTaxPrice] ? sheetData[row][colMap.noTaxPrice].trim() : '';
  186. const taxPrice = sheetData[row][colMap.taxPrice] ? sheetData[row][colMap.taxPrice].trim() : '';
  187. if (!className && !code && !name && !specs && !noTaxPrice && !taxPrice) { // 认为是空数据
  188. continue;
  189. }
  190. if (areaName && areaName !== curAreaName) {
  191. curAreaName = areaName;
  192. }
  193. const areaID = areaMap[curAreaName];
  194. if (!areaID) {
  195. continue;
  196. }
  197. if (className && className !== curClassName) {
  198. curClassName = className;
  199. const classItem = {
  200. libID,
  201. areaID,
  202. ID: uuidV1(),
  203. ParentID: '-1',
  204. NextSiblingID: '-1',
  205. name: curClassName
  206. };
  207. curClassID = classItem.ID;
  208. classData.push(classItem);
  209. (areaClassDataMap[areaID] || (areaClassDataMap[areaID] = [])).push(classItem);
  210. const preClassItem = areaClassDataMap[areaID][areaClassDataMap[areaID].length - 2];
  211. if (preClassItem) {
  212. preClassItem.NextSiblingID = classItem.ID;
  213. }
  214. }
  215. if (!curClassID) {
  216. continue;
  217. }
  218. data.push({
  219. ID: uuidV1(),
  220. compilationID,
  221. libID,
  222. areaID,
  223. classID: curClassID,
  224. period: libs[0].period,
  225. code,
  226. name,
  227. specs,
  228. unit,
  229. noTaxPrice,
  230. taxPrice
  231. });
  232. }
  233. if (classData.length) {
  234. await priceInfoClassModel.remove({ libID });
  235. await priceInfoClassModel.insertMany(classData);
  236. }
  237. if (data.length) {
  238. await priceInfoItemModel.remove({ libID });
  239. await priceInfoItemModel.insertMany(data);
  240. } else {
  241. throw 'excel没有有效数据。'
  242. }
  243. }
  244. // 导入excel关键字数据(主表+副表),目前只针对珠海,根据列号导入
  245. /*
  246. 主表:主从对应码 别名编码 材料名称 规格 单位 含税价(元) 除税价(元) 月份备注 计算式
  247. 副表:主从对应码 关键字 单位 关键字效果 组别 选项号
  248. */
  249. async function importKeyData(libID, mainData, subData) {
  250. const lib = await priceInfoLibModel.findOne({ ID: libID }).lean();
  251. if (!lib) {
  252. throw new Error('库不存在');
  253. }
  254. const zh = await priceInfoAreaModel.findOne({ name: { $regex: '珠海' } }).lean();
  255. if (!zh) {
  256. throw new Error('该库不存在珠海地区');
  257. }
  258. // 删除珠海地区所有材料
  259. await priceInfoItemModel.deleteMany({ libID, areaID: zh.ID });
  260. const classItems = await priceInfoClassModel.find({ libID, areaID: zh.ID }).lean();
  261. // 分类树前四位编码 - 分类节点ID映射表
  262. let otherClassID = '';
  263. const classMap = {};
  264. classItems.forEach(item => {
  265. if (item.name) {
  266. if (!otherClassID && /其他/.test(item.name)) {
  267. otherClassID = item.ID;
  268. }
  269. const code = item.name.substr(0, 4);
  270. if (/\d{4}/.test(code)) {
  271. classMap[code] = item.ID;
  272. }
  273. }
  274. });
  275. // 主从对应码 - 关键字数组映射
  276. const keywordMap = {};
  277. for (let row = 1; row < subData.length; row++) {
  278. const rowData = subData[row];
  279. const keywordItem = {
  280. code: rowData[0] ? String(rowData[0]) : '',
  281. keyword: rowData[1] || '',
  282. unit: rowData[2] || '',
  283. coe: rowData[3] || '',
  284. group: rowData[4] || '',
  285. optionCode: rowData[5] || '',
  286. };
  287. if (!keywordItem.code) {
  288. continue;
  289. }
  290. (keywordMap[keywordItem.code] || (keywordMap[keywordItem.code] = [])).push(keywordItem);
  291. }
  292. const priceItems = [];
  293. for (let row = 1; row < mainData.length; row++) {
  294. const rowData = mainData[row];
  295. const code = rowData[0] ? String(rowData[0]) : '';
  296. if (!code) {
  297. continue;
  298. }
  299. const matchCode = code.substring(0, 4);
  300. const classID = classMap[matchCode] || otherClassID;
  301. const priceItem = {
  302. code,
  303. libID,
  304. classID,
  305. ID: uuidV1(),
  306. compilationID: lib.compilationID,
  307. areaID: zh.ID,
  308. period: lib.period,
  309. classCode: rowData[1] || '',
  310. name: rowData[2] || '',
  311. specs: rowData[3] || '',
  312. unit: rowData[4] || '',
  313. taxPrice: rowData[5] || '',
  314. noTaxPrice: rowData[6] || '',
  315. dateRemark: rowData[7] || '',
  316. expString: rowData[8] || '',
  317. keywordList: keywordMap[code] || [],
  318. }
  319. priceItems.push(priceItem);
  320. }
  321. if (priceItems.length) {
  322. await priceInfoItemModel.insertMany(priceItems);
  323. }
  324. }
  325. // 获取费用定额的地区数据
  326. async function getAreas(compilationID) {
  327. return await priceInfoAreaModel.find({ compilationID }, '-_id ID name serialNo').lean();
  328. }
  329. async function updateAres(updateData) {
  330. const bulks = [];
  331. updateData.forEach(({ ID, field, value }) => bulks.push({
  332. updateOne: {
  333. filter: { ID },
  334. update: { [field]: value }
  335. }
  336. }));
  337. if (bulks.length) {
  338. await priceInfoAreaModel.bulkWrite(bulks);
  339. }
  340. }
  341. async function insertAreas(insertData) {
  342. await priceInfoAreaModel.insertMany(insertData);
  343. }
  344. async function deleteAreas(deleteData) {
  345. await priceInfoClassModel.remove({ areaID: { $in: deleteData } });
  346. await priceInfoItemModel.remove({ areaID: { $in: deleteData } });
  347. await priceInfoAreaModel.remove({ ID: { $in: deleteData } });
  348. }
  349. async function getClassData(libID, areaID) {
  350. if (libID && areaID) {
  351. return await priceInfoClassModel.find({ libID, areaID }, '-_id').lean();
  352. }
  353. if (libID) {
  354. return await priceInfoClassModel.find({ libID }, '-_id').lean();
  355. }
  356. if (areaID) {
  357. return await priceInfoClassModel.find({ areaID }, '-_id').lean();
  358. }
  359. }
  360. async function getPriceData(classIDList) {
  361. return await priceInfoItemModel.find({ classID: { $in: classIDList } }, '-_id').lean();
  362. }
  363. const UpdateType = {
  364. UPDATE: 'update',
  365. DELETE: 'delete',
  366. CREATE: 'create',
  367. };
  368. async function editPriceData(postData) {
  369. const bulks = [];
  370. postData.forEach(data => {
  371. const filter = { ID: data.ID };
  372. // 为了命中索引,ID暂时还没添加索引,数据量太大,担心内存占用太多
  373. if (data.areaID) {
  374. filter.areaID = data.areaID;
  375. }
  376. if (data.compilationID) {
  377. filter.compilationID = data.compilationID;
  378. }
  379. if (data.period) {
  380. filter.period = data.period;
  381. }
  382. if (data.type === UpdateType.UPDATE) {
  383. bulks.push({
  384. updateOne: {
  385. filter,
  386. update: { ...data.data }
  387. }
  388. });
  389. } else if (data.type === UpdateType.DELETE) {
  390. bulks.push({
  391. deleteOne: {
  392. filter,
  393. }
  394. });
  395. } else {
  396. bulks.push({
  397. insertOne: {
  398. document: data.data
  399. }
  400. });
  401. }
  402. });
  403. if (bulks.length) {
  404. await priceInfoItemModel.bulkWrite(bulks);
  405. }
  406. }
  407. async function editClassData(updateData) {
  408. const bulks = [];
  409. const deleteIDList = [];
  410. updateData.forEach(({ type, filter, update, document }) => {
  411. if (type === UpdateType.UPDATE) {
  412. bulks.push({
  413. updateOne: {
  414. filter,
  415. update
  416. }
  417. });
  418. } else if (type === UpdateType.DELETE) {
  419. deleteIDList.push(filter.ID);
  420. bulks.push({
  421. deleteOne: {
  422. filter
  423. }
  424. });
  425. } else {
  426. bulks.push({
  427. insertOne: {
  428. document
  429. }
  430. });
  431. }
  432. });
  433. if (deleteIDList.length) {
  434. await priceInfoItemModel.remove({ classID: { $in: deleteIDList } });
  435. }
  436. if (bulks.length) {
  437. await priceInfoClassModel.bulkWrite(bulks);
  438. }
  439. }
  440. //计算指标平均值
  441. function calcIndexAvg(period, areaID, compilationID, preCodeMap) {
  442. const newData = [];
  443. for (const code in preCodeMap) {
  444. const indexArr = preCodeMap[code];
  445. let total = 0;
  446. for (const index of indexArr) {
  447. total = scMathUtil.roundForObj(total + index, 2);
  448. }
  449. const avg = scMathUtil.roundForObj(total / indexArr.length, 2);
  450. newData.push({ ID: uuidV1(), code, period, areaID, compilationID, index: avg })
  451. }
  452. return newData
  453. }
  454. //一个月里有classCode相同,但是价格不同的情况,取平均值
  455. function getClassCodePriceAvgMap(items) {
  456. const classCodeMap = {};
  457. for (const b of items) {
  458. classCodeMap[b.classCode] ? classCodeMap[b.classCode].push(b) : classCodeMap[b.classCode] = [b];
  459. }
  460. for (const classCode in classCodeMap) {
  461. const baseItems = classCodeMap[classCode];
  462. const item = baseItems[0];
  463. if (baseItems.length > 1) {
  464. let sum = 0;
  465. for (const b of baseItems) {
  466. sum += parseFloat(b.noTaxPrice);
  467. }
  468. classCodeMap[classCode] = { code: item.code, name: item.name, price: scMathUtil.roundForObj(sum / baseItems.length, 2) };
  469. } else {
  470. classCodeMap[classCode] = { code: item.code, name: item.name, price: parseFloat(item.noTaxPrice) }
  471. }
  472. }
  473. return classCodeMap
  474. }
  475. async function calcPriceIndex(libID, period, areaID, compilationID) {
  476. const baseItems = await priceInfoItemModel.find({ areaID, period: '2022年-01月' }).lean();//以珠海 22年1月的数据为基准
  477. const currentItems = await priceInfoItemModel.find({ areaID, period }).lean();
  478. const preCodeMap = {};//编码前4位-指数映射
  479. const baseAvgMap = getClassCodePriceAvgMap(baseItems);
  480. const currentAvgMap = getClassCodePriceAvgMap(currentItems);
  481. let message = '';
  482. for (const classCode in currentAvgMap) {
  483. const c = currentAvgMap[classCode];
  484. const preCode = c.code.substr(0, 4);
  485. let index = 1;
  486. const baseItem = baseAvgMap[classCode];
  487. const tem = { index, classCode, name: c.name, code: c.code };
  488. if (baseItem && baseItem.price) {//一个月份里有多个值时,先取平均再计算
  489. index = scMathUtil.roundForObj(c.price / baseItem.price, 2);
  490. tem.baseName = baseItem.name;
  491. }
  492. tem.index = index;
  493. if (Math.abs(index - 1) > 0.2) {
  494. const string = `classCode:${tem.classCode},编号:${tem.code},基础名称:${tem.baseName},当前库中名称:${tem.name},指数:${tem.index};\n`;
  495. message += string;
  496. console.log(string)
  497. }
  498. preCodeMap[preCode] ? preCodeMap[preCode].push(index) : preCodeMap[preCode] = [index];
  499. }
  500. const newIndexData = calcIndexAvg(period, areaID, compilationID, preCodeMap)
  501. //删除旧数据
  502. await priceInfoIndexModel.deleteMany({ areaID, period });
  503. //插入新数据
  504. await priceInfoIndexModel.insertMany(newIndexData);
  505. return message;
  506. }
  507. const getMatchSummaryKey = (item) => {
  508. const props = ['name', 'specs', 'unit'];
  509. return props.map(prop => {
  510. const subKey = item[prop] ? item[prop].trim() : '';
  511. return subKey;
  512. }).join('@');
  513. }
  514. const getSummaryMap = (items) => {
  515. const map = {};
  516. items.forEach(item => {
  517. const key = getMatchSummaryKey(item);
  518. map[key] = item;
  519. });
  520. return map;
  521. }
  522. // 匹配总表
  523. // 按规则匹配信息价的编码、别名编码、计算式(只匹配珠海建筑,要单独标记珠海地区);
  524. // 匹配规则:名称+规格型号+单位,与总表一致则自动填入编码、别名编码、计算式(珠海建筑);
  525. const matchSummary = async (compilationID, libID, areaID) => {
  526. const updateBulks = [];
  527. const areaFilter = { compilationID };
  528. if (areaID) {
  529. areaFilter.ID = areaID;
  530. }
  531. const areas = await priceInfoAreaModel.find(areaFilter, '-_id ID name').lean();
  532. const areaNameMap = {};
  533. areas.forEach(area => {
  534. areaNameMap[area.ID] = area.name;
  535. });
  536. const filter = { libID };
  537. if (areaID) {
  538. filter.areaID = areaID;
  539. }
  540. const priceItems = await priceInfoItemModel.find(filter, '-_id ID compilationID name specs unit areaID period').lean();
  541. const summaryItems = await priceInfoSummaryModel.find({}, '-_id ID name specs unit code classCode expString').lean();
  542. const summaryMap = getSummaryMap(summaryItems);
  543. priceItems.forEach(priceItem => {
  544. const key = getMatchSummaryKey(priceItem);
  545. const matched = summaryMap[key];
  546. if (matched) {
  547. const updateObj = {
  548. code: matched.code,
  549. classCode: matched.classCode,
  550. }
  551. console.log(matched);
  552. console.log(updateObj);
  553. const areaName = areaNameMap[priceItem.areaID];
  554. /* if (/珠海/.test(areaName)) {
  555. updateObj.expString = matched.expString;
  556. } */
  557. updateBulks.push({
  558. updateOne: {
  559. filter: { ID: priceItem.ID, compilationID: priceItem.compilationID, areaID: priceItem.areaID, period: priceItem.period },
  560. update: updateObj
  561. }
  562. })
  563. }
  564. });
  565. if (updateBulks.length) {
  566. console.log(`updateBulks.length`, updateBulks.length);
  567. await priceInfoItemModel.bulkWrite(updateBulks);
  568. }
  569. }
  570. // 获取空数据(没有别名编码)
  571. const getPriceEmptyData = async (compilationID, libID, areaID) => {
  572. const lib = await priceInfoLibModel.findOne({ ID: libID }).lean();
  573. if (!lib) {
  574. return [];
  575. }
  576. const filter = { compilationID, libID, period: lib.period };
  577. if (areaID) {
  578. filter.areaID = areaID;
  579. }
  580. const priceItems = await priceInfoItemModel.find(filter).lean();
  581. return priceItems.filter(item => !item.classCode);
  582. };
  583. const getMatchPrice = (allInfoPrice, nameArray, needHandleLongWord = true) => {
  584. let items = [];
  585. let maxNum = 0; // 最大匹配数
  586. const matchMap = {}; // 匹配储存
  587. let handleLongWord = false;
  588. if (needHandleLongWord) {
  589. for (const na of nameArray) {
  590. if (na.length >= 5) handleLongWord = true;
  591. }
  592. }
  593. for (const info of allInfoPrice) {
  594. // specs
  595. const matchString = alias(info.name + info.specs); // 组合名称和规格型号
  596. info.matchString = matchString;
  597. let matchCount = 0;
  598. for (const na of nameArray) {
  599. if (matchString.indexOf(na) !== -1) {
  600. matchCount += 1;
  601. if (needHandleLongWord && na.length >= 5) handleLongWord = false; // 有5个字的,并且匹配上了,这里就为false不用再处理一次了
  602. }
  603. }
  604. if (matchCount > 0) {
  605. if (matchMap[matchCount]) {
  606. matchMap[matchCount].push(info);
  607. } else {
  608. matchMap[matchCount] = [info];
  609. }
  610. if (matchCount > maxNum) maxNum = matchCount;
  611. }
  612. }
  613. if (maxNum > 0) items = matchMap[maxNum];
  614. return { items, handleLongWord };
  615. }
  616. // 获取推荐总表数据
  617. const getRecommendPriceSummaryData = async (keyword) => {
  618. const nameArray = getWordArray(keyword);
  619. console.log(`nameArray`);
  620. console.log(nameArray);
  621. const allItems = await priceInfoSummaryModel.find({}).lean();
  622. let { items } = getMatchPrice(allItems, nameArray);
  623. // 按匹配位置排序 如[ '橡胶', '胶圈', '给水' ] 先显示橡胶
  624. items = _.sortBy(items, item => {
  625. const ms = item.matchString;
  626. for (let i = 0; i < nameArray.length; i += 1) {
  627. if (ms.indexOf(nameArray[i]) !== -1) return i;
  628. }
  629. return 0;
  630. });
  631. return items;
  632. }
  633. // 处理价格¥符号
  634. /* const handlePriceText = async () => {
  635. const libs = await priceInfoLibModel.find({}).lean();
  636. for (const lib of libs) {
  637. const libID = lib.ID;
  638. const bulks = [];
  639. const items = await priceInfoItemModel.find({ libID }, '-_id ID noTaxPrice areaID period').lean();
  640. items.forEach(item => {
  641. if (item.noTaxPrice && /¥/.test(item.noTaxPrice)) {
  642. const noTaxPrice = item.noTaxPrice.replace('¥', '').replace(',', '');
  643. bulks.push({ updateOne: { filter: { ID: item.ID, areaID: item.areaID, period: item.period }, update: { $set: { noTaxPrice } } } });
  644. // bulks.push({ deleteOne: { filter: { ID: item.ID, areaID: item.areaID, period: item.period } } });
  645. }
  646. });
  647. if (bulks.length) {
  648. const chunks = _.chunk(bulks, Math.floor(bulks.length / 500) + 1);
  649. for (const chunk of chunks) {
  650. if (chunk.length) {
  651. await priceInfoItemModel.bulkWrite(chunk);
  652. }
  653. }
  654. }
  655. }
  656. } */
  657. // 删除价格为空的
  658. const handlePriceText = async () => {
  659. const libs = await priceInfoLibModel.find({}).lean();
  660. for (const lib of libs) {
  661. const libID = lib.ID;
  662. const bulks = [];
  663. const items = await priceInfoItemModel.find({ libID }, '-_id ID noTaxPrice areaID period').lean();
  664. items.forEach(item => {
  665. if (!item.noTaxPrice) {
  666. bulks.push({ deleteOne: { filter: { ID: item.ID, areaID: item.areaID, period: item.period } } });
  667. }
  668. });
  669. if (bulks.length) {
  670. const chunks = _.chunk(bulks, Math.floor(bulks.length / 500) + 1);
  671. for (const chunk of chunks) {
  672. if (chunk.length) {
  673. await priceInfoItemModel.bulkWrite(chunk);
  674. }
  675. }
  676. }
  677. }
  678. }
  679. // 按库导出信息价库完整数据,不需要带上地区
  680. async function exportInfoPriceByLib(libID) {
  681. const lib = await priceInfoLibModel.findOne({ ID: libID }).lean();
  682. if (!lib) {
  683. throw new Error('不存在该信息价库!');
  684. }
  685. const { compilationID } = lib;
  686. const priceLibs = await priceInfoLibModel.find({ ID: libID }, '-_id').lean();
  687. const priceClasses = await priceInfoClassModel.find({ libID }, '-_id').lean();
  688. const priceItems = await priceInfoItemModel.find({ libID }, '-_id').lean();
  689. const exportData = { compilationID, priceLibs, priceClasses, priceItems };
  690. const str = JSON.stringify(exportData);
  691. exportData.md5 = sms.md5(str);
  692. return { jsonStr: JSON.stringify(exportData), period: lib.period, name: lib.name };
  693. }
  694. // 按编办导出信息价库完整数据,需要带上地区
  695. async function exportInfoPriceByCompilation(compilationID) {
  696. const areas = await priceInfoAreaModel.find({ compilationID }, '-_id').lean();
  697. const priceLibs = await priceInfoLibModel.find({ compilationID }, '-_id').lean();
  698. const libIDs = priceLibs.map(lib => lib.ID);
  699. const priceClasses = await priceInfoClassModel.find({ libID: { $in: libIDs } }, '-_id').lean();
  700. const priceItems = await priceInfoItemModel.find({ libID: { $in: libIDs } }, '-_id').lean();
  701. const exportData = { compilationID, areas, priceLibs, priceClasses, priceItems };
  702. const str = JSON.stringify(exportData);
  703. exportData.md5 = sms.md5(str);
  704. return { jsonStr: JSON.stringify(exportData), period: lib.period, name: lib.name };
  705. }
  706. module.exports = {
  707. getLibs,
  708. createLib,
  709. updateLib,
  710. deleteLib,
  711. processChecking,
  712. crawlDataByCompilation,
  713. importExcelData,
  714. importKeyData,
  715. getAreas,
  716. updateAres,
  717. insertAreas,
  718. deleteAreas,
  719. getClassData,
  720. calcPriceIndex,
  721. getPriceData,
  722. editPriceData,
  723. editClassData,
  724. matchSummary,
  725. getPriceEmptyData,
  726. getRecommendPriceSummaryData,
  727. handlePriceText,
  728. exportInfoPriceByLib,
  729. exportInfoPriceByCompilation,
  730. getAllLibs,
  731. }