guangdong_2018_price_crawler.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. /*
  2. * @Descripttion: 广东材料信息价格获取(通过造价通接口)
  3. * @Author: vian
  4. * @Date: 2020-09-29 11:22:59
  5. */
  6. module.exports = {
  7. crawlData,
  8. };
  9. const uuidV1 = require('uuid/v1');
  10. const mongoose = require('mongoose');
  11. const axios = require('axios');
  12. const querystring = require('querystring');
  13. const priceInfoLibModel = mongoose.model('std_price_info_lib');
  14. const priceInfoClassModel = mongoose.model('std_price_info_class');
  15. const priceInfoAreaModel = mongoose.model('std_price_info_areas');
  16. const priceInfoItemModel = mongoose.model('std_price_info_items');
  17. const priceInfoSourceModel = mongoose.model('std_price_info_source');
  18. const gljLibModel = mongoose.model('std_glj_lib_map');
  19. const gljClassModel = mongoose.model('std_glj_lib_gljClass');
  20. // 造价通网页上整理的地区https://gd.zjtcn.com/gov/c_cs_d_t_p1.html
  21. const areas = [
  22. { city: '广州市', county: '广州市' },
  23. { city: '广州市', county: '花都区' },
  24. { city: '广州市', county: '增城市' },
  25. { city: '广州市', county: '从化市' },
  26. { city: '韶关市', county: '韶关市' },
  27. { city: '韶关市', county: '乐昌市' },
  28. { city: '深圳市', county: '深圳市' },
  29. { city: '珠海市', county: '珠海市' },
  30. { city: '汕头市', county: '汕头市' },
  31. { city: '汕头市', county: '濠江区' },
  32. { city: '汕头市', county: '潮阳区' },
  33. { city: '汕头市', county: '潮南区' },
  34. { city: '汕头市', county: '澄海区' },
  35. { city: '汕头市', county: '南澳县' },
  36. { city: '佛山市', county: '佛山市' },
  37. { city: '佛山市', county: '南海区' },
  38. { city: '佛山市', county: '顺德区' },
  39. { city: '江门市', county: '江门市' },
  40. { city: '江门市', county: '新会区' },
  41. { city: '江门市', county: '台山市' },
  42. { city: '江门市', county: '开平市' },
  43. { city: '江门市', county: '鹤山市' },
  44. { city: '江门市', county: '恩平市' },
  45. { city: '湛江市', county: '湛江市' },
  46. { city: '湛江市', county: '遂溪县' },
  47. { city: '湛江市', county: '徐闻县' },
  48. { city: '湛江市', county: '廉江市' },
  49. { city: '湛江市', county: '雷州市' },
  50. { city: '湛江市', county: '吴川市' },
  51. { city: '茂名市', county: '茂名市' },
  52. { city: '茂名市', county: '电白市' },
  53. { city: '茂名市', county: '高州市' },
  54. { city: '茂名市', county: '化州市' },
  55. { city: '茂名市', county: '信宜市' },
  56. { city: '肇庆市', county: '肇庆市' },
  57. { city: '肇庆市', county: '鼎湖区' },
  58. { city: '肇庆市', county: '广宁县' },
  59. { city: '肇庆市', county: '怀集县' },
  60. { city: '肇庆市', county: '封开县' },
  61. { city: '肇庆市', county: '德庆县' },
  62. { city: '肇庆市', county: '高要市' },
  63. { city: '肇庆市', county: '四会市' },
  64. { city: '惠州市', county: '惠州市' },
  65. { city: '惠州市', county: '惠阳区' },
  66. { city: '惠州市', county: '大亚湾开发区' },
  67. { city: '惠州市', county: '博罗县' },
  68. { city: '惠州市', county: '惠东县' },
  69. { city: '惠州市', county: '龙门县' },
  70. { city: '梅州市', county: '梅州市' },
  71. { city: '梅州市', county: '梅县' },
  72. { city: '梅州市', county: '大埔县' },
  73. { city: '梅州市', county: '丰顺县' },
  74. { city: '梅州市', county: '平远县' },
  75. { city: '汕尾市', county: '汕尾市' },
  76. { city: '汕尾市', county: '海丰县' },
  77. { city: '汕尾市', county: '陆河县' },
  78. { city: '河源市', county: '河源市' },
  79. { city: '河源市', county: '紫金县' },
  80. { city: '河源市', county: '龙川县' },
  81. { city: '河源市', county: '连平县' },
  82. { city: '河源市', county: '和平县' },
  83. { city: '河源市', county: '东源县' },
  84. { city: '阳江市', county: '阳江市' },
  85. { city: '阳江市', county: '海陵岛区' },
  86. { city: '阳江市', county: '阳西县' },
  87. { city: '阳江市', county: '阳春市' },
  88. { city: '清远市', county: '清远市' },
  89. { city: '清远市', county: '佛冈县' },
  90. { city: '清远市', county: '阳山县' },
  91. { city: '清远市', county: '连山县' },
  92. { city: '清远市', county: '连南县' },
  93. { city: '清远市', county: '英德市' },
  94. { city: '清远市', county: '连州市' },
  95. { city: '东莞市', county: '东莞市' },
  96. { city: '中山市', county: '中山市' },
  97. { city: '潮州市', county: '潮州市' },
  98. { city: '潮州市', county: '潮安县' },
  99. { city: '潮州市', county: '饶平县' },
  100. { city: '揭阳市', county: '揭阳市' },
  101. { city: '揭阳市', county: '揭西县' },
  102. { city: '揭阳市', county: '惠来县' },
  103. { city: '揭阳市', county: '普宁市' },
  104. { city: '云浮市', county: '云浮市' },
  105. { city: '云浮市', county: '新兴县' },
  106. { city: '云浮市', county: '郁南县' },
  107. { city: '云浮市', county: '罗定市' },
  108. ];
  109. const TIME_OUT = 120000;
  110. // 创建axios实例
  111. const axiosConfig = {
  112. baseURL: 'http://api.zjtcn.com/user',
  113. timeout: TIME_OUT,
  114. /* proxy: {
  115. host: "127.0.0.1", port: "8888" // Fiddler抓包,需要打开Fiddler否则会报connect error
  116. }, */
  117. headers: {
  118. 'Cache-Control': 'max-age=0',
  119. 'Content-Type': 'application/x-www-form-urlencoded',
  120. 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36',
  121. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
  122. 'Accept-Encoding': 'gzip, deflate',
  123. 'Accept-Language': 'zh-TW,zh;q=0.9,en-US;q=0.8,en;q=0.7,zh-CN;q=0.6',
  124. },
  125. //responseType: 'document'
  126. };
  127. const axiosInstance = axios.create(axiosConfig);
  128. console.log('axiosConfig=-========================================');
  129. console.log(axiosConfig);
  130. // 响应拦截器
  131. axiosInstance.interceptors.response.use(function (response) {
  132. return response.data;
  133. }, function (error) {
  134. // 对响应错误做点什么
  135. if (error.message.includes('timeout')) {
  136. return Promise.reject(`目标网络超时,请稍后再试。(${TIME_OUT}ms)`);
  137. } else {
  138. return Promise.reject(error);
  139. }
  140. });
  141. async function post(url, data) {
  142. if (url === '/dyn_code') {
  143. console.log(axiosInstance);
  144. }
  145. return await axiosInstance.post(url, querystring.stringify(data));
  146. }
  147. // 有效期一年,通过购买造价通服务获得
  148. const SERVICE_ID = '2020090003';
  149. const SERVICE_KEY = '97F2A441633F10DFEB5BFC29B3862847';
  150. // 获取后续获取信息价期刊必要的token
  151. async function getToken() {
  152. // 获取动态码
  153. const dynData = await post('/dyn_code', { service_id: SERVICE_ID });
  154. if (!dynData.response_code) {
  155. throw `错误代号${dynData.retCode} 获取动态码失败。`;
  156. }
  157. // 获取加密字符串
  158. const serviceSecret = await post('/aes', { service_id: SERVICE_ID, service_key: SERVICE_KEY, service_code: dynData.response_code });
  159. if (typeof serviceSecret !== 'string') {
  160. throw `错误代号${serviceSecret.retCode} 获取加密字符串错误。`;
  161. }
  162. const tokenData = await post('/authentication', { service_id: SERVICE_ID, service_secret: serviceSecret });
  163. if (!tokenData.token) {
  164. throw `错误代号${tokenData.retCode} 获取token失败。`
  165. }
  166. return tokenData.token;
  167. }
  168. const monthMap = {
  169. '1': '01月',
  170. '2': '02月',
  171. '3': '03月',
  172. '4': '04月',
  173. '5': '05月',
  174. '6': '06月',
  175. '7': '07月',
  176. '8': '08月',
  177. '9': '09月',
  178. '10': '10月',
  179. '11': '11月',
  180. '12': '12月',
  181. };
  182. // 根据期数范围,获取期数数据
  183. function getPeriodData(from, to) {
  184. if (from > to) {
  185. return null;
  186. }
  187. const reg = /(\d+)-(\d+)/;
  188. const fromMatch = from.match(reg);
  189. const fromYear = +fromMatch[1];
  190. const fromMonth = +fromMatch[2];
  191. const toMatch = to.match(reg);
  192. const toYear = +toMatch[1];
  193. const toMonth = +toMatch[2];
  194. let curYear = fromYear;
  195. let curMonth = fromMonth;
  196. const periods = [];
  197. while (curYear <= toYear && curMonth <= toMonth) {
  198. periods.push(`${curYear}年-${monthMap[curMonth]}`);
  199. if (curMonth === 12) {
  200. curYear++;
  201. curMonth = 1;
  202. } else {
  203. curMonth++;
  204. }
  205. }
  206. return periods;
  207. }
  208. // 获取信息价期刊
  209. async function getPriceInfoSource(token, period, city, county) {
  210. const province = '广东';
  211. const area = `${province}-${city}-${county}`;
  212. const industry = 1;
  213. const existData = await priceInfoSourceModel.find({ period, area, industry }).lean();
  214. if (existData.length) {
  215. return existData;
  216. }
  217. const body = {
  218. token,
  219. province,
  220. city,
  221. county,
  222. industry,
  223. date: `${period}-05` // 天数05表示请求月度数据
  224. };
  225. const sourceData = await post('/gov/get', body);
  226. if (!sourceData.results) {
  227. // 不抛出错误,不同地区更新信息价期刊的时间不同,如果导入数据时,有地区没发布数据,直接跳过并提示
  228. return `retCode: ${sourceData.retCode} ${sourceData.msg} (${period} ${city} ${county})`;
  229. }
  230. // 因为造价通接口请求有次数限制,一个地区只能请求一次,为保险起见,将造价通源数据入库
  231. const insertData = sourceData.results.map(item => ({
  232. period,
  233. area,
  234. industry,
  235. subcid: item.subcid,
  236. code: item.code,
  237. name: item.name,
  238. unit: item.unit,
  239. price: item.price,
  240. taxPrice: item.tax_price,
  241. noTaxPrice: item.no_tax_price,
  242. specs: item.spec,
  243. remark: item.notes,
  244. }));
  245. if (insertData.length) {
  246. await priceInfoSourceModel.insertMany(insertData);
  247. }
  248. return insertData;
  249. }
  250. // 获取数据subcid与分类名称的映射表
  251. async function getClassNameMap(compilationID) {
  252. const gljLib = await gljLibModel.findOne({ compilationId: compilationID }).lean();
  253. if (!gljLib) {
  254. return null;
  255. }
  256. const classData = await gljClassModel.find({ repositoryId: gljLib.ID }).lean();
  257. const map = {};
  258. const reg = /^\d{4}/;
  259. classData.forEach(item => {
  260. const name = item.Name || '';
  261. const matched = name.match(reg);
  262. if (matched) {
  263. map[matched[0]] = name;
  264. }
  265. });
  266. return map;
  267. }
  268. /**
  269. * 将信息价源数据转换入库
  270. * @param {String} compilationID - 费用定额ID
  271. * @param {String} period - 期数 eg: 2020年-09月
  272. * @param {String} areaID - 地区ID
  273. * @param {Array} sourceData - 造价通源数据
  274. * @param {Object} classNameMap - 从标准人材机分类树获取的编号-名称映射表
  275. * @return {Void}
  276. */
  277. async function saveData(compilationID, period, areaID, sourceData, classNameMap) {
  278. let lib = await priceInfoLibModel.findOne({ compilationID, period }).lean();
  279. if (!lib) {
  280. lib = {
  281. compilationID,
  282. period,
  283. ID: uuidV1(),
  284. name: `信息价(${period})`,
  285. createDate: Date.now()
  286. };
  287. await priceInfoLibModel.insertMany([lib]);
  288. }
  289. const libID = lib.ID;
  290. // 如果该期数该地区下存在数据,则不处理,防止重复插入数据
  291. // 造价通地区数据更新不同步,可能需要多次导入数据补全一期数据,如果已经有数据,说明该地区已经导入成功过了,直接跳过
  292. const existCount = await priceInfoItemModel.count({ compilationID, period, areaID });
  293. if (existCount) {
  294. return;
  295. }
  296. // 分类数据应为空才对,如果有就清空
  297. const existClassCount = await priceInfoClassModel.count({ libID: lib.ID, areaID });
  298. if (existClassCount) {
  299. await priceInfoClassModel.remove({ libID: lib.ID, areaID });
  300. }
  301. // 导入分类数据及价格信息数据
  302. const otherClassName = '其他';
  303. const curClassMap = {
  304. [otherClassName]: { libID, areaID, ID: uuidV1(), ParentID: '-1', name: otherClassName }
  305. };
  306. const classData = [];
  307. const priceData = [];
  308. const splitReg = /([0-9.]+)-([0-9.]+)/;
  309. let needOtherClass = false;
  310. sourceData.forEach(item => {
  311. const className = classNameMap[item.subcid] || otherClassName;
  312. if (className === otherClassName) {
  313. needOtherClass = true;
  314. }
  315. if (!curClassMap[className]) {
  316. const classItem = { libID, areaID, ID: uuidV1(), ParentID: '-1', NextSiblingID: '-1', name: className };
  317. curClassMap[className] = classItem;
  318. /* const preClassData = classData[classData.length - 1];
  319. if (preClassData) {
  320. preClassData.NextSiblingID = classItem.ID;
  321. } */
  322. classData.push(classItem);
  323. }
  324. const classID = curClassMap[className].ID;
  325. const price = item.price || '';
  326. const matchSplitPrice = price.match(splitReg);
  327. if (matchSplitPrice) { // 价格字段是区间,需要分割成最低价、最高价两条数据
  328. const minPrice = matchSplitPrice[1];
  329. const maxPrice = matchSplitPrice[2];
  330. priceData.push(transfromSourceItemToPriceItem(item, classID, `${item.name}-最低价`, minPrice));
  331. priceData.push(transfromSourceItemToPriceItem(item, classID, `${item.name}-最高价`, maxPrice));
  332. } else {
  333. priceData.push(transfromSourceItemToPriceItem(item, classID, item.name, item.noTaxPrice));
  334. }
  335. });
  336. // 分类按分类编号排序
  337. classData.sort((a, b) => a.name.localeCompare(b.name));
  338. classData.forEach((classItem, index) => {
  339. const preClassItem = classData[index - 1];
  340. if (preClassItem) {
  341. preClassItem.NextSiblingID = classItem.ID;
  342. }
  343. });
  344. if (needOtherClass) {
  345. const otherClassItem = curClassMap[otherClassName];
  346. otherClassItem.NextSiblingID = classData[0].ID;
  347. classData.push(otherClassItem);
  348. }
  349. const task = [
  350. priceInfoClassModel.insertMany(classData),
  351. priceInfoItemModel.insertMany(priceData)
  352. ];
  353. await Promise.all(task);
  354. // 将信息价源数据转换成信息价数据
  355. function transfromSourceItemToPriceItem(sourceItem, classID, name, noTaxPrice) {
  356. if (/(m³)|(m²)/.test(sourceItem.unit)) {
  357. sourceItem.unit = sourceItem.unit.replace(/m³/g, 'm3');
  358. sourceItem.unit = sourceItem.unit.replace(/m²/g, 'm2');
  359. }
  360. return {
  361. compilationID,
  362. period,
  363. name,
  364. noTaxPrice,
  365. classID,
  366. libID,
  367. areaID,
  368. ID: uuidV1(),
  369. code: sourceItem.subcid,
  370. unit: sourceItem.unit,
  371. specs: sourceItem.specs,
  372. taxPrice: sourceItem.taxPrice,
  373. remark: sourceItem.remark,
  374. };
  375. }
  376. }
  377. /**
  378. * 获取数据
  379. * @param {String} from - 从哪一期开始 eg: 2020-01
  380. * @param {String} to - 从哪一期结束 eg: 2020-05
  381. * @param {String} compilationID - 费用定额ID
  382. * @return {Object}
  383. */
  384. async function crawlData(from, to, compilationID) {
  385. const token = await getToken();
  386. const periods = getPeriodData(from, to);
  387. if (!periods) {
  388. throw '无效的期数区间。';
  389. }
  390. const classNameMap = await getClassNameMap(compilationID);
  391. if (!classNameMap) {
  392. throw '无有效的分类数据。';
  393. }
  394. const hintInfos = [];
  395. for (const period of periods) {
  396. const sourcePeriod = period.replace(/年|月/g, '');
  397. for (let i = 0; i < areas.length; i++) {
  398. // 存入地区
  399. const { city, county } = areas[i];
  400. const area = `${city}-${county}`;
  401. let areaItem = await priceInfoAreaModel.findOne({ compilationID, name: area }).lean();
  402. const serialNo = i + 1;
  403. if (!areaItem) {
  404. areaItem = { compilationID, serialNo, ID: uuidV1(), name: area };
  405. await priceInfoAreaModel.insertMany([areaItem]);
  406. } else if (!areaItem.serialNo) { // 需求变更,需要排序,旧数据可能没有排序字段,需要加上
  407. await priceInfoAreaModel.update({ ID: areaItem.ID }, { $set: { serialNo } });
  408. }
  409. // 存入信息价相关数据
  410. const sourceData = await getPriceInfoSource(token, sourcePeriod, city, county);
  411. if (typeof sourceData === 'string') {
  412. hintInfos.push(sourceData);
  413. continue;
  414. }
  415. if (!sourceData.length) {
  416. continue;
  417. }
  418. await saveData(compilationID, period, areaItem.ID, sourceData, classNameMap);
  419. }
  420. }
  421. if (hintInfos.length) {
  422. throw hintInfos.join('\n');
  423. }
  424. }