index.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788
  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] ? String(sheetData[row][colMap.area]).trim() : '';
  180. const className = sheetData[row][colMap.class] ? String(sheetData[row][colMap.class]).trim() : '';
  181. const code = sheetData[row][colMap.code] ? String(sheetData[row][colMap.code]).trim() : '';
  182. const name = sheetData[row][colMap.name] ? String(sheetData[row][colMap.name]).trim() : '';
  183. const specs = sheetData[row][colMap.specs] ? String(sheetData[row][colMap.specs]).trim() : '';
  184. const unit = sheetData[row][colMap.unit] ? String(sheetData[row][colMap.unit]).trim() : '';
  185. const noTaxPrice = sheetData[row][colMap.noTaxPrice] ? String(sheetData[row][colMap.noTaxPrice]).trim() : '';
  186. const taxPrice = sheetData[row][colMap.taxPrice] ? String(sheetData[row][colMap.taxPrice]).trim() : '';
  187. if (!className && !code && !name && !specs && !noTaxPrice && !taxPrice) { // 认为是空数据
  188. continue;
  189. }
  190. let areaChange = false;
  191. if (areaName && areaName !== curAreaName) {
  192. curAreaName = areaName;
  193. areaChange = true;
  194. }
  195. const areaID = areaMap[curAreaName];
  196. if (!areaID) {
  197. continue;
  198. }
  199. if ((className && className !== curClassName) || areaChange) {
  200. curClassName = className;
  201. const classItem = {
  202. libID,
  203. areaID,
  204. ID: uuidV1(),
  205. ParentID: '-1',
  206. NextSiblingID: '-1',
  207. name: curClassName
  208. };
  209. curClassID = classItem.ID;
  210. classData.push(classItem);
  211. (areaClassDataMap[areaID] || (areaClassDataMap[areaID] = [])).push(classItem);
  212. const preClassItem = areaClassDataMap[areaID][areaClassDataMap[areaID].length - 2];
  213. if (preClassItem) {
  214. preClassItem.NextSiblingID = classItem.ID;
  215. }
  216. }
  217. if (!curClassID) {
  218. continue;
  219. }
  220. data.push({
  221. ID: uuidV1(),
  222. compilationID,
  223. libID,
  224. areaID,
  225. classID: curClassID,
  226. period: libs[0].period,
  227. code,
  228. name,
  229. specs,
  230. unit,
  231. noTaxPrice,
  232. taxPrice
  233. });
  234. }
  235. if (classData.length) {
  236. await priceInfoClassModel.remove({ libID });
  237. await priceInfoClassModel.insertMany(classData);
  238. }
  239. if (data.length) {
  240. await priceInfoItemModel.remove({ libID });
  241. await priceInfoItemModel.insertMany(data);
  242. } else {
  243. throw 'excel没有有效数据。'
  244. }
  245. }
  246. // 导入excel关键字数据(主表+副表),目前只针对珠海,根据列号导入
  247. /*
  248. 主表:主从对应码 别名编码 材料名称 规格 单位 含税价(元) 除税价(元) 月份备注 计算式
  249. 副表:主从对应码 关键字 单位 关键字效果 组别 选项号
  250. */
  251. async function importKeyData(libID, mainData, subData) {
  252. const lib = await priceInfoLibModel.findOne({ ID: libID }).lean();
  253. if (!lib) {
  254. throw new Error('库不存在');
  255. }
  256. const zh = await priceInfoAreaModel.findOne({ name: { $regex: '珠海' } }).lean();
  257. if (!zh) {
  258. throw new Error('该库不存在珠海地区');
  259. }
  260. // 删除珠海地区所有材料
  261. await priceInfoItemModel.deleteMany({ libID, areaID: zh.ID });
  262. const classItems = await priceInfoClassModel.find({ libID, areaID: zh.ID }).lean();
  263. // 分类树前四位编码 - 分类节点ID映射表
  264. let otherClassID = '';
  265. const classMap = {};
  266. classItems.forEach(item => {
  267. if (item.name) {
  268. if (!otherClassID && /其他/.test(item.name)) {
  269. otherClassID = item.ID;
  270. }
  271. const code = item.name.substr(0, 4);
  272. if (/\d{4}/.test(code)) {
  273. classMap[code] = item.ID;
  274. }
  275. }
  276. });
  277. // 主从对应码 - 关键字数组映射
  278. const keywordMap = {};
  279. for (let row = 1; row < subData.length; row++) {
  280. const rowData = subData[row];
  281. const keywordItem = {
  282. code: rowData[0] ? String(rowData[0]) : '',
  283. keyword: rowData[1] || '',
  284. unit: rowData[2] || '',
  285. coe: rowData[3] || '',
  286. group: rowData[4] || '',
  287. optionCode: rowData[5] || '',
  288. };
  289. if (!keywordItem.code) {
  290. continue;
  291. }
  292. (keywordMap[keywordItem.code] || (keywordMap[keywordItem.code] = [])).push(keywordItem);
  293. }
  294. const priceItems = [];
  295. for (let row = 1; row < mainData.length; row++) {
  296. const rowData = mainData[row];
  297. const code = rowData[0] ? String(rowData[0]) : '';
  298. if (!code) {
  299. continue;
  300. }
  301. const matchCode = code.substring(0, 4);
  302. const classID = classMap[matchCode] || otherClassID;
  303. const priceItem = {
  304. code,
  305. libID,
  306. classID,
  307. ID: uuidV1(),
  308. compilationID: lib.compilationID,
  309. areaID: zh.ID,
  310. period: lib.period,
  311. classCode: rowData[1] || '',
  312. name: rowData[2] || '',
  313. specs: rowData[3] || '',
  314. unit: rowData[4] || '',
  315. taxPrice: rowData[5] || '',
  316. noTaxPrice: rowData[6] || '',
  317. dateRemark: rowData[7] || '',
  318. expString: rowData[8] || '',
  319. keywordList: keywordMap[code] || [],
  320. }
  321. priceItems.push(priceItem);
  322. }
  323. if (priceItems.length) {
  324. await priceInfoItemModel.insertMany(priceItems);
  325. }
  326. }
  327. // 获取费用定额的地区数据
  328. async function getAreas(compilationID) {
  329. return await priceInfoAreaModel.find({ compilationID }, '-_id ID name serialNo').lean();
  330. }
  331. async function updateAres(updateData) {
  332. const bulks = [];
  333. updateData.forEach(({ ID, field, value }) => bulks.push({
  334. updateOne: {
  335. filter: { ID },
  336. update: { [field]: value }
  337. }
  338. }));
  339. if (bulks.length) {
  340. await priceInfoAreaModel.bulkWrite(bulks);
  341. }
  342. }
  343. async function insertAreas(insertData) {
  344. await priceInfoAreaModel.insertMany(insertData);
  345. }
  346. async function deleteAreas(deleteData) {
  347. await priceInfoClassModel.remove({ areaID: { $in: deleteData } });
  348. await priceInfoItemModel.remove({ areaID: { $in: deleteData } });
  349. await priceInfoAreaModel.remove({ ID: { $in: deleteData } });
  350. }
  351. async function getClassData(libID, areaID) {
  352. if (libID && areaID) {
  353. return await priceInfoClassModel.find({ libID, areaID }, '-_id').lean();
  354. }
  355. if (libID) {
  356. return await priceInfoClassModel.find({ libID }, '-_id').lean();
  357. }
  358. if (areaID) {
  359. return await priceInfoClassModel.find({ areaID }, '-_id').lean();
  360. }
  361. }
  362. async function getPriceData(classIDList) {
  363. return await priceInfoItemModel.find({ classID: { $in: classIDList } }, '-_id').lean();
  364. }
  365. const UpdateType = {
  366. UPDATE: 'update',
  367. DELETE: 'delete',
  368. CREATE: 'create',
  369. };
  370. async function editPriceData(postData) {
  371. const bulks = [];
  372. postData.forEach(data => {
  373. const filter = { ID: data.ID };
  374. // 为了命中索引,ID暂时还没添加索引,数据量太大,担心内存占用太多
  375. if (data.areaID) {
  376. filter.areaID = data.areaID;
  377. }
  378. if (data.compilationID) {
  379. filter.compilationID = data.compilationID;
  380. }
  381. if (data.period) {
  382. filter.period = data.period;
  383. }
  384. if (data.type === UpdateType.UPDATE) {
  385. bulks.push({
  386. updateOne: {
  387. filter,
  388. update: { ...data.data }
  389. }
  390. });
  391. } else if (data.type === UpdateType.DELETE) {
  392. bulks.push({
  393. deleteOne: {
  394. filter,
  395. }
  396. });
  397. } else {
  398. bulks.push({
  399. insertOne: {
  400. document: data.data
  401. }
  402. });
  403. }
  404. });
  405. if (bulks.length) {
  406. await priceInfoItemModel.bulkWrite(bulks);
  407. }
  408. }
  409. async function editClassData(updateData) {
  410. const bulks = [];
  411. const deleteIDList = [];
  412. updateData.forEach(({ type, filter, update, document }) => {
  413. if (type === UpdateType.UPDATE) {
  414. bulks.push({
  415. updateOne: {
  416. filter,
  417. update
  418. }
  419. });
  420. } else if (type === UpdateType.DELETE) {
  421. deleteIDList.push(filter.ID);
  422. bulks.push({
  423. deleteOne: {
  424. filter
  425. }
  426. });
  427. } else {
  428. bulks.push({
  429. insertOne: {
  430. document
  431. }
  432. });
  433. }
  434. });
  435. if (deleteIDList.length) {
  436. await priceInfoItemModel.remove({ classID: { $in: deleteIDList } });
  437. }
  438. if (bulks.length) {
  439. await priceInfoClassModel.bulkWrite(bulks);
  440. }
  441. }
  442. //计算指标平均值
  443. function calcIndexAvg(period, areaID, compilationID, preCodeMap) {
  444. const newData = [];
  445. for (const code in preCodeMap) {
  446. const indexArr = preCodeMap[code];
  447. let total = 0;
  448. for (const index of indexArr) {
  449. total = scMathUtil.roundForObj(total + index, 2);
  450. }
  451. const avg = scMathUtil.roundForObj(total / indexArr.length, 2);
  452. newData.push({ ID: uuidV1(), code, period, areaID, compilationID, index: avg })
  453. }
  454. return newData
  455. }
  456. //一个月里有classCode相同,但是价格不同的情况,取平均值
  457. function getClassCodePriceAvgMap(items) {
  458. const classCodeMap = {};
  459. for (const b of items) {
  460. classCodeMap[b.classCode] ? classCodeMap[b.classCode].push(b) : classCodeMap[b.classCode] = [b];
  461. }
  462. for (const classCode in classCodeMap) {
  463. const baseItems = classCodeMap[classCode];
  464. const item = baseItems[0];
  465. if (baseItems.length > 1) {
  466. let sum = 0;
  467. for (const b of baseItems) {
  468. sum += parseFloat(b.noTaxPrice);
  469. }
  470. classCodeMap[classCode] = { code: item.code, name: item.name, price: scMathUtil.roundForObj(sum / baseItems.length, 2) };
  471. } else {
  472. classCodeMap[classCode] = { code: item.code, name: item.name, price: parseFloat(item.noTaxPrice) }
  473. }
  474. }
  475. return classCodeMap
  476. }
  477. async function calcPriceIndex(libID, period, areaID, compilationID) {
  478. const baseItems = await priceInfoItemModel.find({ areaID, period: '2022年-01月' }).lean();//以珠海 22年1月的数据为基准
  479. const currentItems = await priceInfoItemModel.find({ areaID, period }).lean();
  480. const preCodeMap = {};//编码前4位-指数映射
  481. const baseAvgMap = getClassCodePriceAvgMap(baseItems);
  482. const currentAvgMap = getClassCodePriceAvgMap(currentItems);
  483. let message = '';
  484. for (const classCode in currentAvgMap) {
  485. const c = currentAvgMap[classCode];
  486. const preCode = c.code.substr(0, 4);
  487. let index = 1;
  488. const baseItem = baseAvgMap[classCode];
  489. const tem = { index, classCode, name: c.name, code: c.code };
  490. if (baseItem && baseItem.price) {//一个月份里有多个值时,先取平均再计算
  491. index = scMathUtil.roundForObj(c.price / baseItem.price, 2);
  492. tem.baseName = baseItem.name;
  493. }
  494. tem.index = index;
  495. if (Math.abs(index - 1) > 0.2) {
  496. const string = `classCode:${tem.classCode},编号:${tem.code},基础名称:${tem.baseName},当前库中名称:${tem.name},指数:${tem.index};\n`;
  497. message += string;
  498. console.log(string)
  499. }
  500. preCodeMap[preCode] ? preCodeMap[preCode].push(index) : preCodeMap[preCode] = [index];
  501. }
  502. const newIndexData = calcIndexAvg(period, areaID, compilationID, preCodeMap)
  503. //删除旧数据
  504. await priceInfoIndexModel.deleteMany({ areaID, period });
  505. //插入新数据
  506. await priceInfoIndexModel.insertMany(newIndexData);
  507. return message;
  508. }
  509. const getMatchSummaryKey = (item) => {
  510. const props = ['name', 'specs', 'unit'];
  511. return props.map(prop => {
  512. const subKey = item[prop] ? item[prop].trim() : '';
  513. return subKey;
  514. }).join('@');
  515. }
  516. const getSummaryMap = (items) => {
  517. const map = {};
  518. items.forEach(item => {
  519. const key = getMatchSummaryKey(item);
  520. map[key] = item;
  521. });
  522. return map;
  523. }
  524. // 匹配总表
  525. // 按规则匹配信息价的编码、别名编码、计算式(只匹配珠海建筑,要单独标记珠海地区);
  526. // 匹配规则:名称+规格型号+单位,与总表一致则自动填入编码、别名编码、计算式(珠海建筑);
  527. const matchSummary = async (compilationID, libID, areaID) => {
  528. const updateBulks = [];
  529. const areaFilter = { compilationID };
  530. if (areaID) {
  531. areaFilter.ID = areaID;
  532. }
  533. const areas = await priceInfoAreaModel.find(areaFilter, '-_id ID name').lean();
  534. const areaNameMap = {};
  535. areas.forEach(area => {
  536. areaNameMap[area.ID] = area.name;
  537. });
  538. const filter = { libID };
  539. if (areaID) {
  540. filter.areaID = areaID;
  541. }
  542. const priceItems = await priceInfoItemModel.find(filter, '-_id ID compilationID name specs unit areaID period').lean();
  543. const summaryItems = await priceInfoSummaryModel.find({}, '-_id ID name specs unit code classCode expString').lean();
  544. const summaryMap = getSummaryMap(summaryItems);
  545. priceItems.forEach(priceItem => {
  546. const key = getMatchSummaryKey(priceItem);
  547. const matched = summaryMap[key];
  548. if (matched) {
  549. const updateObj = {
  550. code: matched.code,
  551. classCode: matched.classCode,
  552. }
  553. console.log(matched);
  554. console.log(updateObj);
  555. const areaName = areaNameMap[priceItem.areaID];
  556. /* if (/珠海/.test(areaName)) {
  557. updateObj.expString = matched.expString;
  558. } */
  559. updateBulks.push({
  560. updateOne: {
  561. filter: { ID: priceItem.ID, compilationID: priceItem.compilationID, areaID: priceItem.areaID, period: priceItem.period },
  562. update: updateObj
  563. }
  564. })
  565. }
  566. });
  567. if (updateBulks.length) {
  568. console.log(`updateBulks.length`, updateBulks.length);
  569. await priceInfoItemModel.bulkWrite(updateBulks);
  570. }
  571. }
  572. // 获取空数据(没有别名编码)
  573. const getPriceEmptyData = async (compilationID, libID, areaID) => {
  574. const lib = await priceInfoLibModel.findOne({ ID: libID }).lean();
  575. if (!lib) {
  576. return [];
  577. }
  578. const filter = { compilationID, libID, period: lib.period };
  579. if (areaID) {
  580. filter.areaID = areaID;
  581. }
  582. const priceItems = await priceInfoItemModel.find(filter).lean();
  583. return priceItems.filter(item => !item.classCode);
  584. };
  585. const getMatchPrice = (allInfoPrice, nameArray, needHandleLongWord = true) => {
  586. let items = [];
  587. let maxNum = 0; // 最大匹配数
  588. const matchMap = {}; // 匹配储存
  589. let handleLongWord = false;
  590. if (needHandleLongWord) {
  591. for (const na of nameArray) {
  592. if (na.length >= 5) handleLongWord = true;
  593. }
  594. }
  595. for (const info of allInfoPrice) {
  596. // specs
  597. const matchString = alias(info.name + info.specs); // 组合名称和规格型号
  598. info.matchString = matchString;
  599. let matchCount = 0;
  600. for (const na of nameArray) {
  601. if (matchString.indexOf(na) !== -1) {
  602. matchCount += 1;
  603. if (needHandleLongWord && na.length >= 5) handleLongWord = false; // 有5个字的,并且匹配上了,这里就为false不用再处理一次了
  604. }
  605. }
  606. if (matchCount > 0) {
  607. if (matchMap[matchCount]) {
  608. matchMap[matchCount].push(info);
  609. } else {
  610. matchMap[matchCount] = [info];
  611. }
  612. if (matchCount > maxNum) maxNum = matchCount;
  613. }
  614. }
  615. if (maxNum > 0) items = matchMap[maxNum];
  616. return { items, handleLongWord };
  617. }
  618. // 获取推荐总表数据
  619. const getRecommendPriceSummaryData = async (keyword) => {
  620. const nameArray = getWordArray(keyword);
  621. console.log(`nameArray`);
  622. console.log(nameArray);
  623. const allItems = await priceInfoSummaryModel.find({}).lean();
  624. let { items } = getMatchPrice(allItems, nameArray);
  625. // 按匹配位置排序 如[ '橡胶', '胶圈', '给水' ] 先显示橡胶
  626. items = _.sortBy(items, item => {
  627. const ms = item.matchString;
  628. for (let i = 0; i < nameArray.length; i += 1) {
  629. if (ms.indexOf(nameArray[i]) !== -1) return i;
  630. }
  631. return 0;
  632. });
  633. return items;
  634. }
  635. // 处理价格¥符号
  636. /* const handlePriceText = async () => {
  637. const libs = await priceInfoLibModel.find({}).lean();
  638. for (const lib of libs) {
  639. const libID = lib.ID;
  640. const bulks = [];
  641. const items = await priceInfoItemModel.find({ libID }, '-_id ID noTaxPrice areaID period').lean();
  642. items.forEach(item => {
  643. if (item.noTaxPrice && /¥/.test(item.noTaxPrice)) {
  644. const noTaxPrice = item.noTaxPrice.replace('¥', '').replace(',', '');
  645. bulks.push({ updateOne: { filter: { ID: item.ID, areaID: item.areaID, period: item.period }, update: { $set: { noTaxPrice } } } });
  646. // bulks.push({ deleteOne: { filter: { ID: item.ID, areaID: item.areaID, period: item.period } } });
  647. }
  648. });
  649. if (bulks.length) {
  650. const chunks = _.chunk(bulks, Math.floor(bulks.length / 500) + 1);
  651. for (const chunk of chunks) {
  652. if (chunk.length) {
  653. await priceInfoItemModel.bulkWrite(chunk);
  654. }
  655. }
  656. }
  657. }
  658. } */
  659. // 删除价格为空的
  660. const handlePriceText = async () => {
  661. const libs = await priceInfoLibModel.find({}).lean();
  662. for (const lib of libs) {
  663. const libID = lib.ID;
  664. const bulks = [];
  665. const items = await priceInfoItemModel.find({ libID }, '-_id ID noTaxPrice areaID period').lean();
  666. items.forEach(item => {
  667. if (!item.noTaxPrice) {
  668. bulks.push({ deleteOne: { filter: { ID: item.ID, areaID: item.areaID, period: item.period } } });
  669. }
  670. });
  671. if (bulks.length) {
  672. const chunks = _.chunk(bulks, Math.floor(bulks.length / 500) + 1);
  673. for (const chunk of chunks) {
  674. if (chunk.length) {
  675. await priceInfoItemModel.bulkWrite(chunk);
  676. }
  677. }
  678. }
  679. }
  680. }
  681. // 按库导出信息价库完整数据,不需要带上地区
  682. async function exportInfoPriceByLib(libID) {
  683. const lib = await priceInfoLibModel.findOne({ ID: libID }).lean();
  684. if (!lib) {
  685. throw new Error('不存在该信息价库!');
  686. }
  687. const { compilationID } = lib;
  688. const priceLibs = await priceInfoLibModel.find({ ID: libID }, '-_id').lean();
  689. const priceClasses = await priceInfoClassModel.find({ libID }, '-_id').lean();
  690. const priceItems = await priceInfoItemModel.find({ libID }, '-_id').lean();
  691. const exportData = { compilationID, priceLibs, priceClasses, priceItems };
  692. const str = JSON.stringify(exportData);
  693. exportData.md5 = sms.md5(str);
  694. return { jsonStr: JSON.stringify(exportData), period: lib.period, name: lib.name };
  695. }
  696. // 按编办导出信息价库完整数据,需要带上地区
  697. async function exportInfoPriceByCompilation(compilationID) {
  698. const areas = await priceInfoAreaModel.find({ compilationID }, '-_id').lean();
  699. const priceLibs = await priceInfoLibModel.find({ compilationID }, '-_id').lean();
  700. const libIDs = priceLibs.map(lib => lib.ID);
  701. const priceClasses = await priceInfoClassModel.find({ libID: { $in: libIDs } }, '-_id').lean();
  702. const priceItems = await priceInfoItemModel.find({ libID: { $in: libIDs } }, '-_id').lean();
  703. const exportData = { compilationID, areas, priceLibs, priceClasses, priceItems };
  704. const str = JSON.stringify(exportData);
  705. exportData.md5 = sms.md5(str);
  706. return { jsonStr: JSON.stringify(exportData), period: lib.period, name: lib.name };
  707. }
  708. module.exports = {
  709. getLibs,
  710. createLib,
  711. updateLib,
  712. deleteLib,
  713. processChecking,
  714. crawlDataByCompilation,
  715. importExcelData,
  716. importKeyData,
  717. getAreas,
  718. updateAres,
  719. insertAreas,
  720. deleteAreas,
  721. getClassData,
  722. calcPriceIndex,
  723. getPriceData,
  724. editPriceData,
  725. editClassData,
  726. matchSummary,
  727. getPriceEmptyData,
  728. getRecommendPriceSummaryData,
  729. handlePriceText,
  730. exportInfoPriceByLib,
  731. exportInfoPriceByCompilation,
  732. getAllLibs,
  733. }