index.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  1. const mongoose = require('mongoose');
  2. const uuidV1 = require('uuid/v1');
  3. const { CRAWL_LOG_KEY, ProcessStatus } = require('../../../public/constants/price_info_constant');
  4. const priceInfoLibModel = mongoose.model('std_price_info_lib');
  5. const priceInfoClassModel = mongoose.model('std_price_info_class');
  6. const priceInfoItemModel = mongoose.model('std_price_info_items');
  7. const priceInfoAreaModel = mongoose.model('std_price_info_areas');
  8. const compilationModel = mongoose.model('compilation');
  9. const importLogsModel = mongoose.model('import_logs');
  10. async function getLibs(query) {
  11. return await priceInfoLibModel.find(query).lean();
  12. }
  13. async function createLib(name, period, compilationID) {
  14. // 将2020-01变成2020年01月
  15. const reg = /(\d{4})-(\d{2})/;
  16. const formattedPeriod = period.replace(reg, '$1年-$2月');
  17. const lib = {
  18. ID: uuidV1(),
  19. name,
  20. period: formattedPeriod,
  21. compilationID,
  22. createDate: Date.now(),
  23. };
  24. await priceInfoLibModel.create(lib);
  25. return lib;
  26. }
  27. async function updateLib(query, updateData) {
  28. await priceInfoLibModel.update(query, updateData);
  29. }
  30. async function deleteLib(libID) {
  31. await priceInfoClassModel.remove({ libID });
  32. await priceInfoItemModel.remove({ libID });
  33. await priceInfoLibModel.remove({ ID: libID });
  34. }
  35. async function processChecking(key) {
  36. const logData = key
  37. ? await importLogsModel.findOne({ key })
  38. : await importLogsModel.findOne({ key: CRAWL_LOG_KEY });
  39. if (!logData) {
  40. return { status: ProcessStatus.FINISH };
  41. }
  42. if (logData.status === ProcessStatus.FINISH || logData.status === ProcessStatus.ERROR) {
  43. await importLogsModel.remove({ key: logData.key });
  44. }
  45. return { status: logData.status, errorMsg: logData.errorMsg || '', key: logData.key };
  46. }
  47. // 爬取数据
  48. async function crawlDataByCompilation(compilationID, from, to) {
  49. if (!compilationID) {
  50. throw '无有效费用定额。';
  51. }
  52. const compilationData = await compilationModel.findOne({ _id: mongoose.Types.ObjectId(compilationID) }, 'overWriteUrl').lean();
  53. if (!compilationData || !compilationData.overWriteUrl) {
  54. throw '无有效费用定额。';
  55. }
  56. // 从overWriteUrl提取并组装爬虫文件
  57. const reg = /\/([^/]+)\.js/;
  58. const matched = compilationData.overWriteUrl.match(reg);
  59. const crawlURL = `${matched[1]}_price_crawler.js`;
  60. let crawlData;
  61. try {
  62. const crawler = require(`../../../web/over_write/crawler/${crawlURL}`);
  63. crawlData = crawler.crawlData;
  64. } catch (e) {
  65. console.log(e);
  66. throw '该费用定额无可用爬虫方法。'
  67. }
  68. //await crawlData(from, to);
  69. // 异步不等结果,结果由checking来获取
  70. crawlDataByMiddleware(crawlData, from, to, compilationID);
  71. }
  72. // 爬取数据中间件,主要处理checking初始化
  73. async function crawlDataByMiddleware(crawlFunc, from, to, compilationID) {
  74. const logUpdateData = { status: ProcessStatus.FINISH };
  75. try {
  76. const logData = {
  77. key: CRAWL_LOG_KEY,
  78. content: '正在爬取数据,请稍候……',
  79. status: ProcessStatus.START,
  80. create_time: Date.now()
  81. };
  82. await importLogsModel.create(logData);
  83. await crawlFunc(from, to, compilationID);
  84. } catch (err) {
  85. console.log(err);
  86. logUpdateData.errorMsg = String(err);
  87. logUpdateData.status = ProcessStatus.ERROR;
  88. } finally {
  89. await importLogsModel.update({ key: CRAWL_LOG_KEY }, logUpdateData);
  90. }
  91. }
  92. // 导入excel数据,格式如下
  93. // 格式1:
  94. //地区 分类 编码 名称 规格型号 单位 不含税价 含税价
  95. //江北区 黑色及有色金属 热轧光圆钢筋 φ6(6.5) 3566.37 4030
  96. //江北区 木、竹材料及其制品 柏木门套线 60×10 8.76 9.9
  97. // 格式2:
  98. //地区 分类 编码 名称 规格型号 不含税价 含税价
  99. //江北区 黑色及有色金属 热轧光圆钢筋 φ6(6.5) 3566.37 4030
  100. // 柏木门套线 60×10 8.76 9.9
  101. // 沥青混凝土 AC-13 982.3 1110
  102. //
  103. //北碚区 木、竹材料及其制品 热轧光圆钢筋 φ6(6.5) 3566.37 4030
  104. async function importExcelData(libID, sheetData) {
  105. const libs = await getLibs({ ID: libID });
  106. const compilationID = libs[0].compilationID;
  107. // 建立区映射表:名称-ID映射、ID-名称映射
  108. const areaList = await getAreas(compilationID);
  109. const areaMap = {};
  110. areaList.forEach(({ ID, name }) => {
  111. areaMap[name] = ID;
  112. areaMap[ID] = name;
  113. });
  114. // 建立分类映射表:地区名称@分类名称:ID映射
  115. /* const classMap = {};
  116. const classList = await getClassData(libID);
  117. classList.forEach(({ ID, areaID, name }) => {
  118. const areaName = areaMap[areaID] || '';
  119. classMap[`${areaName}@${name}`] = ID;
  120. }); */
  121. // 第一行获取行映射
  122. const colMap = {};
  123. for (let col = 0; col < sheetData[0].length; col++) {
  124. const cellText = sheetData[0][col];
  125. switch (cellText) {
  126. case '地区':
  127. colMap.area = col;
  128. break;
  129. case '分类':
  130. colMap.class = col;
  131. break;
  132. case '编码':
  133. colMap.code = col;
  134. break;
  135. case '名称':
  136. colMap.name = col;
  137. break;
  138. case '规格型号':
  139. colMap.specs = col;
  140. break;
  141. case '单位':
  142. colMap.unit = col;
  143. break;
  144. case '不含税价':
  145. colMap.noTaxPrice = col;
  146. break;
  147. case '含税价':
  148. colMap.taxPrice = col;
  149. break;
  150. }
  151. }
  152. // 提取数据
  153. const data = [];
  154. const classData = [];
  155. const areaClassDataMap = {};
  156. let curAreaName;
  157. let curClassName;
  158. let curClassID;
  159. for (let row = 1; row < sheetData.length; row++) {
  160. const areaName = sheetData[row][colMap.area] || '';
  161. const className = sheetData[row][colMap.class] || '';
  162. const code = sheetData[row][colMap.code] || '';
  163. const name = sheetData[row][colMap.name] || '';
  164. const specs = sheetData[row][colMap.specs] || '';
  165. const unit = sheetData[row][colMap.unit] || '';
  166. const noTaxPrice = sheetData[row][colMap.noTaxPrice] || '';
  167. const taxPrice = sheetData[row][colMap.taxPrice] || '';
  168. if (!className && !code && !name && !specs && !noTaxPrice && !taxPrice) { // 认为是空数据
  169. continue;
  170. }
  171. if (areaName && areaName !== curAreaName) {
  172. curAreaName = areaName;
  173. }
  174. const areaID = areaMap[curAreaName];
  175. if (!areaID) {
  176. continue;
  177. }
  178. if (className && className !== curClassName) {
  179. curClassName = className;
  180. const classItem = {
  181. libID,
  182. areaID,
  183. ID: uuidV1(),
  184. ParentID: '-1',
  185. NextSiblingID: '-1',
  186. name: curClassName
  187. };
  188. curClassID = classItem.ID;
  189. classData.push(classItem);
  190. (areaClassDataMap[areaID] || (areaClassDataMap[areaID] = [])).push(classItem);
  191. const preClassItem = areaClassDataMap[areaID][areaClassDataMap[areaID].length - 2];
  192. if (preClassItem) {
  193. preClassItem.NextSiblingID = classItem.ID;
  194. }
  195. }
  196. if (!curClassID) {
  197. continue;
  198. }
  199. data.push({
  200. ID: uuidV1(),
  201. compilationID,
  202. libID,
  203. areaID,
  204. classID: curClassID,
  205. period: libs[0].period,
  206. code,
  207. name,
  208. specs,
  209. unit,
  210. noTaxPrice,
  211. taxPrice
  212. });
  213. }
  214. if (classData.length) {
  215. await priceInfoClassModel.remove({ libID });
  216. await priceInfoClassModel.insertMany(classData);
  217. }
  218. if (data.length) {
  219. await priceInfoItemModel.remove({ libID });
  220. await priceInfoItemModel.insertMany(data);
  221. } else {
  222. throw 'excel没有有效数据。'
  223. }
  224. }
  225. // 导入excel关键字数据(主表+副表),目前只针对珠海,根据列号导入
  226. /*
  227. 主表:主从对应码 别名编码 材料名称 规格 单位 含税价(元) 除税价(元) 月份备注 计算式
  228. 副表:主从对应码 关键字 单位 关键字效果 组别 选项号
  229. */
  230. async function importKeyData(libID, mainData, subData) {
  231. const lib = await priceInfoLibModel.findOne({ ID: libID }).lean();
  232. if (!lib) {
  233. throw new Error('库不存在');
  234. }
  235. const zh = await priceInfoAreaModel.findOne({ name: { $regex: '珠海' } }).lean();
  236. if (!zh) {
  237. throw new Error('该库不存在珠海地区');
  238. }
  239. // 删除珠海地区所有材料
  240. await priceInfoItemModel.deleteMany({ libID, areaID: zh.ID });
  241. const classItems = await priceInfoClassModel.find({ libID, areaID: zh.ID }).lean();
  242. // 分类树前四位编码 - 分类节点ID映射表
  243. let otherClassID = '';
  244. const classMap = {};
  245. classItems.forEach(item => {
  246. if (item.name) {
  247. if (!otherClassID && /其他/.test(item.name)) {
  248. otherClassID = item.ID;
  249. }
  250. const code = item.name.substr(0, 4);
  251. if (/\d{4}/.test(code)) {
  252. classMap[code] = item.ID;
  253. }
  254. }
  255. });
  256. // 主从对应码 - 关键字数组映射
  257. const keywordMap = {};
  258. for (let row = 1; row < subData.length; row++) {
  259. const rowData = subData[row];
  260. const keywordItem = {
  261. code: rowData[0] || '',
  262. keyword: rowData[1] || '',
  263. unit: rowData[2] || '',
  264. coe: rowData[3] || '',
  265. group: rowData[4] || '',
  266. optionCode: rowData[5] || '',
  267. };
  268. (keywordMap[keywordItem.code] || (keywordMap[keywordItem.code] = [])).push(keywordItem);
  269. }
  270. const priceItems = [];
  271. for (let row = 1; row < mainData.length; row++) {
  272. const rowData = mainData[row];
  273. const code = rowData[0] || '';
  274. const matchCode = code.substr(0, 4);
  275. const classID = classMap[matchCode] || otherClassID;
  276. const priceItem = {
  277. code,
  278. libID,
  279. classID,
  280. ID: uuidV1(),
  281. compilationID: lib.compilationID,
  282. areaID: zh.ID,
  283. period: lib.period,
  284. classCode: rowData[1] || '',
  285. name: rowData[2] || '',
  286. specs: rowData[3] || '',
  287. unit: rowData[4] || '',
  288. taxPrice: rowData[5] || '',
  289. noTaxPrice: rowData[6] || '',
  290. dateRemark: rowData[7] || '',
  291. expString: rowData[8] || '',
  292. keywordList: keywordMap[code] || [],
  293. }
  294. priceItems.push(priceItem);
  295. }
  296. if (priceItems.length) {
  297. await priceInfoItemModel.insertMany(priceItems);
  298. }
  299. }
  300. /* async function importExcelData(libID, sheetData) {
  301. const libs = await getLibs({ ID: libID });
  302. const compilationID = libs[0].compilationID;
  303. // 建立区映射表:名称-ID映射、ID-名称映射
  304. const areaList = await getAreas(compilationID);
  305. const areaMap = {};
  306. areaList.forEach(({ ID, name }) => {
  307. areaMap[name] = ID;
  308. areaMap[ID] = name;
  309. });
  310. // 建立分类映射表:地区名称@分类名称:ID映射
  311. const classMap = {};
  312. const classList = await getClassData(libID);
  313. classList.forEach(({ ID, areaID, name }) => {
  314. const areaName = areaMap[areaID] || '';
  315. classMap[`${areaName}@${name}`] = ID;
  316. });
  317. // 第一行获取行映射
  318. const colMap = {};
  319. for (let col = 0; col < sheetData[0].length; col++) {
  320. const cellText = sheetData[0][col];
  321. switch (cellText) {
  322. case '地区':
  323. colMap.area = col;
  324. break;
  325. case '分类':
  326. colMap.class = col;
  327. break;
  328. case '编码':
  329. colMap.code = col;
  330. break;
  331. case '名称':
  332. colMap.name = col;
  333. break;
  334. case '规格型号':
  335. colMap.specs = col;
  336. break;
  337. case '单位':
  338. colMap.unit = col;
  339. break;
  340. case '不含税价':
  341. colMap.noTaxPrice = col;
  342. break;
  343. case '含税价':
  344. colMap.taxPrice = col;
  345. break;
  346. }
  347. }
  348. // 提取数据
  349. const data = [];
  350. let curAreaName;
  351. let curClassName;
  352. for (let row = 1; row < sheetData.length; row++) {
  353. const areaName = sheetData[row][colMap.area] || '';
  354. const className = sheetData[row][colMap.class] || '';
  355. const code = sheetData[row][colMap.code] || '';
  356. const name = sheetData[row][colMap.name] || '';
  357. const specs = sheetData[row][colMap.specs] || '';
  358. const unit = sheetData[row][colMap.unit] || '';
  359. const noTaxPrice = sheetData[row][colMap.noTaxPrice] || '';
  360. const taxPrice = sheetData[row][colMap.taxPrice] || '';
  361. if (!code && !name && !specs && !noTaxPrice && !taxPrice) { // 认为是空数据
  362. continue;
  363. }
  364. if (areaName && areaName !== curAreaName) {
  365. curAreaName = areaName;
  366. }
  367. if (className && className !== curClassName) {
  368. curClassName = className;
  369. }
  370. const areaID = areaMap[curAreaName];
  371. if (!areaID) {
  372. continue;
  373. }
  374. const classID = classMap[`${curAreaName}@${curClassName}`];
  375. if (!classID) {
  376. continue;
  377. }
  378. data.push({
  379. ID: uuidV1(),
  380. compilationID,
  381. libID,
  382. areaID,
  383. classID,
  384. period: libs[0].period,
  385. code,
  386. name,
  387. specs,
  388. unit,
  389. noTaxPrice,
  390. taxPrice
  391. });
  392. }
  393. if (data.length) {
  394. await priceInfoItemModel.remove({ libID });
  395. await priceInfoItemModel.insertMany(data);
  396. } else {
  397. throw 'excel没有有效数据。'
  398. }
  399. } */
  400. // 获取费用定额的地区数据
  401. async function getAreas(compilationID) {
  402. return await priceInfoAreaModel.find({ compilationID }, '-_id ID name serialNo').lean();
  403. }
  404. async function updateAres(updateData) {
  405. const bulks = [];
  406. updateData.forEach(({ ID, name }) => bulks.push({
  407. updateOne: {
  408. filter: { ID },
  409. update: { name }
  410. }
  411. }));
  412. if (bulks.length) {
  413. await priceInfoAreaModel.bulkWrite(bulks);
  414. }
  415. }
  416. async function insertAreas(insertData) {
  417. await priceInfoAreaModel.insertMany(insertData);
  418. }
  419. async function deleteAreas(deleteData) {
  420. await priceInfoClassModel.remove({ areaID: { $in: deleteData } });
  421. await priceInfoItemModel.remove({ areaID: { $in: deleteData } });
  422. await priceInfoAreaModel.remove({ ID: { $in: deleteData } });
  423. }
  424. async function getClassData(libID, areaID) {
  425. if (libID && areaID) {
  426. return await priceInfoClassModel.find({ libID, areaID }, '-_id').lean();
  427. }
  428. if (libID) {
  429. return await priceInfoClassModel.find({ libID }, '-_id').lean();
  430. }
  431. if (areaID) {
  432. return await priceInfoClassModel.find({ areaID }, '-_id').lean();
  433. }
  434. }
  435. async function getPriceData(classIDList) {
  436. return await priceInfoItemModel.find({ classID: { $in: classIDList } }, '-_id').lean();
  437. }
  438. const UpdateType = {
  439. UPDATE: 'update',
  440. DELETE: 'delete',
  441. CREATE: 'create',
  442. };
  443. async function editPriceData(postData) {
  444. const bulks = [];
  445. postData.forEach(data => {
  446. if (data.type === UpdateType.UPDATE) {
  447. bulks.push({
  448. updateOne: {
  449. filter: { ID: data.ID },
  450. update: { ...data.data }
  451. }
  452. });
  453. } else if (data.type === UpdateType.DELETE) {
  454. bulks.push({
  455. deleteOne: {
  456. filter: { ID: data.ID }
  457. }
  458. });
  459. } else {
  460. bulks.push({
  461. insertOne: {
  462. document: data.data
  463. }
  464. });
  465. }
  466. });
  467. if (bulks.length) {
  468. await priceInfoItemModel.bulkWrite(bulks);
  469. }
  470. }
  471. async function editClassData(updateData) {
  472. const bulks = [];
  473. const deleteIDList = [];
  474. updateData.forEach(({ type, filter, update, document }) => {
  475. if (type === UpdateType.UPDATE) {
  476. bulks.push({
  477. updateOne: {
  478. filter,
  479. update
  480. }
  481. });
  482. } else if (type === UpdateType.DELETE) {
  483. deleteIDList.push(filter.ID);
  484. bulks.push({
  485. deleteOne: {
  486. filter
  487. }
  488. });
  489. } else {
  490. bulks.push({
  491. insertOne: {
  492. document
  493. }
  494. });
  495. }
  496. });
  497. if (deleteIDList.length) {
  498. await priceInfoItemModel.remove({ classID: { $in: deleteIDList } });
  499. }
  500. if (bulks.length) {
  501. await priceInfoClassModel.bulkWrite(bulks);
  502. }
  503. }
  504. module.exports = {
  505. getLibs,
  506. createLib,
  507. updateLib,
  508. deleteLib,
  509. processChecking,
  510. crawlDataByCompilation,
  511. importExcelData,
  512. importKeyData,
  513. getAreas,
  514. updateAres,
  515. insertAreas,
  516. deleteAreas,
  517. getClassData,
  518. getPriceData,
  519. editPriceData,
  520. editClassData
  521. }