data_processor.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. package ruizide
  2. import (
  3. "context"
  4. "encoding/json"
  5. "eta/eta_data_analysis/models"
  6. "eta/eta_data_analysis/utils"
  7. "fmt"
  8. "github.com/chromedp/cdproto/cdp"
  9. "github.com/xuri/excelize/v2"
  10. "io"
  11. "log"
  12. "os"
  13. "path/filepath"
  14. "time"
  15. "github.com/chromedp/chromedp"
  16. )
  17. // 定义选择器
  18. var (
  19. downloadDir = utils.RZD_EXCEL_PATH
  20. defaultDir = utils.RZD_DOWNLOAD_PATH
  21. rzdLoginPath = "https://clients.rystadenergy.com/clients/"
  22. rzdBatchSize = 500
  23. clientSearchLink = `div.d-none.d-lg-flex.flex-grow-1 a[href="/clients/search/"]`
  24. downloadButtonSelector = `div.btn.btn-link.btn-sm.dashboard-action.dashboard-action--download-data`
  25. )
  26. // 处理数据下载的步骤
  27. func downloadData(ctx context.Context) error {
  28. // Analytics Library
  29. if err := chromedp.Run(ctx,
  30. chromedp.Sleep(5*time.Second), // 考虑移除这一行,如果不必要的话
  31. chromedp.Navigate(rzdLoginPath),
  32. chromedp.WaitVisible(`div.d-none.d-lg-flex.flex-grow-1`, chromedp.ByQuery),
  33. chromedp.Click(clientSearchLink, chromedp.ByQuery),
  34. chromedp.WaitVisible(`input[class="ais-SearchBox-input rounded border py-2 px-3 shadow-sm font-size-14 w-100"]`, chromedp.ByQuery),
  35. chromedp.SetValue(`input[class="ais-SearchBox-input rounded border py-2 px-3 shadow-sm font-size-14 w-100"]`, "oil demand signals weekly report", chromedp.ByQuery),
  36. chromedp.Sleep(10*time.Second),
  37. //chromedp.Click(`div.ais-InfiniteHits li a:has(img[src="/Static/img/icons/xls.png"])`, chromedp.ByQuery),
  38. ); err != nil {
  39. return fmt.Errorf("下载 Analytics Library 数据错误: %v", err)
  40. }
  41. xpath := `//div[@id='search-page-hits']//li//a[.//div//span[@class='align-middle' and text()='Data']]`
  42. var inputCount int
  43. var nodes []*cdp.Node // 使用 *cdp.Node
  44. if err := chromedp.Run(ctx,
  45. chromedp.ActionFunc(func(ctx context.Context) error {
  46. // 获取匹配的节点
  47. if err := chromedp.Nodes(xpath, &nodes, chromedp.BySearch).Do(ctx); err != nil {
  48. return fmt.Errorf("检查节点失败: %v", err)
  49. }
  50. // 获取节点数量
  51. inputCount = len(nodes)
  52. fmt.Printf("找到 %d 个匹配的元素\n", inputCount)
  53. if inputCount > 0 {
  54. // 点击第一个节点
  55. return chromedp.MouseClickNode(nodes[0]).Do(ctx) // 使用 []cdp.NodeID
  56. }
  57. return nil
  58. }),
  59. chromedp.Sleep(10*time.Second),
  60. ); err != nil {
  61. return fmt.Errorf("下载 Analytics Library 数据错误: %v", err)
  62. }
  63. // 解析文件移动到目标目录
  64. if err := waitAndRenameDownloadedFile("Oil_Demand_Signals_Weekly_Report_"+utils.GetCurrentYearMonth()+".xlsx", downloadDir); err != nil {
  65. return err
  66. }
  67. return nil
  68. }
  69. // 等待下载文件并重命名
  70. func waitAndRenameDownloadedFile(newFileName, targetDir string) error {
  71. // 等待一段时间以确保文件下载完成
  72. time.Sleep(100 * time.Second) // 可能需要根据实际情况调整
  73. // 查找下载目录中的文件
  74. files, err := filepath.Glob(filepath.Join(defaultDir, "*.xlsx"))
  75. if err != nil {
  76. return fmt.Errorf("查找文件时出错: %v", err)
  77. }
  78. // 如果没有找到文件,返回错误
  79. if len(files) == 0 {
  80. return fmt.Errorf("未找到任何下载的文件")
  81. }
  82. // 找到最新的文件
  83. var latestFile string
  84. var latestTime time.Time
  85. for _, file := range files {
  86. info, err := os.Stat(file)
  87. if err != nil {
  88. return fmt.Errorf("获取文件信息时出错: %v", err)
  89. }
  90. if info.ModTime().After(latestTime) {
  91. latestTime = info.ModTime()
  92. latestFile = file
  93. }
  94. }
  95. // 目标文件的完整路径
  96. targetFilePath := filepath.Join(targetDir, newFileName)
  97. // 重命名并移动到目标目录
  98. if latestFile != "" {
  99. if err := moveFile(latestFile, targetFilePath); err != nil {
  100. return fmt.Errorf("重命名文件时出错: %v", err)
  101. }
  102. // 打印重命名后的文件名
  103. fmt.Printf("文件重命名并移动到: %s\n", targetFilePath)
  104. }
  105. return nil
  106. }
  107. func moveFile(source, destination string) error {
  108. // 复制文件
  109. srcFile, err := os.Open(source)
  110. if err != nil {
  111. return fmt.Errorf("打开源文件时出错: %v", err)
  112. }
  113. defer srcFile.Close()
  114. dstFile, err := os.Create(destination)
  115. if err != nil {
  116. return fmt.Errorf("创建目标文件时出错: %v", err)
  117. }
  118. defer dstFile.Close()
  119. if _, err := io.Copy(dstFile, srcFile); err != nil {
  120. return fmt.Errorf("复制文件时出错: %v", err)
  121. }
  122. time.Sleep(60 * time.Second)
  123. // 删除源文件
  124. /*if err := os.Remove(source); err != nil {
  125. return fmt.Errorf("删除源文件时出错: %v", err)
  126. }*/
  127. return nil
  128. }
  129. // 解析网页数据,下载文件
  130. // func main() {
  131. func ResolverNet(cont context.Context) (err error) {
  132. // 创建下载目录
  133. if err := os.MkdirAll(downloadDir, os.ModePerm); err != nil {
  134. fmt.Printf("创建下载目录时出错: %v\n", err)
  135. return nil
  136. }
  137. // 创建 chromedp 执行上下文
  138. options := []chromedp.ExecAllocatorOption{
  139. chromedp.Flag("headless", false),
  140. chromedp.Flag("disable-blink-features", "AutomationControlled"),
  141. chromedp.UserAgent(`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.80 Safari/537.36`),
  142. // 设置了但并不生效,直接从默认下载路径读取过来
  143. //chromedp.Flag("download.default_directory", downloadDir),
  144. //chromedp.Flag("download.prompt_for_download", false), // 不弹出下载对话框
  145. chromedp.Flag("safebrowsing.enabled", true), // 启用安全浏览
  146. //chromedp.UserDataDir(filepath.Join(downloadDir, "user-data")),
  147. }
  148. allocCtx, cancel := chromedp.NewExecAllocator(context.Background(), options...)
  149. defer cancel()
  150. ctx, cancel := chromedp.NewContext(allocCtx)
  151. defer cancel()
  152. // 启动 Chrome 实例
  153. if err := chromedp.Run(ctx); err != nil {
  154. fmt.Printf("启动 Chrome 实例时出错: %v\n", err)
  155. return nil
  156. }
  157. // 设置下载行为
  158. /*if err := setDownloadBehavior(ctx); err != nil {
  159. fmt.Printf("设置下载路径时出错: %v\n", err)
  160. return
  161. }*/
  162. // 登录操作
  163. if err := login(ctx); err != nil {
  164. fmt.Printf("登录错误: %v\n", err)
  165. return nil
  166. }
  167. // 下载数据
  168. if err := downloadData(ctx); err != nil {
  169. fmt.Printf("数据下载错误: %v\n", err)
  170. return nil
  171. }
  172. fmt.Println("数据下载完成")
  173. // 解析表格 读取数据
  174. fileResolver()
  175. return nil
  176. }
  177. // 解析本地文件
  178. func fileResolver() {
  179. //func main() {
  180. var tableNameList = []string{
  181. "Oil_Demand_Signals_Weekly_Report",
  182. "Oil_Supply_Analysis",
  183. "Supply_Revision_Analysis",
  184. "Oil_Market_Cube_Upstream_Supply_Oil_Quality_API",
  185. "Oil_Market_Cube_Upstream_Supply_Oil_Quality_Sulphur",
  186. "Oil_Market_Cube_Upstream_Supply_Capacity_Capacity",
  187. "Oil_Market_Cube_Upstream_Supply_Production",
  188. "Oil_Market_Cube_Upstream_Supply_Production_Wo_Seasonality",
  189. "Oil_Market_Cube_Upstream_Supply_OPEC_Policy_Reference_Production",
  190. "Oil_Market_Cube_Upstream_Supply_OPEC_Policy_Target_Production",
  191. "Oil_Market_Cube_Upstream_Supply_OPEC_Policy_Target_Cut",
  192. "Oil_Market_Cube_Upstream_Supply_OPEC_Policy_Actual_Cut",
  193. "Oil_Market_Cube_Upstream_Supply_OPEC_Policy_Compliance",
  194. "Oil_Market_Cube_Upstream_Supply_OPEC_Policy_Production_Subject_To_Cut",
  195. "Oil_Market_Cube_Products_Demand_Products_Demand_Mean",
  196. "Oil_Market_Cube_Products_Demand_Products_Demand+Sigma",
  197. "Oil_Market_Cube_Products_Demand_Products_Demand-Sigma",
  198. "Oil_Market_Cube_Balances_Total_Liquids_Balances",
  199. "Oil_Market_Cube_Geography_Latitude",
  200. "Oil_Market_Cube_Geography_Longitude",
  201. "Oil_Demand_Analysis_Product_Detail",
  202. "Oil_Demand_Analysis_Region",
  203. "Oil_Demand_Analysis_Scenario",
  204. "Oil_Demand_Analysis_Continent",
  205. "Oil_Demand_Analysis_Country",
  206. "Oil_Demand_Analysis_Product_Category",
  207. "Oil_Demand_Analysis_Sector_Category",
  208. "Oil_Demand_Analysis_Sector_Detail",
  209. }
  210. for _, tableName := range tableNameList {
  211. var fileName string
  212. // 解析表格
  213. fileName = tableName + "_" + utils.GetCurrentYearMonth() + ".xlsx"
  214. filePath := filepath.Join(downloadDir, fileName)
  215. // 打开 Excel 文件
  216. f, err := excelize.OpenFile(filePath)
  217. if err != nil {
  218. log.Fatalf("无法打开 Excel 文件: %v", err)
  219. }
  220. // 获取所有工作表
  221. sheetNames := f.GetSheetList()
  222. for _, sheetName := range sheetNames {
  223. fmt.Printf("读取工作表: %s\n", sheetName)
  224. // 获取工作表的最大行数
  225. maxRow, err := f.GetRows(sheetName) // 直接获取所有行数据
  226. if err != nil {
  227. log.Fatalf("获取工作表数据时出错: %v", err)
  228. continue
  229. }
  230. // 遍历行并打印内容
  231. indexData := []models.BaseFromRzdData{}
  232. for rowIndex, rowData := range maxRow {
  233. // 因为excel文件中的sheet表格不固定 对于 Supply_Revision_Analysis, Oil_Supply_Analysis 文件 手动调整sheet表格顺序
  234. if tableName == "Supply_Revision_Analysis" && rowIndex == 0 {
  235. if rowData[0] == "YearQuarter" && rowData[1] == "Revision" && rowData[2] == "CountryRevisionGroup" {
  236. sheetName = "Chart1"
  237. }
  238. if rowData[0] == "YearQuarter" && rowData[1] == "Current" && rowData[2] == "Previous" {
  239. sheetName = "Chart2"
  240. }
  241. if rowData[0] == "Year" && rowData[1] == "Revision" && rowData[2] == "CountryRevisionGroup" {
  242. sheetName = "Chart3"
  243. }
  244. if rowData[0] == "Year" && rowData[1] == "Current" && rowData[2] == "Previous" {
  245. sheetName = "Chart4"
  246. }
  247. if rowData[0] == "Previous" && rowData[1] == "Current" && rowData[2] == "YearMonth" {
  248. sheetName = "Chart5"
  249. }
  250. if rowData[0] == "YearMonth" && rowData[1] == "CountryRevisionGroup" && rowData[2] == "Revision" {
  251. sheetName = "Chart6"
  252. }
  253. } else if tableName == "Oil_Supply_Analysis" && rowIndex == 0 {
  254. if rowData[0] == "Viz Date" && rowData[1] == "OilAndGasCategory" && rowData[2] == "supply_kbbld" {
  255. sheetName = "Chart1"
  256. }
  257. if rowData[0] == "Viz Date" && rowData[1] == "supply_kbbld" && rowData[2] == "Region" {
  258. sheetName = "Chart2"
  259. }
  260. if rowData[0] == "Viz Date" && rowData[1] == "CapacityDetail" && rowData[2] == "Capacity_kbbld" {
  261. sheetName = "Chart3"
  262. }
  263. if rowData[0] == "Viz Date" && rowData[1] == "Oil Classification Group" && rowData[2] == "supply_kbbld" {
  264. sheetName = "Chart4"
  265. }
  266. }
  267. processor, err := GetProcessor(tableName, sheetName)
  268. if err != nil {
  269. continue
  270. }
  271. baseFromRzdDataList, err := processor.Process(tableName, sheetName, rowIndex, rowData)
  272. if err != nil {
  273. log.Printf("processor.Process err: %v", err)
  274. return
  275. }
  276. indexData = append(indexData, baseFromRzdDataList...)
  277. }
  278. // 新增数据源指标数据
  279. if len(indexData) > 0 {
  280. for i := 0; i < len(indexData); i += rzdBatchSize {
  281. // 计算当前批次的结束索引
  282. end := i + rzdBatchSize
  283. if end > len(indexData) {
  284. end = len(indexData)
  285. }
  286. // 获取当前批次的数据
  287. batchData := indexData[i:end]
  288. // 转换成json
  289. marshal, err := json.Marshal(batchData)
  290. if err != nil {
  291. log.Printf("json.Marshal err: %v", err)
  292. return
  293. }
  294. // 发送 HTTP POST 请求
  295. _, err = utils.HttpPostRequest(utils.EDB_LIB_URL+utils.ADD_BATCH_RZD_DATA, string(marshal), "application/json")
  296. if err != nil {
  297. log.Printf("postEdbLib err: %v", err)
  298. return
  299. }
  300. }
  301. }
  302. // 新增指标库数据
  303. edbDataList := []models.EdbDataRzd{}
  304. for _, index := range indexData {
  305. // 补充 判断是否存在于指标库
  306. paramsLib := make(map[string]interface{})
  307. paramsLib["IndexCode"] = index.IndexCode
  308. paramsLib["Source"] = utils.DATA_SOURCE_RZD
  309. postEdbLib, err := httpRequestFill(paramsLib, utils.GET_RZD_EDB_INFO_BY_INDEX_CODE)
  310. if err != nil {
  311. // 有错误就不继续执行
  312. log.Printf("postEdbLib err: %v", err)
  313. continue
  314. }
  315. var requestResponse models.RequestResponse[models.EdbInfo]
  316. err = json.Unmarshal(postEdbLib, &requestResponse)
  317. if err != nil {
  318. log.Printf("postEdbLib err: %v", err)
  319. continue
  320. }
  321. if requestResponse.Data.EdbInfoId != 0 {
  322. edbDataRzd := models.EdbDataRzd{
  323. CreateTime: utils.GetCurrentTime(),
  324. ModifyTime: utils.GetCurrentTime(),
  325. EdbInfoId: index.BaseFromRzdIndexId,
  326. EdbCode: index.IndexCode,
  327. DataTime: index.DataTime,
  328. Value: index.Value,
  329. DataTimestamp: uint64(utils.StringToTimeFormat(index.DataTime, utils.FormatDate).UnixMilli()),
  330. }
  331. edbDataList = append(edbDataList, edbDataRzd)
  332. }
  333. }
  334. if len(edbDataList) > 0 {
  335. // 转换成json
  336. marshal, err := json.Marshal(edbDataList)
  337. if err != nil {
  338. log.Printf("postEdbLib err: %v", err)
  339. return
  340. }
  341. _, err = utils.HttpPostRequest(utils.EDB_LIB_URL+utils.ADD_BATCH_RZD_EDB_DATA, string(marshal), "application/json")
  342. if err != nil {
  343. // 有错误就不继续执行
  344. log.Printf("postEdbLib err: %v", err)
  345. return
  346. }
  347. }
  348. }
  349. }
  350. }
  351. func login(ctx context.Context) error {
  352. return chromedp.Run(ctx,
  353. chromedp.Navigate(rzdLoginPath),
  354. chromedp.SetValue(`input[id="Username"]`, utils.RZD_USERNAME, chromedp.ByQuery),
  355. chromedp.SetValue(`input[id="Password"]`, utils.RZD_PASSWORD, chromedp.ByQuery),
  356. chromedp.WaitEnabled(`//button[text()='Login']`, chromedp.BySearch),
  357. chromedp.Click(`//button[text()='Login']`, chromedp.BySearch),
  358. chromedp.Sleep(5*time.Second),
  359. // 等待并点击登录后页面的链接
  360. chromedp.WaitVisible(`a[href="/clients/"]`, chromedp.ByQuery), // 等待 Analytics Library 链接可见
  361. chromedp.Sleep(5*time.Second), // 等待页面加载完成
  362. )
  363. }
  364. func httpRequestFill(data interface{}, urlMethod string) (postEdbLib []byte, err error) {
  365. // 转换成json
  366. marshal, err := json.Marshal(data)
  367. if err != nil {
  368. return nil, err
  369. }
  370. // json 转 interface
  371. var result map[string]interface{}
  372. err = json.Unmarshal(marshal, &result)
  373. if err != nil {
  374. return nil, err
  375. }
  376. postEdbLib, err = utils.PostEdbLibRequest(result, urlMethod)
  377. if err != nil {
  378. // 有错误就不继续执行
  379. log.Printf("postEdbLib err: %v", err)
  380. return nil, err
  381. }
  382. return postEdbLib, nil
  383. }