processor_business_logic.go 80 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456
  1. // @Author gmy 2024/8/6 10:50:00
  2. package main
  3. import (
  4. "context"
  5. "encoding/json"
  6. "eta/eta_data_analysis/models"
  7. "eta/eta_data_analysis/utils"
  8. "fmt"
  9. "github.com/PuerkitoBio/goquery"
  10. "github.com/beego/beego/v2/core/logs"
  11. "github.com/chromedp/chromedp"
  12. "log"
  13. "regexp"
  14. "strconv"
  15. "strings"
  16. "unicode"
  17. )
  18. var (
  19. sourceName = "lysww" // 粮油商务网
  20. )
  21. // TableData 用于存储表格的数据
  22. type TableData struct {
  23. Headers []string `json:"headers"`
  24. Rows [][]string `json:"rows"`
  25. }
  26. // ImportCostProcessor
  27. // @Description: 进口成本处理器
  28. type ImportCostProcessor struct{}
  29. func (p *ImportCostProcessor) Process(ctx context.Context, product string, reportContent string, keywords []string, classifyId int) ([]models.BaseFromLyData, error) {
  30. logs.Info("Processing import cost...")
  31. // 解析关键字
  32. if len(keywords) < 5 {
  33. return []models.BaseFromLyData{}, fmt.Errorf("ProcessingImportCostProcessor Process() : keywords must contain at least 5 elements")
  34. }
  35. // 拿到 行关键字和列关键字
  36. columnName := keywords[len(keywords)-4]
  37. rowVariety := keywords[0]
  38. rowPort := keywords[len(keywords)-3]
  39. indexNamePrefix := keywords[:1]
  40. indexNameSuffix := keywords[1:]
  41. // 提取所有表格数据
  42. tableData := getNoHeadTableData(reportContent)
  43. // 提取日期信息
  44. dateText, err := getDateInfo(ctx)
  45. if err != nil {
  46. return []models.BaseFromLyData{}, err
  47. }
  48. // 时间格式转换
  49. format, err := utils.ConvertTimeFormat(dateText)
  50. if err != nil {
  51. return []models.BaseFromLyData{}, err
  52. }
  53. // 解析日期并计算当前月份
  54. var targetMonths []string
  55. if product == "油菜籽" {
  56. targetMonths, err = utils.ParseDateAndMonthColzaOil(format)
  57. } else {
  58. targetMonths, err = utils.ParseDateAndMonth(dateText)
  59. }
  60. if err != nil {
  61. return []models.BaseFromLyData{}, fmt.Errorf("ProcessingImportCostProcessor Process() : Failed to parse date: %v", err)
  62. }
  63. fmt.Printf("Target Month: %s\n", targetMonths)
  64. // 处理提取的表格数据
  65. var result []models.BaseFromLyData
  66. for _, data := range tableData {
  67. tableHeaders := data.Headers
  68. tableRows := data.Rows
  69. // 查找目标列
  70. columnIdx := -1
  71. for i, header := range tableHeaders {
  72. if strings.Contains(header, columnName) {
  73. columnIdx = i
  74. break
  75. }
  76. }
  77. if columnIdx == -1 {
  78. log.Printf("ProcessingImportCostProcessor Process() : Column '%s' not found in table", columnName)
  79. continue
  80. }
  81. // 处理表格中的每一行
  82. //var flag bool = true
  83. var previousRowVariety string
  84. var previousRowPort string
  85. for rowIndex, row := range tableRows {
  86. if len(row) == len(tableHeaders) {
  87. previousRowVariety = row[0]
  88. previousRowPort = row[1]
  89. } else if len(row) == len(tableHeaders)-1 {
  90. previousRowPort = row[0]
  91. row = append([]string{previousRowVariety}, row...)
  92. tableRows[rowIndex] = row
  93. } else if len(row) == len(tableHeaders)-2 {
  94. row = append([]string{previousRowVariety, previousRowPort}, row...)
  95. tableRows[rowIndex] = row
  96. }
  97. for _, targetMonth := range targetMonths {
  98. if len(row) >= len(tableHeaders) && strings.Contains(rowVariety, row[0]) && row[1] == targetMonth && row[len(row)-1] == rowPort {
  99. if columnIdx < len(row) {
  100. // 指标名称
  101. indexNameList := append(indexNamePrefix, append([]string{targetMonth}, indexNameSuffix...)...)
  102. indexName := strings.Join(indexNameList[:len(keywords)-2], ":")
  103. // 指标编码
  104. indexCode := utils.GenerateIndexCode(sourceName, indexName)
  105. // 指标id获取
  106. indexId, err := getIndexId(indexCode, indexName, classifyId, sourceName, keywords[len(keywords)-2], keywords[len(keywords)-1])
  107. if err != nil {
  108. logs.Error("ProcessingImportCostProcessor Process() : Failed to get index id: %v", err)
  109. continue
  110. }
  111. paramsLib := make(map[string]interface{})
  112. paramsLib["IndexId"] = indexId
  113. paramsLib["DataTime"] = format
  114. postEdbLib, err := httpRequestFill(paramsLib, utils.GET_LY_DATA_BY_INDEX_ID_AND_DATA_TIME)
  115. if err != nil {
  116. logs.Error("ProcessingImportCostProcessor Process() : Failed to get data by index id and date: %v", err)
  117. continue
  118. }
  119. var requestResponse models.RequestResponse[[]models.BaseFromLyData]
  120. err = json.Unmarshal(postEdbLib, &requestResponse)
  121. indexData := requestResponse.Data
  122. if len(indexData) > 0 {
  123. logs.Info("ProcessingImportCostProcessor Process() : Data already exists for index %d and date %s", indexId, dateText)
  124. continue
  125. }
  126. valueStr := row[columnIdx]
  127. value, err := strconv.ParseFloat(valueStr, 64)
  128. if err != nil {
  129. return []models.BaseFromLyData{}, fmt.Errorf("failed to parse value '%s': %v", valueStr, err)
  130. }
  131. // 创建并添加到结果列表
  132. baseFromLyData := models.BaseFromLyData{
  133. DataTime: format,
  134. Value: value,
  135. BaseFromLyIndexId: indexId,
  136. IndexCode: indexCode,
  137. }
  138. result = append(result, baseFromLyData)
  139. } else {
  140. log.Printf("ProcessingImportCostProcessor Process() : Column index out of range for row '%s', '%s'", rowVariety, rowPort)
  141. }
  142. break
  143. }
  144. }
  145. }
  146. }
  147. return result, nil
  148. }
  149. // ProcessingProfitProcessor
  150. // @Description: 加工利润处理器
  151. type ProcessingProfitProcessor struct{}
  152. func (p *ProcessingProfitProcessor) Process(ctx context.Context, product string, reportContent string, keywords []string, classifyId int) ([]models.BaseFromLyData, error) {
  153. fmt.Println("Processing processing profit...")
  154. // 解析关键字
  155. if len(keywords) < 4 {
  156. return []models.BaseFromLyData{}, fmt.Errorf("ProcessingProfitProcessor Process() : keywords must contain at least 4 elements")
  157. }
  158. // 拿到 行关键字和列关键字
  159. columnName := keywords[1]
  160. rowVariety := keywords[0]
  161. indexNamePrefix := keywords[:1]
  162. indexNameSuffix := keywords[1:]
  163. // 提取所有表格数据
  164. tableData := getNoHeadTableData(reportContent)
  165. // 提取日期信息
  166. dateText, err := getDateInfo(ctx)
  167. if err != nil {
  168. return []models.BaseFromLyData{}, err
  169. }
  170. // 时间格式转换
  171. format, err := utils.ConvertTimeFormat(dateText)
  172. if err != nil {
  173. return []models.BaseFromLyData{}, err
  174. }
  175. // 解析日期并计算当前月份 和 后两月
  176. yearMonths, err := utils.ConvertTimeFormatToYearMonth(format)
  177. if err != nil {
  178. return nil, err
  179. }
  180. fmt.Printf("Target yearMonth: %s\n", yearMonths)
  181. // 处理提取的表格数据
  182. var result []models.BaseFromLyData
  183. for _, data := range tableData {
  184. tableHeaders := data.Headers
  185. tableRows := data.Rows
  186. // 查找目标列
  187. columnIdx := -1
  188. for i, header := range tableHeaders {
  189. if strings.Contains(columnName, header) {
  190. columnIdx = i
  191. break
  192. }
  193. }
  194. if columnIdx == -1 {
  195. log.Printf("ProcessingProfitProcessor Process() : Column '%s' not found in table", columnName)
  196. continue
  197. }
  198. // 处理表格中的每一行
  199. var previousRowVariety string
  200. for rowIndex, row := range tableRows {
  201. if len(row) == len(tableHeaders) {
  202. previousRowVariety = row[0]
  203. } else if len(row) == len(tableHeaders)-1 {
  204. row = append([]string{previousRowVariety}, row...)
  205. tableRows[rowIndex] = row
  206. }
  207. for _, targetMonth := range yearMonths {
  208. if len(row) >= len(tableHeaders) && row[0] == rowVariety && row[1] == targetMonth {
  209. if columnIdx < len(row) {
  210. // 指标名称
  211. indexNameList := append(indexNamePrefix, append([]string{targetMonth}, indexNameSuffix...)...)
  212. indexName := strings.Join(indexNameList[:len(keywords)-1], ":")
  213. // 指标编码
  214. indexCode := utils.GenerateIndexCode(sourceName, indexName)
  215. // 指标id获取
  216. indexId, err := getIndexId(indexCode, indexName, classifyId, sourceName, keywords[len(keywords)-2], keywords[len(keywords)-1])
  217. if err != nil {
  218. logs.Error("ProcessingProfitProcessor Process() : Failed to get index id: %v", err)
  219. continue
  220. }
  221. paramsLib := make(map[string]interface{})
  222. paramsLib["IndexId"] = indexId
  223. paramsLib["DataTime"] = format
  224. postEdbLib, err := httpRequestFill(paramsLib, utils.GET_LY_DATA_BY_INDEX_ID_AND_DATA_TIME)
  225. if err != nil {
  226. logs.Error("ProcessingProfitProcessor Process() : Failed to get data by index id and date: %v", err)
  227. continue
  228. }
  229. var requestResponse models.RequestResponse[[]models.BaseFromLyData]
  230. err = json.Unmarshal(postEdbLib, &requestResponse)
  231. indexData := requestResponse.Data
  232. if len(indexData) > 0 {
  233. logs.Info("ProcessingProfitProcessor Process() : Data already exists for index %d and date %s", indexId, dateText)
  234. continue
  235. }
  236. valueStr := row[columnIdx]
  237. value, err := strconv.ParseFloat(valueStr, 64)
  238. if err != nil {
  239. return []models.BaseFromLyData{}, fmt.Errorf("failed to parse value '%s': %v", valueStr, err)
  240. }
  241. // 创建并添加到结果列表
  242. baseFromLyData := models.BaseFromLyData{
  243. DataTime: format,
  244. Value: value,
  245. BaseFromLyIndexId: indexId,
  246. IndexCode: indexCode,
  247. }
  248. result = append(result, baseFromLyData)
  249. } else {
  250. log.Printf("ProcessingProfitProcessor Process() : Column index out of range for row '%s', '%s'", rowVariety, columnName)
  251. }
  252. break
  253. }
  254. }
  255. }
  256. }
  257. return result, nil
  258. }
  259. // ShippingCostProcessor
  260. // @Description: 船运费用处理器
  261. type ShippingCostProcessor struct{}
  262. func (p *ShippingCostProcessor) Process(ctx context.Context, product string, reportContent string, keywords []string, classifyId int) ([]models.BaseFromLyData, error) {
  263. fmt.Println("Processing processing profit...")
  264. // 解析关键字
  265. if len(keywords) < 4 {
  266. return []models.BaseFromLyData{}, fmt.Errorf("ShippingCostProcessor Process() : keywords must contain at least 5 elements")
  267. }
  268. // 拿到 行关键字和列关键字
  269. columnName := keywords[len(keywords)-3]
  270. rowVariety := keywords[0]
  271. rowDestination := keywords[1]
  272. rowShipType := keywords[2]
  273. // 提取所有表格数据
  274. tableData := getNoHeadTableData(reportContent)
  275. // 提取日期信息
  276. dateText, err := getDateInfo(ctx)
  277. if err != nil {
  278. return []models.BaseFromLyData{}, err
  279. }
  280. // 时间格式转换
  281. format, err := utils.ConvertTimeFormat(dateText)
  282. if err != nil {
  283. return []models.BaseFromLyData{}, err
  284. }
  285. // 处理提取的表格数据
  286. var result []models.BaseFromLyData
  287. for _, data := range tableData {
  288. tableHeaders := data.Headers
  289. tableRows := data.Rows
  290. // 查找目标列
  291. columnIdx := -1
  292. for i, header := range tableHeaders {
  293. if strings.Contains(header, columnName) {
  294. columnIdx = i
  295. break
  296. }
  297. }
  298. if columnIdx == -1 {
  299. log.Printf("ShippingCostProcessor Process() : Column '%s' not found in table", columnName)
  300. continue
  301. }
  302. // 处理表格中的每一行
  303. for rowIndex, row := range tableRows {
  304. if len(row) == len(tableHeaders)-1 {
  305. row = append([]string{rowVariety}, row...)
  306. tableRows[rowIndex] = row
  307. rowShipType, err = extractValueInParentheses(rowVariety)
  308. if err != nil {
  309. logs.Error("ShippingCostProcessor Process() : Failed to extract value in parentheses: %v", err)
  310. continue
  311. }
  312. }
  313. if len(row) >= len(tableHeaders) && row[0] == rowVariety && (row[1] == rowDestination || strings.Contains(row[0], row[1])) && row[2] == rowShipType {
  314. if columnIdx < len(row) {
  315. // 指标名称
  316. indexName := strings.Join(keywords[:len(keywords)-3], `:`)
  317. // 指标编码
  318. indexCode := utils.GenerateIndexCode(sourceName, indexName)
  319. // 指标id获取
  320. indexId, err := getIndexId(indexCode, indexName, classifyId, sourceName, keywords[len(keywords)-2], keywords[len(keywords)-1])
  321. if err != nil {
  322. logs.Error("ShippingCostProcessor Process() : Failed to get index id: %v", err)
  323. continue
  324. }
  325. paramsLib := make(map[string]interface{})
  326. paramsLib["IndexId"] = indexId
  327. paramsLib["DataTime"] = format
  328. postEdbLib, err := httpRequestFill(paramsLib, utils.GET_LY_DATA_BY_INDEX_ID_AND_DATA_TIME)
  329. if err != nil {
  330. logs.Error("ShippingCostProcessor Process() : Failed to get data by index id and date: %v", err)
  331. continue
  332. }
  333. var requestResponse models.RequestResponse[[]models.BaseFromLyData]
  334. err = json.Unmarshal(postEdbLib, &requestResponse)
  335. indexData := requestResponse.Data
  336. if len(indexData) > 0 {
  337. logs.Info("ShippingCostProcessor Process() : Data already exists for index %d and date %s", indexId, dateText)
  338. continue
  339. }
  340. valueStr := row[columnIdx]
  341. value, err := strconv.ParseFloat(valueStr, 64)
  342. if err != nil {
  343. return []models.BaseFromLyData{}, fmt.Errorf("failed to parse value '%s': %v", valueStr, err)
  344. }
  345. // 创建并添加到结果列表
  346. baseFromLyData := models.BaseFromLyData{
  347. DataTime: format,
  348. Value: value,
  349. BaseFromLyIndexId: indexId,
  350. IndexCode: indexCode,
  351. }
  352. result = append(result, baseFromLyData)
  353. } else {
  354. log.Printf("ShippingCostProcessor Process() : Column index out of range for row '%s', '%s'", rowVariety, columnName)
  355. }
  356. break
  357. }
  358. }
  359. }
  360. return result, nil
  361. }
  362. // SupplyDemandBalanceProcessor
  363. // @Description: 供需平衡处理器
  364. type SupplyDemandBalanceProcessor struct{}
  365. func (p *SupplyDemandBalanceProcessor) Process(ctx context.Context, product string, reportContent string, keywords []string, classifyId int) ([]models.BaseFromLyData, error) {
  366. // https://www.fao.com.cn/art/gG7gKTCNDHLJNsq9QRYjoQ==.htm
  367. logs.Info("Processing processing report...")
  368. // 解析关键字
  369. if len(keywords) < 4 {
  370. return []models.BaseFromLyData{}, fmt.Errorf("SupplyDemandBalanceProcessor Process() : keywords must contain at least 4 elements")
  371. }
  372. // 拿到 行关键字和列关键字
  373. var columnName string
  374. rowVariety := keywords[1]
  375. // 提取所有表格数据
  376. tableData := getTableData(reportContent, true)
  377. logs.Info("SupplyDemandBalanceProcessor Process() : Table data: %v", tableData)
  378. // 提取日期信息
  379. dateText, err := getDateInfo(ctx)
  380. if err != nil {
  381. return []models.BaseFromLyData{}, err
  382. }
  383. // 时间格式转换
  384. format, err := utils.ConvertTimeFormat(dateText)
  385. if err != nil {
  386. return []models.BaseFromLyData{}, err
  387. }
  388. currentYearAndNextYear, err := utils.GetCurrentYearAndNextYear(format)
  389. if err != nil {
  390. return nil, err
  391. }
  392. month, err := utils.GetCurrentMonth(format)
  393. if err != nil {
  394. return nil, err
  395. }
  396. monthSuffix := "预估"
  397. logs.Info("SupplyDemandBalanceProcessor Process() : Target Year: %s:%s\n", currentYearAndNextYear, month+monthSuffix)
  398. // 处理提取的表格数据
  399. var result []models.BaseFromLyData
  400. headers := tableData.Headers
  401. rows := tableData.Rows
  402. for _, year := range currentYearAndNextYear {
  403. columnName = year + month + monthSuffix
  404. isCurrentYear, err := utils.IsCurrentYear(year)
  405. if err != nil {
  406. logs.Error("SupplyDemandBalanceProcessor Process() : Failed to determine if year is current year: %v", err)
  407. continue
  408. }
  409. if !isCurrentYear {
  410. format, err = utils.GetNextYearLastDay(format)
  411. if err != nil {
  412. logs.Error("SupplyDemandBalanceProcessor Process() : Failed to get next year last day: %v", err)
  413. continue
  414. }
  415. }
  416. // 查找目标列
  417. columnIdx := -1
  418. for i, header := range headers {
  419. if strings.Contains(columnName, header) {
  420. columnIdx = i
  421. break
  422. }
  423. }
  424. if columnIdx == -1 {
  425. logs.Error("SupplyDemandBalanceProcessor Process() : Column '%s' not found in table", columnName)
  426. continue
  427. }
  428. // 处理表格中的每一行
  429. for _, row := range rows {
  430. if len(row) >= len(headers) && row[0] == rowVariety {
  431. if columnIdx < len(row) {
  432. // 指标名称
  433. indexName := strings.Join(keywords[:len(keywords)-2], ":")
  434. // 指标编码
  435. indexCode := utils.GenerateIndexCode(sourceName, indexName)
  436. // 指标id获取
  437. indexId, err := getIndexId(indexCode, indexName, classifyId, sourceName, keywords[len(keywords)-2], keywords[len(keywords)-1])
  438. if err != nil {
  439. logs.Error("SupplyDemandBalanceProcessor Process() : Failed to get index id: %v", err)
  440. continue
  441. }
  442. valueStr := row[columnIdx]
  443. value, err := strconv.ParseFloat(valueStr, 64)
  444. if err != nil {
  445. return []models.BaseFromLyData{}, fmt.Errorf("SupplyDemandBalanceProcessor Process() : failed to parse value '%s': %v", valueStr, err)
  446. }
  447. yearMonth, err := utils.GetYearMonth(format)
  448. if err != nil {
  449. logs.Error("SupplyDemandBalanceProcessor Process() : Failed to get year month: %v", err)
  450. continue
  451. }
  452. paramsLib := make(map[string]interface{})
  453. paramsLib["IndexId"] = indexId
  454. paramsLib["YearMonth"] = format
  455. postEdbLib, err := httpRequestFill(paramsLib, utils.GET_LY_DATA_BY_INDEX_ID_AND_DATA_TIME_YM)
  456. if err != nil {
  457. logs.Error("SupplyDemandBalanceProcessor Process() : Failed to get data by index id and date: %v", err)
  458. continue
  459. }
  460. var requestResponse models.RequestResponse[[]models.BaseFromLyData]
  461. err = json.Unmarshal(postEdbLib, &requestResponse)
  462. indexData := requestResponse.Data
  463. if len(indexData) > 0 {
  464. logs.Info("SupplyDemandBalanceProcessor Process() : Data already exists for index %d and date %s", indexId, dateText)
  465. // 存在走更新逻辑 主要更新今年在去年的预估值
  466. indexData := indexData[0]
  467. if indexData.Value != value {
  468. time, err := utils.StringToTime(indexData.ModifyTime)
  469. if err != nil {
  470. return nil, err
  471. }
  472. timeZero, err := utils.StringToTimeZero(format)
  473. if err != nil {
  474. return nil, err
  475. }
  476. if time.Before(timeZero) {
  477. // 更新指标数据
  478. paramsLib := make(map[string]interface{})
  479. paramsLib["Id"] = indexData.BaseFromLyDataId
  480. paramsLib["Value"] = value
  481. _, err := httpRequestFill(paramsLib, utils.UPDATE_LY_DATA_BY_ID)
  482. if err != nil {
  483. return nil, fmt.Errorf("SupplyDemandBalanceProcessor Process() : failed to parse value '%s': %v", valueStr, err)
  484. }
  485. // 更新指标库数据
  486. paramsLib = make(map[string]interface{})
  487. paramsLib["IndexCode"] = indexData.IndexCode
  488. paramsLib["DataTime"] = yearMonth
  489. postEdbLib, err := httpRequestFill(paramsLib, utils.GET_LY_EDB_DATA_BY_INDEX_CODE_AND_DATA_TIME)
  490. if err != nil {
  491. logs.Error("SupplyDemandBalanceProcessor Process() : Failed to get data by index id and date: %v", err)
  492. continue
  493. }
  494. var requestResponse models.RequestResponse[[]models.EdbDataLy]
  495. err = json.Unmarshal(postEdbLib, &requestResponse)
  496. if err != nil {
  497. return nil, err
  498. }
  499. edbIndexData := requestResponse.Data
  500. if len(edbIndexData) > 0 {
  501. paramsLib := make(map[string]interface{})
  502. paramsLib["Id"] = edbIndexData[0].EdbInfoId
  503. paramsLib["Value"] = value
  504. _, err := httpRequestFill(paramsLib, utils.UPDATE_LY_EDB_DATA_BY_ID)
  505. if err != nil {
  506. return nil, fmt.Errorf("SupplyDemandBalanceProcessor Process() : failed to parse value '%s': %v", valueStr, err)
  507. }
  508. }
  509. }
  510. }
  511. continue
  512. }
  513. // 创建并添加到结果列表
  514. baseFromLyData := models.BaseFromLyData{
  515. DataTime: format,
  516. Value: value,
  517. BaseFromLyIndexId: indexId,
  518. IndexCode: indexCode,
  519. }
  520. result = append(result, baseFromLyData)
  521. } else {
  522. log.Printf("SupplyDemandBalanceProcessor Process() : Column index out of range for row '%s', '%s'", rowVariety, columnName)
  523. }
  524. break
  525. }
  526. }
  527. }
  528. return result, nil
  529. }
  530. // PurchaseShippingProcessor
  531. // @Description: 采购装船处理器
  532. type PurchaseShippingProcessor struct{}
  533. func (p *PurchaseShippingProcessor) Process(ctx context.Context, product string, reportContent string, keywords []string, classifyId int) ([]models.BaseFromLyData, error) {
  534. logs.Info("Processing purchase shipping...")
  535. // 解析关键字
  536. if len(keywords) < 3 {
  537. return []models.BaseFromLyData{}, fmt.Errorf("SupplyDemandBalanceProcessor Process() : keywords must contain at least 3 elements")
  538. }
  539. // 拿到 行关键字和列关键字
  540. columnName := keywords[len(keywords)-3]
  541. // 提取所有表格数据
  542. tableData := getPurchaseShippingTableData(reportContent)
  543. logs.Info("SupplyDemandBalanceProcessor Process() : Table data: %v", tableData)
  544. // 提取日期信息
  545. dateText, err := getDateInfo(ctx)
  546. if err != nil {
  547. return []models.BaseFromLyData{}, err
  548. }
  549. // 时间格式转换
  550. format, err := utils.ConvertTimeFormat(dateText)
  551. if err != nil {
  552. return []models.BaseFromLyData{}, err
  553. }
  554. // 处理提取的表格数据
  555. var result []models.BaseFromLyData
  556. headers := tableData.Headers
  557. rows := tableData.Rows
  558. // 查找目标列
  559. columnIdx := -1
  560. for i, header := range headers {
  561. if strings.Contains(columnName, header) {
  562. columnIdx = i
  563. break
  564. }
  565. }
  566. if columnIdx == -1 {
  567. log.Printf("SupplyDemandBalanceProcessor Process() : Column '%s' not found in table", columnName)
  568. } else {
  569. // 处理表格中的每一行
  570. for _, row := range rows {
  571. if len(row) >= len(headers) {
  572. if columnIdx < len(row) {
  573. if !isNumber(row[columnIdx]) {
  574. continue
  575. }
  576. // 指标名称
  577. indexName := strings.Join(keywords[:len(keywords)-3], ":")
  578. // 指标编码
  579. indexCode := utils.GenerateIndexCode(sourceName, indexName)
  580. // 指标id获取
  581. indexId, err := getIndexId(indexCode, indexName, classifyId, sourceName, keywords[len(keywords)-2], keywords[len(keywords)-1])
  582. if err != nil {
  583. logs.Error("SupplyDemandBalanceProcessor Process() : Failed to get index id: %v", err)
  584. continue
  585. }
  586. var yearMonth string
  587. number, err := utils.ConvertMonthToNumber(row[1])
  588. if err != nil {
  589. return nil, err
  590. }
  591. yearMonth = row[0] + "-" + number
  592. isSameMonth, err := utils.IsSameMonth(format, yearMonth)
  593. if err != nil {
  594. return nil, err
  595. }
  596. if isSameMonth {
  597. yearMonth = format
  598. } else {
  599. lastDayOfMonth, err := utils.GetLastDayOfMonth(yearMonth)
  600. if err != nil {
  601. return nil, err
  602. }
  603. yearMonth = lastDayOfMonth
  604. }
  605. valueStr := row[columnIdx]
  606. value, err := strconv.ParseFloat(valueStr, 64)
  607. if err != nil {
  608. return []models.BaseFromLyData{}, fmt.Errorf("SupplyDemandBalanceProcessor Process() : failed to parse value '%s': %v", valueStr, err)
  609. }
  610. month, err := utils.GetYearMonth(yearMonth)
  611. if err != nil {
  612. return nil, err
  613. }
  614. paramsLib := make(map[string]interface{})
  615. paramsLib["IndexId"] = indexId
  616. paramsLib["YearMonth"] = month
  617. postEdbLib, err := httpRequestFill(paramsLib, utils.GET_LY_DATA_BY_INDEX_ID_AND_DATA_TIME_YM)
  618. if err != nil {
  619. logs.Error("SupplyDemandBalanceProcessor Process() : Failed to get data by index id and date: %v", err)
  620. continue
  621. }
  622. var requestResponse models.RequestResponse[[]models.BaseFromLyData]
  623. err = json.Unmarshal(postEdbLib, &requestResponse)
  624. indexData := requestResponse.Data
  625. if len(indexData) > 0 {
  626. if indexData[0].Value != value {
  627. logs.Info("SupplyDemandBalanceProcessor Process() : Data already exists for index %d and date %s", indexId, dateText)
  628. lyData := indexData[0]
  629. time, err := utils.StringToTime(lyData.ModifyTime)
  630. if err != nil {
  631. return nil, err
  632. }
  633. timeZero, err := utils.StringToTimeZero(format)
  634. if err != nil {
  635. return nil, err
  636. }
  637. if time.Before(timeZero) {
  638. // 更新指标数据
  639. paramsLib := make(map[string]interface{})
  640. paramsLib["Id"] = lyData.BaseFromLyDataId
  641. paramsLib["Value"] = value
  642. _, err := httpRequestFill(paramsLib, utils.UPDATE_LY_DATA_BY_ID)
  643. if err != nil {
  644. return nil, fmt.Errorf("SupplyDemandBalanceProcessor Process() : failed to parse value '%s': %v", valueStr, err)
  645. }
  646. // 同步更新指标库数据 须根据指标编码和日期更新
  647. paramsLib = make(map[string]interface{})
  648. paramsLib["IndexCode"] = lyData.IndexCode
  649. paramsLib["DataTime"] = yearMonth
  650. postEdbLib, err := httpRequestFill(paramsLib, utils.GET_LY_EDB_DATA_BY_INDEX_CODE_AND_DATA_TIME)
  651. if err != nil {
  652. logs.Error("SupplyDemandBalanceProcessor Process() : Failed to get data by index id and date: %v", err)
  653. continue
  654. }
  655. var requestResponse models.RequestResponse[[]models.EdbDataLy]
  656. err = json.Unmarshal(postEdbLib, &requestResponse)
  657. edbIndexData := requestResponse.Data
  658. if err != nil {
  659. return nil, err
  660. }
  661. if len(edbIndexData) > 0 {
  662. paramsLib := make(map[string]interface{})
  663. paramsLib["Id"] = edbIndexData[0].EdbInfoId
  664. paramsLib["Value"] = value
  665. _, err := httpRequestFill(paramsLib, utils.UPDATE_LY_EDB_DATA_BY_ID)
  666. if err != nil {
  667. return nil, fmt.Errorf("SupplyDemandBalanceProcessor Process() : failed to parse value '%s': %v", valueStr, err)
  668. }
  669. }
  670. }
  671. }
  672. continue
  673. }
  674. // 创建并添加到结果列表
  675. baseFromLyData := models.BaseFromLyData{
  676. DataTime: yearMonth,
  677. Value: value,
  678. BaseFromLyIndexId: indexId,
  679. IndexCode: indexCode,
  680. }
  681. result = append(result, baseFromLyData)
  682. continue
  683. } else {
  684. log.Printf("SupplyDemandBalanceProcessor Process() : Column index out of range for row '%s'", columnName)
  685. }
  686. break
  687. }
  688. }
  689. }
  690. return result, nil
  691. }
  692. // ProcessingReportProcessor
  693. // @Description: 加工报告处理器
  694. type ProcessingReportProcessor struct {
  695. }
  696. func (p *ProcessingReportProcessor) Process(ctx context.Context, product string, reportContent string, keywords []string, classifyId int) ([]models.BaseFromLyData, error) {
  697. logs.Info("Processing processing report...")
  698. // 解析关键字
  699. if len(keywords) < 3 {
  700. return []models.BaseFromLyData{}, fmt.Errorf("ProcessingReportProcessor Process() : keywords must contain at least 3 elements")
  701. }
  702. // 拿到 行关键字和列关键字
  703. columnName := keywords[0]
  704. rowName := keywords[1]
  705. // 提取所有表格数据
  706. tableData := getAllTableData(reportContent)
  707. // 提取日期信息
  708. dateText, err := getDateInfo(ctx)
  709. if err != nil {
  710. return []models.BaseFromLyData{}, err
  711. }
  712. indexName := strings.Join(keywords[:len(keywords)-2], ":")
  713. // 指标编码
  714. indexCode := utils.GenerateIndexCode(sourceName, indexName)
  715. // 指标id获取
  716. indexId, err := getIndexId(indexCode, indexName, classifyId, sourceName, keywords[len(keywords)-2], keywords[len(keywords)-1])
  717. if err != nil {
  718. return nil, err
  719. }
  720. // 校验指标数据是否存在 根据指标id和日期 存在则跳过,不存在正常往下走
  721. format, err := utils.ConvertTimeFormat(dateText)
  722. if err != nil {
  723. return []models.BaseFromLyData{}, err
  724. }
  725. paramsLib := make(map[string]interface{})
  726. paramsLib["IndexId"] = indexId
  727. paramsLib["DataTime"] = format
  728. postEdbLib, err := httpRequestFill(paramsLib, utils.GET_LY_DATA_BY_INDEX_ID_AND_DATA_TIME)
  729. if err != nil {
  730. return []models.BaseFromLyData{}, fmt.Errorf("ProcessingReportProcessor Process() : Failed to get data by index id and date: %v", err)
  731. }
  732. var requestResponse models.RequestResponse[[]models.BaseFromLyData]
  733. err = json.Unmarshal(postEdbLib, &requestResponse)
  734. indexData := requestResponse.Data
  735. if len(indexData) > 0 {
  736. logs.Info("ProcessingReportProcessor Process() : Data already exists for index %d and date %s", indexId, dateText)
  737. // 不必做更新处理,报告每周刷新,即使本周和上周数据一致,也需要每周记录
  738. return []models.BaseFromLyData{}, nil
  739. }
  740. // 解析日期并计算当前周数
  741. targetWeek, err := utils.ParseDateAndWeek(dateText)
  742. if err != nil {
  743. return []models.BaseFromLyData{}, fmt.Errorf("ProcessingReportProcessor Process() : Failed to parse date: %v", err)
  744. }
  745. fmt.Printf("Target Week: %s\n", targetWeek)
  746. var result []models.BaseFromLyData
  747. // 处理提取的表格数据
  748. for _, data := range tableData {
  749. tableHeaders := data.Headers
  750. tableRows := data.Rows
  751. // 查找目标列
  752. columnIdx := -1
  753. for i, header := range tableHeaders {
  754. headerString := extractChinese(header)
  755. if strings.Contains(columnName, headerString) {
  756. // 这个表格不是很好处理,这里写的有些僵硬,后续需要优化
  757. if columnName == "国内大豆开机率" {
  758. i = i + 2
  759. }
  760. columnIdx = i
  761. break
  762. }
  763. }
  764. if columnIdx == -1 {
  765. logs.Error("ProcessingReportProcessor Process() : Column '%s' not found in table", columnName)
  766. continue
  767. }
  768. // 查找本周的列位置
  769. weekIdx := -1
  770. for i, header := range tableHeaders {
  771. if strings.Contains(header, targetWeek) && i > columnIdx {
  772. weekIdx = i
  773. break
  774. }
  775. }
  776. if weekIdx == -1 {
  777. fmt.Printf("Week column '%s' not found in table\n", targetWeek)
  778. continue
  779. }
  780. // 查找目标行
  781. for _, row := range tableRows {
  782. if strings.Contains(row[0], rowName) {
  783. if columnIdx < len(row) {
  784. // 指标名称
  785. indexName := strings.Join(keywords[:len(keywords)-2], ":")
  786. // 指标编码
  787. indexCode := utils.GenerateIndexCode(sourceName, indexName)
  788. // 指标id获取
  789. indexId, err := getIndexId(indexCode, indexName, classifyId, sourceName, keywords[len(keywords)-2], keywords[len(keywords)-1])
  790. if err != nil {
  791. logs.Error("ProcessingReportProcessor Process() : Failed to get index id: %v", err)
  792. continue
  793. }
  794. paramsLib := make(map[string]interface{})
  795. paramsLib["IndexId"] = indexId
  796. paramsLib["DataTime"] = format
  797. postEdbLib, err := httpRequestFill(paramsLib, utils.GET_LY_DATA_BY_INDEX_ID_AND_DATA_TIME)
  798. if err != nil {
  799. logs.Error("ProcessingReportProcessor Process() : Failed to get data by index id and date: %v", err)
  800. continue
  801. }
  802. var requestResponse models.RequestResponse[[]models.BaseFromLyData]
  803. err = json.Unmarshal(postEdbLib, &requestResponse)
  804. indexData := requestResponse.Data
  805. if len(indexData) > 0 {
  806. logs.Info("ProcessingReportProcessor Process() : Data already exists for index %d and date %s", indexId, dateText)
  807. // 无需走更新逻辑,报告每日更新,即使今天和昨天数据一致,也需要每天记录,如果到这里也只是说,今天这个报告被读取了两次
  808. continue
  809. }
  810. valueStr := row[columnIdx]
  811. value, err := strconv.ParseFloat(valueStr, 64)
  812. if err != nil {
  813. return []models.BaseFromLyData{}, fmt.Errorf("ProcessingReportProcessor Process() : failed to parse value '%s': %v", valueStr, err)
  814. }
  815. // 创建并添加到结果列表
  816. baseFromLyData := models.BaseFromLyData{
  817. DataTime: format,
  818. Value: value,
  819. BaseFromLyIndexId: indexId,
  820. IndexCode: indexCode,
  821. }
  822. result = append(result, baseFromLyData)
  823. continue
  824. } else {
  825. log.Printf("ProcessingReportProcessor Process() : Column index out of range for row '%s', '%s'", rowName, columnName)
  826. }
  827. break
  828. }
  829. /*if len(row) > 0 && strings.Contains(row[0], rowName) {
  830. if weekIdx < len(row) {
  831. logs.Info("Value in column '%s' - '%s': %s", columnName, rowName, row[columnIdx])
  832. numFlag := isNumeric(row[columnIdx])
  833. if numFlag {
  834. value, err := strconv.ParseFloat(row[columnIdx], 64)
  835. if err != nil {
  836. logs.Error("ProcessingReportProcessor Process() : Error converting value to float64: %v", err)
  837. return []models.BaseFromLyData{}, err
  838. }
  839. // 返回BaseFromLyData对象的数据
  840. baseFromLyData := models.BaseFromLyData{
  841. DataTime: dateText,
  842. Value: value,
  843. }
  844. result = append(result, baseFromLyData)
  845. }
  846. } else {
  847. logs.Error("ProcessingReportProcessor Process() : Column index out of range")
  848. }
  849. }*/
  850. }
  851. }
  852. return result, nil
  853. }
  854. // InventoryAnalysisProcessor
  855. // @Description: 库存分析处理器
  856. type InventoryAnalysisProcessor struct{}
  857. func (p *InventoryAnalysisProcessor) Process(ctx context.Context, product string, reportContent string, keywords []string, classifyId int) ([]models.BaseFromLyData, error) {
  858. // https://www.fao.com.cn/art/yg1IKj9FpPEIDv2LefnPhQ==.htm
  859. logs.Info("Processing inventory analysis...")
  860. // 解析关键字
  861. if len(keywords) < 4 {
  862. return []models.BaseFromLyData{}, fmt.Errorf("SupplyDemandBalanceProcessor Process() : keywords must contain at least 4 elements")
  863. }
  864. // 拿到 行关键字和列关键字
  865. columnName := keywords[0]
  866. rowVariety := keywords[1]
  867. columnSuffix := "本周"
  868. columnName = columnName + columnSuffix
  869. // 提取所有表格数据
  870. tableData := getTableData(reportContent, true)
  871. logs.Info("SupplyDemandBalanceProcessor Process() : Table data: %v", tableData)
  872. // 提取日期信息
  873. dateText, err := getDateInfo(ctx)
  874. if err != nil {
  875. return []models.BaseFromLyData{}, err
  876. }
  877. // 时间格式转换
  878. format, err := utils.ConvertTimeFormat(dateText)
  879. if err != nil {
  880. return []models.BaseFromLyData{}, err
  881. }
  882. // 处理提取的表格数据
  883. var result []models.BaseFromLyData
  884. headers := tableData.Headers
  885. rows := tableData.Rows
  886. // 查找目标列
  887. columnIdx := -1
  888. for i, header := range headers {
  889. header := removeParentheses(header)
  890. if strings.Contains(columnName, header) {
  891. columnIdx = i
  892. break
  893. }
  894. }
  895. if columnIdx == -1 {
  896. logs.Error("SupplyDemandBalanceProcessor Process() : Column '%s' not found in table", columnName)
  897. } else {
  898. // 处理表格中的每一行
  899. for _, row := range rows {
  900. if len(row) >= len(headers) && strings.Contains(row[0], rowVariety) {
  901. if columnIdx < len(row) {
  902. // 指标名称
  903. indexName := strings.Join(keywords[:len(keywords)-2], ":")
  904. indexName = removeParentheses(indexName)
  905. // 指标编码
  906. indexCode := utils.GenerateIndexCode(sourceName, indexName)
  907. // 指标id获取
  908. indexId, err := getIndexId(indexCode, indexName, classifyId, sourceName, keywords[len(keywords)-2], keywords[len(keywords)-1])
  909. if err != nil {
  910. logs.Error("SupplyDemandBalanceProcessor Process() : Failed to get index id: %v", err)
  911. continue
  912. }
  913. paramsLib := make(map[string]interface{})
  914. paramsLib["IndexId"] = indexId
  915. paramsLib["DataTime"] = format
  916. postEdbLib, err := httpRequestFill(paramsLib, utils.GET_LY_DATA_BY_INDEX_ID_AND_DATA_TIME)
  917. if err != nil {
  918. logs.Error("SupplyDemandBalanceProcessor Process() : Failed to get data by index id and date: %v", err)
  919. continue
  920. }
  921. var requestResponse models.RequestResponse[[]models.BaseFromLyData]
  922. err = json.Unmarshal(postEdbLib, &requestResponse)
  923. indexData := requestResponse.Data
  924. if len(indexData) > 0 {
  925. logs.Info("SupplyDemandBalanceProcessor Process() : Data already exists for index %d and date %s", indexId, dateText)
  926. // 无需走更新逻辑,报告每周更新,即使本周和上周数据一致,也需要每周记录,如果到这里也只是说,今天这个报告被读取了两次
  927. continue
  928. }
  929. valueStr := row[columnIdx]
  930. value, err := strconv.ParseFloat(valueStr, 64)
  931. if err != nil {
  932. return []models.BaseFromLyData{}, fmt.Errorf("SupplyDemandBalanceProcessor Process() : failed to parse value '%s': %v", valueStr, err)
  933. }
  934. // 创建并添加到结果列表
  935. baseFromLyData := models.BaseFromLyData{
  936. DataTime: format,
  937. Value: value,
  938. BaseFromLyIndexId: indexId,
  939. IndexCode: indexCode,
  940. }
  941. result = append(result, baseFromLyData)
  942. continue
  943. } else {
  944. log.Printf("SupplyDemandBalanceProcessor Process() : Column index out of range for row '%s', '%s'", rowVariety, columnName)
  945. }
  946. break
  947. }
  948. }
  949. }
  950. return result, nil
  951. }
  952. // PriceSpreadArbitrageProcessor
  953. // @Description: 价差套利处理器
  954. type PriceSpreadArbitrageProcessor struct{}
  955. func (p *PriceSpreadArbitrageProcessor) Process(ctx context.Context, product string, reportContent string, keywords []string, classifyId int) ([]models.BaseFromLyData, error) {
  956. fmt.Println("Processing processing profit...")
  957. // 解析关键字
  958. if len(keywords) < 4 {
  959. return []models.BaseFromLyData{}, fmt.Errorf("ProcessingProfitProcessor Process() : keywords must contain at least 4 elements")
  960. }
  961. // 拿到 行关键字和列关键字
  962. var columnDate string
  963. rowVariety := keywords[0]
  964. rowBourse := keywords[1]
  965. // 提取所有表格数据
  966. tableData := getNoHeadTableData(reportContent)
  967. // 提取日期信息
  968. dateText, err := getDateInfo(ctx)
  969. if err != nil {
  970. return []models.BaseFromLyData{}, err
  971. }
  972. // 时间格式转换
  973. format, err := utils.ConvertTimeFormat(dateText)
  974. if err != nil {
  975. return []models.BaseFromLyData{}, err
  976. }
  977. day, err := utils.ConvertTimeFormatToYearMonthDay(format)
  978. if err != nil {
  979. return nil, err
  980. }
  981. columnDate = day
  982. // 处理提取的表格数据
  983. var result []models.BaseFromLyData
  984. for _, data := range tableData {
  985. tableHeaders := data.Headers
  986. tableRows := data.Rows
  987. // 查找目标列
  988. columnIdx := -1
  989. for i, header := range tableHeaders {
  990. if strings.Contains(header, columnDate) {
  991. columnIdx = i
  992. break
  993. }
  994. }
  995. if columnIdx == -1 {
  996. log.Printf("ProcessingProfitProcessor Process() : Column '%s' not found in table", columnDate)
  997. continue
  998. }
  999. // 处理表格中的每一行
  1000. for _, row := range tableRows {
  1001. if len(row) >= len(tableHeaders) && row[0] == rowVariety && row[1] == rowBourse {
  1002. if columnIdx < len(row) {
  1003. // 指标名称
  1004. indexName := strings.Join(keywords[:len(keywords)-2], ":")
  1005. // 指标编码
  1006. indexCode := utils.GenerateIndexCode(sourceName, indexName)
  1007. // 指标id获取
  1008. indexId, err := getIndexId(indexCode, indexName, classifyId, sourceName, keywords[len(keywords)-2], keywords[len(keywords)-1])
  1009. if err != nil {
  1010. logs.Error("ProcessingProfitProcessor Process() : Failed to get index id: %v", err)
  1011. continue
  1012. }
  1013. paramsLib := make(map[string]interface{})
  1014. paramsLib["IndexId"] = indexId
  1015. paramsLib["DataTime"] = format
  1016. postEdbLib, err := httpRequestFill(paramsLib, utils.GET_LY_DATA_BY_INDEX_ID_AND_DATA_TIME)
  1017. if err != nil {
  1018. logs.Error("ProcessingProfitProcessor Process() : Failed to get data by index id and date: %v", err)
  1019. continue
  1020. }
  1021. var requestResponse models.RequestResponse[[]models.BaseFromLyData]
  1022. err = json.Unmarshal(postEdbLib, &requestResponse)
  1023. indexData := requestResponse.Data
  1024. if len(indexData) > 0 {
  1025. logs.Info("ProcessingProfitProcessor Process() : Data already exists for index %d and date %s", indexId, dateText)
  1026. // 无需走更新逻辑,报告每天更新,即使今天和每天数据一致,也需要每天记录,如果到这里也只是说,今天这个报告被读取了两次
  1027. continue
  1028. }
  1029. valueStr := row[columnIdx]
  1030. value, err := strconv.ParseFloat(valueStr, 64)
  1031. if err != nil {
  1032. return []models.BaseFromLyData{}, fmt.Errorf("failed to parse value '%s': %v", valueStr, err)
  1033. }
  1034. // 创建并添加到结果列表
  1035. baseFromLyData := models.BaseFromLyData{
  1036. DataTime: format,
  1037. Value: value,
  1038. BaseFromLyIndexId: indexId,
  1039. IndexCode: indexCode,
  1040. }
  1041. result = append(result, baseFromLyData)
  1042. } else {
  1043. log.Printf("ProcessingProfitProcessor Process() : Column index out of range for row '%s', '%s'", rowVariety, columnDate)
  1044. }
  1045. break
  1046. }
  1047. }
  1048. }
  1049. return result, nil
  1050. }
  1051. // DailyTransactionProcessor
  1052. // @Description: 每日成交处理器
  1053. type DailyTransactionProcessor struct{}
  1054. func (p *DailyTransactionProcessor) Process(ctx context.Context, product string, reportContent string, keywords []string, classifyId int) ([]models.BaseFromLyData, error) {
  1055. fmt.Println("Processing processing profit...")
  1056. // 解析关键字
  1057. if len(keywords) < 4 {
  1058. return []models.BaseFromLyData{}, fmt.Errorf("DailyTransactionProcessor Process() : keywords must contain at least 4 elements")
  1059. }
  1060. // 获取第一个表格
  1061. areaTableDataList := getNoHeadTableData(reportContent)
  1062. if len(areaTableDataList) == 0 {
  1063. return []models.BaseFromLyData{}, fmt.Errorf("DailyTransactionProcessor Process() : No table data found")
  1064. }
  1065. areaTableData := areaTableDataList[0]
  1066. // 获取第二个表格
  1067. blocTableData := getTableData(reportContent, false)
  1068. if blocTableData.Headers == nil {
  1069. return []models.BaseFromLyData{}, fmt.Errorf("DailyTransactionProcessor Process() : No table data found")
  1070. }
  1071. logs.Info("SupplyDemandBalanceProcessor Process() : areaTableData data: %v, blocTableData data: %v", areaTableData, blocTableData)
  1072. // 提取日期信息
  1073. dateText, err := getDateInfo(ctx)
  1074. if err != nil {
  1075. return []models.BaseFromLyData{}, err
  1076. }
  1077. // 时间格式转换
  1078. format, err := utils.ConvertTimeFormat(dateText)
  1079. if err != nil {
  1080. return []models.BaseFromLyData{}, err
  1081. }
  1082. // 处理提取的表格数据
  1083. var result []models.BaseFromLyData
  1084. areaHeaders := areaTableData.Headers
  1085. areaRows := areaTableData.Rows
  1086. // 第一个表格
  1087. // 拿到 行关键字和列关键字
  1088. columnArea := keywords[1]
  1089. var rowAreaMonthDays []string
  1090. rowWeek := "地区总计"
  1091. monthDay, err := utils.GetWeekdaysInSameWeek(format)
  1092. if err != nil {
  1093. return nil, err
  1094. }
  1095. rowAreaMonthDays = monthDay
  1096. // 查找目标列
  1097. areaColumnIdx := -1
  1098. for i, header := range areaHeaders {
  1099. if strings.Contains(header, columnArea) {
  1100. areaColumnIdx = i
  1101. break
  1102. }
  1103. }
  1104. if areaColumnIdx == -1 {
  1105. log.Printf("DailyTransactionProcessor Process() : One Column '%s' not found in table", columnArea)
  1106. } else if !strings.Contains(strings.Join(keywords[:len(keywords)-3], ":"), "主要集团") {
  1107. for _, row := range areaRows {
  1108. if len(row) >= len(areaHeaders) && row[0] == rowWeek {
  1109. if areaColumnIdx < len(row) {
  1110. // 指标名称
  1111. indexName := strings.Join(keywords[:len(keywords)-3], ":")
  1112. // 指标编码
  1113. indexCode := utils.GenerateIndexCode(sourceName, indexName)
  1114. // 指标id获取
  1115. indexId, err := getIndexId(indexCode, indexName, classifyId, sourceName, keywords[len(keywords)-2], keywords[len(keywords)-1])
  1116. if err != nil {
  1117. logs.Error("DailyTransactionProcessor Process() : Failed to get index id: %v", err)
  1118. continue
  1119. }
  1120. paramsLib := make(map[string]interface{})
  1121. paramsLib["IndexId"] = indexId
  1122. paramsLib["DataTime"] = format
  1123. postEdbLib, err := httpRequestFill(paramsLib, utils.GET_LY_DATA_BY_INDEX_ID_AND_DATA_TIME)
  1124. if err != nil {
  1125. logs.Error("DailyTransactionProcessor Process() : Failed to get data by index id and date: %v", err)
  1126. continue
  1127. }
  1128. var requestResponse models.RequestResponse[[]models.BaseFromLyData]
  1129. err = json.Unmarshal(postEdbLib, &requestResponse)
  1130. indexData := requestResponse.Data
  1131. if len(indexData) > 0 {
  1132. logs.Info("DailyTransactionProcessor Process() : Data already exists for index %d and date %s", indexId, dateText)
  1133. // 无需走更新逻辑,报告每周更新,一周出来一周中每天得数据,即使本周和上周数据一致,也需要每天记录,如果到这里也只是说,今天这个报告被读取了两次
  1134. continue
  1135. }
  1136. valueStr := row[areaColumnIdx]
  1137. isChinese := IsChinese(valueStr)
  1138. if isChinese {
  1139. continue
  1140. }
  1141. value, err := strconv.ParseFloat(valueStr, 64)
  1142. if err != nil {
  1143. return []models.BaseFromLyData{}, fmt.Errorf("failed to parse value '%s': %v", valueStr, err)
  1144. }
  1145. // 创建并添加到结果列表
  1146. var dealDate string
  1147. if row[0] == rowWeek {
  1148. dealDate = format
  1149. } else {
  1150. date, err := utils.ConvertToDate(row[0])
  1151. if err != nil {
  1152. return nil, err
  1153. }
  1154. dealDate = date
  1155. }
  1156. baseFromLyData := models.BaseFromLyData{
  1157. DataTime: dealDate,
  1158. Value: value,
  1159. BaseFromLyIndexId: indexId,
  1160. IndexCode: indexCode,
  1161. }
  1162. result = append(result, baseFromLyData)
  1163. } else {
  1164. log.Printf("DailyTransactionProcessor Process() : Column index out of range for row '%s', '%s'", monthDay, columnArea)
  1165. }
  1166. break
  1167. } else {
  1168. for _, monthDay := range rowAreaMonthDays {
  1169. if len(row) >= len(areaHeaders) && (row[0] == monthDay && !strings.Contains(strings.Join(keywords[:len(keywords)-3], ":"), "周度")) {
  1170. if areaColumnIdx < len(row) {
  1171. // 指标名称
  1172. indexName := strings.Join(keywords[:len(keywords)-3], ":")
  1173. // 指标编码
  1174. indexCode := utils.GenerateIndexCode(sourceName, indexName)
  1175. // 指标id获取
  1176. indexId, err := getIndexId(indexCode, indexName, classifyId, sourceName, keywords[len(keywords)-2], keywords[len(keywords)-1])
  1177. if err != nil {
  1178. logs.Error("DailyTransactionProcessor Process() : Failed to get index id: %v", err)
  1179. continue
  1180. }
  1181. paramsLib := make(map[string]interface{})
  1182. paramsLib["IndexId"] = indexId
  1183. paramsLib["DataTime"] = format
  1184. postEdbLib, err := httpRequestFill(paramsLib, utils.GET_LY_DATA_BY_INDEX_ID_AND_DATA_TIME)
  1185. if err != nil {
  1186. logs.Error("DailyTransactionProcessor Process() : Failed to get data by index id and date: %v", err)
  1187. continue
  1188. }
  1189. var requestResponse models.RequestResponse[[]models.BaseFromLyData]
  1190. err = json.Unmarshal(postEdbLib, &requestResponse)
  1191. indexData := requestResponse.Data
  1192. if len(indexData) > 0 {
  1193. logs.Info("DailyTransactionProcessor Process() : Data already exists for index %d and date %s", indexId, dateText)
  1194. // 无需走更新逻辑,报告每周更新,即使本周和上周数据一致,也需要每周记录,如果到这里也只是说,今天这个报告被读取了两次
  1195. continue
  1196. }
  1197. valueStr := row[areaColumnIdx]
  1198. isChinese := IsChinese(valueStr)
  1199. if isChinese {
  1200. continue
  1201. }
  1202. value, err := strconv.ParseFloat(valueStr, 64)
  1203. if err != nil {
  1204. return []models.BaseFromLyData{}, fmt.Errorf("failed to parse value '%s': %v", valueStr, err)
  1205. }
  1206. // 创建并添加到结果列表
  1207. var dealDate string
  1208. if row[0] == rowWeek {
  1209. dealDate = format
  1210. } else {
  1211. date, err := utils.ConvertToDate(row[0])
  1212. if err != nil {
  1213. return nil, err
  1214. }
  1215. dealDate = date
  1216. }
  1217. baseFromLyData := models.BaseFromLyData{
  1218. DataTime: dealDate,
  1219. Value: value,
  1220. BaseFromLyIndexId: indexId,
  1221. IndexCode: indexCode,
  1222. }
  1223. result = append(result, baseFromLyData)
  1224. } else {
  1225. log.Printf("DailyTransactionProcessor Process() : Column index out of range for row '%s', '%s'", monthDay, columnArea)
  1226. }
  1227. break
  1228. }
  1229. }
  1230. }
  1231. }
  1232. }
  1233. // 第二个表格
  1234. // 拿到 行关键字和列关键字
  1235. columnBloc := keywords[len(keywords)-3]
  1236. rowBloc := keywords[1]
  1237. blocHeaders := blocTableData.Headers
  1238. blocRows := blocTableData.Rows
  1239. // 查找目标列
  1240. blocColumnIdx := -1
  1241. for i, header := range blocHeaders {
  1242. if strings.Contains(header, columnBloc) {
  1243. blocColumnIdx = i
  1244. break
  1245. }
  1246. }
  1247. if blocColumnIdx == -1 {
  1248. log.Printf("DailyTransactionProcessor Process() : Two Column '%s' not found in table", columnBloc)
  1249. } else {
  1250. // 处理表格中的每一行
  1251. for _, row := range blocRows {
  1252. if len(row) >= len(blocHeaders) && strings.Contains(row[0], rowBloc) {
  1253. if blocColumnIdx < len(row) {
  1254. // 指标名称
  1255. indexName := strings.Join(keywords[:len(keywords)-3], ":")
  1256. indexName = removeParentheses(indexName)
  1257. // 指标编码
  1258. indexCode := utils.GenerateIndexCode(sourceName, indexName)
  1259. // 指标id获取
  1260. indexId, err := getIndexId(indexCode, indexName, classifyId, sourceName, keywords[len(keywords)-2], keywords[len(keywords)-1])
  1261. if err != nil {
  1262. logs.Error("SupplyDemandBalanceProcessor Process() : Failed to get index id: %v", err)
  1263. continue
  1264. }
  1265. paramsLib := make(map[string]interface{})
  1266. paramsLib["IndexId"] = indexId
  1267. paramsLib["DataTime"] = format
  1268. postEdbLib, err := httpRequestFill(paramsLib, utils.GET_LY_DATA_BY_INDEX_ID_AND_DATA_TIME)
  1269. if err != nil {
  1270. logs.Error("SupplyDemandBalanceProcessor Process() : Failed to get data by index id and date: %v", err)
  1271. continue
  1272. }
  1273. var requestResponse models.RequestResponse[[]models.BaseFromLyData]
  1274. err = json.Unmarshal(postEdbLib, &requestResponse)
  1275. indexData := requestResponse.Data
  1276. if len(indexData) > 0 {
  1277. logs.Info("SupplyDemandBalanceProcessor Process() : Data already exists for index %d and date %s", indexId, dateText)
  1278. continue
  1279. }
  1280. valueStr := row[blocColumnIdx]
  1281. value, err := strconv.ParseFloat(valueStr, 64)
  1282. if err != nil {
  1283. return []models.BaseFromLyData{}, fmt.Errorf("SupplyDemandBalanceProcessor Process() : failed to parse value '%s': %v", valueStr, err)
  1284. }
  1285. // 创建并添加到结果列表
  1286. baseFromLyData := models.BaseFromLyData{
  1287. DataTime: format,
  1288. Value: value,
  1289. BaseFromLyIndexId: indexId,
  1290. IndexCode: indexCode,
  1291. }
  1292. result = append(result, baseFromLyData)
  1293. } else {
  1294. log.Printf("SupplyDemandBalanceProcessor Process() : Column index out of range for row '%s', '%s'", rowBloc, columnBloc)
  1295. }
  1296. break
  1297. }
  1298. }
  1299. }
  1300. return result, nil
  1301. }
  1302. // PalmOilImportCostProcessor 棕榈油进口成本
  1303. type PalmOilImportCostProcessor struct{}
  1304. func (p *PalmOilImportCostProcessor) Process(ctx context.Context, product string, reportContent string, keywords []string, classifyId int) ([]models.BaseFromLyData, error) {
  1305. logs.Info("Processing palm oil import cost...")
  1306. // 解析关键字
  1307. if len(keywords) < 5 {
  1308. return []models.BaseFromLyData{}, fmt.Errorf("PalmOilImportCostProcessor Process() : keywords must contain at least 5 elements")
  1309. }
  1310. // 拿到 行关键字和列关键字
  1311. columnName := keywords[len(keywords)-4]
  1312. rowVariety := keywords[0]
  1313. rowPort := keywords[len(keywords)-3]
  1314. indexNamePrefix := keywords[:1]
  1315. indexNameSuffix := keywords[1:]
  1316. // 提取所有表格数据
  1317. tableData := getNoHeadTableData(reportContent)
  1318. // 提取日期信息
  1319. dateText, err := getDateInfo(ctx)
  1320. if err != nil {
  1321. return []models.BaseFromLyData{}, err
  1322. }
  1323. // 时间格式转换
  1324. format, err := utils.ConvertTimeFormat(dateText)
  1325. if err != nil {
  1326. return []models.BaseFromLyData{}, err
  1327. }
  1328. // 解析日期并计算当前月份
  1329. targetMonths, err := utils.GetYearMonthNoYear(format)
  1330. if err != nil {
  1331. return []models.BaseFromLyData{}, fmt.Errorf("PalmOilImportCostProcessor Process() : Failed to parse date: %v", err)
  1332. }
  1333. fmt.Printf("Target Month: %s\n", targetMonths)
  1334. // 处理提取的表格数据
  1335. var result []models.BaseFromLyData
  1336. for _, data := range tableData {
  1337. tableHeaders := data.Headers
  1338. tableRows := data.Rows
  1339. // 查找目标列
  1340. columnIdx := -1
  1341. for i, header := range tableHeaders {
  1342. if strings.Contains(header, columnName) {
  1343. columnIdx = i
  1344. break
  1345. }
  1346. }
  1347. if columnIdx == -1 {
  1348. log.Printf("PalmOilImportCostProcessor Process() : Column '%s' not found in table", columnName)
  1349. continue
  1350. }
  1351. // 处理表格中的每一行
  1352. //var flag bool = true
  1353. var previousRowVariety string
  1354. var previousRowPort string
  1355. var previousRowFob string
  1356. for rowIndex, row := range tableRows {
  1357. if len(row) == len(tableHeaders) {
  1358. previousRowVariety = row[0]
  1359. previousRowPort = row[1]
  1360. previousRowFob = row[2]
  1361. } else if len(row) == len(tableHeaders)-1 {
  1362. previousRowPort = row[0]
  1363. previousRowFob = row[1]
  1364. row = append([]string{previousRowVariety}, row...)
  1365. tableRows[rowIndex] = row
  1366. } else if len(row) == len(tableHeaders)-2 {
  1367. // 这段这里不需要。。。先保留吧
  1368. previousRowFob = row[0]
  1369. row = append([]string{previousRowVariety, previousRowPort}, row...)
  1370. tableRows[rowIndex] = row
  1371. } else if len(row) == len(tableHeaders)-3 {
  1372. row = append([]string{previousRowVariety, previousRowPort, previousRowFob}, row...)
  1373. tableRows[rowIndex] = row
  1374. }
  1375. for _, targetMonth := range targetMonths {
  1376. if len(row) >= len(tableHeaders) && strings.Contains(rowVariety, row[0]) && row[1] == targetMonth && row[len(row)-1] == rowPort {
  1377. if columnIdx < len(row) {
  1378. // 指标名称
  1379. indexNameList := append(indexNamePrefix, append([]string{targetMonth}, indexNameSuffix...)...)
  1380. indexName := strings.Join(indexNameList[:len(keywords)-2], ":")
  1381. // 指标编码
  1382. indexCode := utils.GenerateIndexCode(sourceName, indexName)
  1383. // 指标id获取
  1384. indexId, err := getIndexId(indexCode, indexName, classifyId, sourceName, keywords[len(keywords)-2], keywords[len(keywords)-1])
  1385. if err != nil {
  1386. logs.Error("PalmOilImportCostProcessor Process() : Failed to get index id: %v", err)
  1387. continue
  1388. }
  1389. paramsLib := make(map[string]interface{})
  1390. paramsLib["IndexId"] = indexId
  1391. paramsLib["DataTime"] = format
  1392. postEdbLib, err := httpRequestFill(paramsLib, utils.GET_LY_DATA_BY_INDEX_ID_AND_DATA_TIME)
  1393. if err != nil {
  1394. logs.Error("PalmOilImportCostProcessor Process() : Failed to get data by index id and date: %v", err)
  1395. continue
  1396. }
  1397. var requestResponse models.RequestResponse[[]models.BaseFromLyData]
  1398. err = json.Unmarshal(postEdbLib, &requestResponse)
  1399. indexData := requestResponse.Data
  1400. if len(indexData) > 0 {
  1401. logs.Info("PalmOilImportCostProcessor Process() : Data already exists for index %d and date %s", indexId, dateText)
  1402. continue
  1403. }
  1404. valueStr := row[columnIdx]
  1405. value, err := strconv.ParseFloat(valueStr, 64)
  1406. if err != nil {
  1407. return []models.BaseFromLyData{}, fmt.Errorf("failed to parse value '%s': %v", valueStr, err)
  1408. }
  1409. // 创建并添加到结果列表
  1410. baseFromLyData := models.BaseFromLyData{
  1411. DataTime: format,
  1412. Value: value,
  1413. BaseFromLyIndexId: indexId,
  1414. IndexCode: indexCode,
  1415. }
  1416. result = append(result, baseFromLyData)
  1417. } else {
  1418. log.Printf("PalmOilImportCostProcessor Process() : Column index out of range for row '%s', '%s'", rowVariety, rowPort)
  1419. }
  1420. break
  1421. }
  1422. }
  1423. }
  1424. }
  1425. return result, nil
  1426. }
  1427. // ImportEstimateProcessor
  1428. // @Description: 进口预估处理器
  1429. type ImportEstimateProcessor struct{}
  1430. func (p *ImportEstimateProcessor) Process(ctx context.Context, product string, reportContent string, keywords []string, classifyId int) ([]models.BaseFromLyData, error) {
  1431. logs.Info("Processing import estimate...")
  1432. // 解析关键字
  1433. if len(keywords) < 4 {
  1434. return []models.BaseFromLyData{}, fmt.Errorf("ImportEstimateProcessor Process() : keywords must contain at least 4 elements")
  1435. }
  1436. // 拿到 行关键字和列关键字
  1437. var columnDates []string
  1438. rowVariety := keywords[1]
  1439. // 提取所有表格数据
  1440. tableData := getNoHeadTableData(reportContent)
  1441. // 提取日期信息
  1442. dateText, err := getDateInfo(ctx)
  1443. if err != nil {
  1444. return []models.BaseFromLyData{}, err
  1445. }
  1446. // 时间格式转换
  1447. format, err := utils.ConvertTimeFormat(dateText)
  1448. if err != nil {
  1449. return []models.BaseFromLyData{}, err
  1450. }
  1451. columnDates, err = utils.GetNextThreeMonthsNoYear(format)
  1452. if err != nil {
  1453. return nil, err
  1454. }
  1455. monthsLastDay, err := utils.GetNextThreeMonthsLastDay(format)
  1456. if err != nil {
  1457. return nil, err
  1458. }
  1459. // 处理提取的表格数据
  1460. var result []models.BaseFromLyData
  1461. for _, data := range tableData {
  1462. tableHeaders := data.Headers
  1463. tableRows := data.Rows
  1464. // 查找目标列
  1465. for _, columnDate := range columnDates {
  1466. columnIdx := -1
  1467. for i, tableHeader := range tableHeaders {
  1468. if strings.Contains(tableHeader, columnDate) {
  1469. columnIdx = i
  1470. break
  1471. }
  1472. }
  1473. if columnIdx == -1 {
  1474. log.Printf("ImportEstimateProcessor Process() : Column '%s' not found in table", columnDate)
  1475. continue
  1476. } else {
  1477. // 处理表格中的每一行
  1478. for _, row := range tableRows {
  1479. if len(row) >= len(tableHeaders) && strings.Contains(row[0], rowVariety) && isNumber(row[columnIdx]) {
  1480. if columnIdx < len(row) {
  1481. // 指标名称
  1482. indexName := strings.Join(keywords[:len(keywords)-2], `:`)
  1483. // 指标编码
  1484. indexCode := utils.GenerateIndexCode(sourceName, indexName)
  1485. // 指标id获取
  1486. indexId, err := getIndexId(indexCode, indexName, classifyId, sourceName, keywords[len(keywords)-2], keywords[len(keywords)-1])
  1487. if err != nil {
  1488. logs.Error("ImportEstimateProcessor Process() : Failed to get index id: %v", err)
  1489. continue
  1490. }
  1491. toNumber, err := utils.ConvertMonthToNumber(columnDate)
  1492. if err != nil {
  1493. logs.Error("ImportEstimateProcessor Process() : Failed to convert month to number: %v", err)
  1494. continue
  1495. }
  1496. slice, err := utils.GetElementInSlice(monthsLastDay, toNumber)
  1497. if err != nil {
  1498. logs.Error("ImportEstimateProcessor Process() : Failed to get element in slice: %v", err)
  1499. continue
  1500. }
  1501. paramsLib := make(map[string]interface{})
  1502. paramsLib["IndexId"] = indexId
  1503. paramsLib["DataTime"] = format
  1504. postEdbLib, err := httpRequestFill(paramsLib, utils.GET_LY_DATA_BY_INDEX_ID_AND_DATA_TIME)
  1505. if err != nil {
  1506. logs.Error("ImportEstimateProcessor Process() : Failed to get data by index id and date: %v", err)
  1507. continue
  1508. }
  1509. var requestResponse models.RequestResponse[[]models.BaseFromLyData]
  1510. err = json.Unmarshal(postEdbLib, &requestResponse)
  1511. indexData := requestResponse.Data
  1512. valueStr := row[columnIdx]
  1513. value, err := strconv.ParseFloat(valueStr, 64)
  1514. if err != nil {
  1515. return []models.BaseFromLyData{}, fmt.Errorf("failed to parse value '%s': %v", valueStr, err)
  1516. }
  1517. if len(indexData) > 0 {
  1518. if indexData[0].Value != value {
  1519. logs.Info("ImportEstimateProcessor Process() : Data already exists for index %d and date %s", indexId, dateText)
  1520. lyData := indexData[0]
  1521. time, err := utils.StringToTime(lyData.ModifyTime)
  1522. if err != nil {
  1523. return nil, err
  1524. }
  1525. timeZero, err := utils.StringToTimeZero(format)
  1526. if err != nil {
  1527. return nil, err
  1528. }
  1529. if lyData.Value != value && time.Before(timeZero) {
  1530. // 更新指标数据
  1531. paramsLib := make(map[string]interface{})
  1532. paramsLib["Id"] = lyData.BaseFromLyDataId
  1533. paramsLib["Value"] = value
  1534. _, err := httpRequestFill(paramsLib, utils.UPDATE_LY_DATA_BY_ID)
  1535. if err != nil {
  1536. return nil, fmt.Errorf("ImportEstimateProcessor Process() : failed to parse value '%s': %v", valueStr, err)
  1537. }
  1538. // 同步更新指标库数据
  1539. paramsLib = make(map[string]interface{})
  1540. paramsLib["IndexCode"] = lyData.IndexCode
  1541. paramsLib["DataTime"] = lyData.DataTime
  1542. postEdbLib, err := httpRequestFill(paramsLib, utils.GET_LY_EDB_DATA_BY_INDEX_CODE_AND_EXACT_DATA_TIME)
  1543. if err != nil {
  1544. logs.Error("ImportEstimateProcessor Process() : Failed to get ly edb data by index code and exact data time: %v", err)
  1545. continue
  1546. }
  1547. var requestResponse models.RequestResponse[[]models.EdbDataLy]
  1548. err = json.Unmarshal(postEdbLib, &requestResponse)
  1549. if err != nil {
  1550. return nil, err
  1551. }
  1552. lyEdbIndexData := requestResponse.Data
  1553. if len(lyEdbIndexData) > 0 {
  1554. paramsLib := make(map[string]interface{})
  1555. paramsLib["Id"] = lyEdbIndexData[0].EdbInfoId
  1556. paramsLib["Value"] = value
  1557. _, err := httpRequestFill(paramsLib, utils.UPDATE_LY_EDB_DATA_BY_ID)
  1558. if err != nil {
  1559. return nil, fmt.Errorf("ImportEstimateProcessor Process() : failed to parse value '%s': %v", valueStr, err)
  1560. }
  1561. }
  1562. }
  1563. }
  1564. continue
  1565. }
  1566. // 创建并添加到结果列表
  1567. baseFromLyData := models.BaseFromLyData{
  1568. DataTime: slice,
  1569. Value: value,
  1570. BaseFromLyIndexId: indexId,
  1571. IndexCode: indexCode,
  1572. }
  1573. result = append(result, baseFromLyData)
  1574. } else {
  1575. log.Printf("ImportEstimateProcessor Process() : Column index out of range for row '%s', '%s'", rowVariety, columnDate)
  1576. }
  1577. break
  1578. }
  1579. }
  1580. }
  1581. }
  1582. }
  1583. return result, nil
  1584. }
  1585. // InternationalPriceProcessor
  1586. // @Description: 国际价格处理器
  1587. type InternationalPriceProcessor struct{}
  1588. func (p *InternationalPriceProcessor) Process(ctx context.Context, product string, reportContent string, keywords []string, classifyId int) ([]models.BaseFromLyData, error) {
  1589. logs.Info("Processing international price...")
  1590. // 解析关键字
  1591. if len(keywords) < 4 {
  1592. return []models.BaseFromLyData{}, fmt.Errorf("InternationalPriceProcessor Process() : keywords must contain at least 4 elements")
  1593. }
  1594. // 拿到 行关键字和列关键字
  1595. columnName := keywords[1]
  1596. rowVariety := keywords[0]
  1597. indexNamePrefix := keywords[:1]
  1598. indexNameSuffix := keywords[1:]
  1599. // 提取所有表格数据
  1600. tableData := getNoHeadTableData(reportContent)
  1601. // 提取日期信息
  1602. dateText, err := getDateInfo(ctx)
  1603. if err != nil {
  1604. return []models.BaseFromLyData{}, err
  1605. }
  1606. // 时间格式转换
  1607. format, err := utils.ConvertTimeFormat(dateText)
  1608. if err != nil {
  1609. return []models.BaseFromLyData{}, err
  1610. }
  1611. // 解析日期并计算当前月份 和 后两月
  1612. yearMonths, err := utils.ConvertTimeFormatToYearMonth(format)
  1613. if err != nil {
  1614. return nil, err
  1615. }
  1616. fmt.Printf("Target yearMonth: %s\n", yearMonths)
  1617. // 处理提取的表格数据
  1618. var result []models.BaseFromLyData
  1619. for _, data := range tableData {
  1620. tableHeaders := data.Headers
  1621. tableRows := data.Rows
  1622. // 查找目标列
  1623. columnIdx := -1
  1624. for i, header := range tableHeaders {
  1625. if strings.Contains(header, columnName) {
  1626. columnIdx = i
  1627. break
  1628. }
  1629. }
  1630. if columnIdx == -1 {
  1631. log.Printf("InternationalPriceProcessor Process() : Column '%s' not found in table", columnName)
  1632. continue
  1633. }
  1634. // 处理表格中的每一行
  1635. var previousRowVariety string
  1636. for rowIndex, row := range tableRows {
  1637. if len(row) == len(tableHeaders) {
  1638. previousRowVariety = row[0]
  1639. } else if len(row) == len(tableHeaders)-1 {
  1640. row = append([]string{previousRowVariety}, row...)
  1641. tableRows[rowIndex] = row
  1642. }
  1643. for _, targetMonth := range yearMonths {
  1644. if len(row) >= len(tableHeaders) && row[0] == rowVariety && row[1] == targetMonth {
  1645. if columnIdx < len(row) {
  1646. // 指标名称
  1647. indexNameList := append(indexNamePrefix, append([]string{targetMonth}, indexNameSuffix...)...)
  1648. indexName := strings.Join(indexNameList[:len(keywords)-2], ":")
  1649. // 指标编码
  1650. indexCode := utils.GenerateIndexCode(sourceName, indexName)
  1651. // 指标id获取
  1652. indexId, err := getIndexId(indexCode, indexName, classifyId, sourceName, keywords[len(keywords)-2], keywords[len(keywords)-1])
  1653. if err != nil {
  1654. logs.Error("InternationalPriceProcessor Process() : Failed to get index id: %v", err)
  1655. continue
  1656. }
  1657. paramsLib := make(map[string]interface{})
  1658. paramsLib["IndexId"] = indexId
  1659. paramsLib["DataTime"] = format
  1660. postEdbLib, err := httpRequestFill(paramsLib, utils.GET_LY_DATA_BY_INDEX_ID_AND_DATA_TIME)
  1661. if err != nil {
  1662. logs.Error("InternationalPriceProcessor Process() : Failed to get data by index id and date: %v", err)
  1663. continue
  1664. }
  1665. var requestResponse models.RequestResponse[[]models.BaseFromLyData]
  1666. err = json.Unmarshal(postEdbLib, &requestResponse)
  1667. indexData := requestResponse.Data
  1668. if len(indexData) > 0 {
  1669. logs.Info("InternationalPriceProcessor Process() : Data already exists for index %d and date %s", indexId, dateText)
  1670. // 无需更新 指标展示本月和后两月的数据,报告每天更新,每天的值可能会改变,即使今天和每天数据一致,也需要每天记录,如果到这里也只是说,今天这个报告被读取了两次
  1671. continue
  1672. }
  1673. valueStr := row[columnIdx]
  1674. value, err := strconv.ParseFloat(valueStr, 64)
  1675. if err != nil {
  1676. return []models.BaseFromLyData{}, fmt.Errorf("failed to parse value '%s': %v", valueStr, err)
  1677. }
  1678. // 创建并添加到结果列表
  1679. baseFromLyData := models.BaseFromLyData{
  1680. DataTime: format,
  1681. Value: value,
  1682. BaseFromLyIndexId: indexId,
  1683. IndexCode: indexCode,
  1684. }
  1685. result = append(result, baseFromLyData)
  1686. } else {
  1687. log.Printf("InternationalPriceProcessor Process() : Column index out of range for row '%s', '%s'", rowVariety, columnName)
  1688. }
  1689. break
  1690. }
  1691. }
  1692. }
  1693. }
  1694. return result, nil
  1695. }
  1696. // CanadaStatisticsBureauProcessor
  1697. // @Description: 加拿大统计局处理器
  1698. type CanadaStatisticsBureauProcessor struct{}
  1699. func (p *CanadaStatisticsBureauProcessor) Process(ctx context.Context, product string, reportContent string, keywords []string, classifyId int) ([]models.BaseFromLyData, error) {
  1700. logs.Info("Processing Canada statistics bureau...")
  1701. // 解析关键字
  1702. if len(keywords) < 4 {
  1703. return []models.BaseFromLyData{}, fmt.Errorf("CanadaStatisticsBureauProcessor Process() : keywords must contain at least 4 elements")
  1704. }
  1705. // 拿到 行关键字和列关键字
  1706. columnDate := "本周"
  1707. rowVariety := keywords[1]
  1708. // 提取所有表格数据
  1709. tableData := getNoHeadTableData(reportContent)
  1710. // 提取日期信息
  1711. dateText, err := getDateInfo(ctx)
  1712. if err != nil {
  1713. return []models.BaseFromLyData{}, err
  1714. }
  1715. // 时间格式转换
  1716. format, err := utils.ConvertTimeFormat(dateText)
  1717. if err != nil {
  1718. return []models.BaseFromLyData{}, err
  1719. }
  1720. // 处理提取的表格数据
  1721. var result []models.BaseFromLyData
  1722. for _, data := range tableData {
  1723. tableHeaders := data.Headers
  1724. tableRows := data.Rows
  1725. // 查找目标列
  1726. columnIdx := -1
  1727. for i, header := range tableHeaders {
  1728. if strings.Contains(header, columnDate) {
  1729. columnIdx = i
  1730. break
  1731. }
  1732. }
  1733. if columnIdx == -1 {
  1734. log.Printf("CanadaStatisticsBureauProcessor Process() : Column '%s' not found in table", columnDate)
  1735. continue
  1736. }
  1737. // 处理表格中的每一行
  1738. for _, row := range tableRows {
  1739. if len(row) >= len(tableHeaders) {
  1740. if columnIdx < len(row) {
  1741. if row[0] != rowVariety {
  1742. continue
  1743. }
  1744. // 指标名称
  1745. indexName := strings.Join(keywords[:len(keywords)-2], ":")
  1746. // 指标编码
  1747. indexCode := utils.GenerateIndexCode(sourceName, indexName)
  1748. // 指标id获取
  1749. indexId, err := getIndexId(indexCode, indexName, classifyId, sourceName, keywords[len(keywords)-2], keywords[len(keywords)-1])
  1750. if err != nil {
  1751. logs.Error("CanadaStatisticsBureauProcessor Process() : Failed to get index id: %v", err)
  1752. continue
  1753. }
  1754. paramsLib := make(map[string]interface{})
  1755. paramsLib["IndexId"] = indexId
  1756. paramsLib["DataTime"] = format
  1757. postEdbLib, err := httpRequestFill(paramsLib, utils.GET_LY_DATA_BY_INDEX_ID_AND_DATA_TIME)
  1758. if err != nil {
  1759. logs.Error("CanadaStatisticsBureauProcessor Process() : Failed to get data by index id and date: %v", err)
  1760. continue
  1761. }
  1762. var requestResponse models.RequestResponse[[]models.BaseFromLyData]
  1763. err = json.Unmarshal(postEdbLib, &requestResponse)
  1764. indexData := requestResponse.Data
  1765. if len(indexData) > 0 {
  1766. logs.Info("CanadaStatisticsBureauProcessor Process() : Data already exists for index %d and date %s", indexId, dateText)
  1767. // 无需更新 指标展示本周的数据,报告每周更新,即使本周和上周数据一致,也需要每周记录,如果到这里也只是说,今天这个报告被读取了两次
  1768. continue
  1769. }
  1770. valueStr := row[columnIdx]
  1771. value, err := strconv.ParseFloat(valueStr, 64)
  1772. if err != nil {
  1773. return []models.BaseFromLyData{}, fmt.Errorf("failed to parse value '%s': %v", valueStr, err)
  1774. }
  1775. // 创建并添加到结果列表
  1776. baseFromLyData := models.BaseFromLyData{
  1777. DataTime: format,
  1778. Value: value,
  1779. BaseFromLyIndexId: indexId,
  1780. IndexCode: indexCode,
  1781. }
  1782. result = append(result, baseFromLyData)
  1783. } else {
  1784. log.Printf("CanadaStatisticsBureauProcessor Process() : Column index out of range for row '%s'", columnDate)
  1785. }
  1786. break
  1787. }
  1788. }
  1789. }
  1790. return result, nil
  1791. }
  1792. // ImportExportAnalysisProcessor
  1793. // @Description: 进出口分析处理器
  1794. type ImportExportAnalysisProcessor struct{}
  1795. func (p *ImportExportAnalysisProcessor) Process(ctx context.Context, product string, reportContent string, keywords []string, classifyId int) ([]models.BaseFromLyData, error) {
  1796. fmt.Println("Processing processing profit...")
  1797. // 解析关键字
  1798. if len(keywords) < 3 {
  1799. return []models.BaseFromLyData{}, fmt.Errorf("ProcessingProfitProcessor Process() : keywords must contain at least 3 elements")
  1800. }
  1801. // 拿到 行关键字和列关键字
  1802. var columnDates []string
  1803. // 提取所有表格数据
  1804. tableData := getNoHeadTableData(reportContent)
  1805. // 提取日期信息
  1806. dateText, err := getDateInfo(ctx)
  1807. if err != nil {
  1808. return []models.BaseFromLyData{}, err
  1809. }
  1810. // 时间格式转换
  1811. format, err := utils.ConvertTimeFormat(dateText)
  1812. if err != nil {
  1813. return []models.BaseFromLyData{}, err
  1814. }
  1815. // 2025年1月可能才出2024年12月的数据,所以往前取一年
  1816. columnDates, err = utils.GetCurrentYearAndLastYear(format)
  1817. if err != nil {
  1818. return nil, err
  1819. }
  1820. // 处理提取的表格数据
  1821. var result []models.BaseFromLyData
  1822. for _, data := range tableData {
  1823. tableHeaders := data.Headers
  1824. tableRows := data.Rows
  1825. for _, columnDate := range columnDates {
  1826. // 查找目标列
  1827. columnIdx := -1
  1828. for i, header := range tableHeaders {
  1829. if strings.Contains(header, columnDate) {
  1830. columnIdx = i
  1831. break
  1832. }
  1833. }
  1834. if columnIdx == -1 {
  1835. log.Printf("ProcessingProfitProcessor Process() : Column '%s' not found in table", columnDate)
  1836. continue
  1837. }
  1838. // 处理表格中的每一行
  1839. for _, row := range tableRows {
  1840. if len(row) >= len(tableHeaders) {
  1841. if columnIdx < len(row) && isNumber(row[columnIdx]) && isNumber(row[0]) {
  1842. // 指标名称
  1843. indexName := strings.Join(keywords[:len(keywords)-2], ":")
  1844. // 指标编码
  1845. indexCode := utils.GenerateIndexCode(sourceName, indexName)
  1846. // 指标id获取
  1847. indexId, err := getIndexId(indexCode, indexName, classifyId, sourceName, keywords[len(keywords)-2], keywords[len(keywords)-1])
  1848. if err != nil {
  1849. logs.Error("ProcessingProfitProcessor Process() : Failed to get index id: %v", err)
  1850. continue
  1851. }
  1852. atoi, err := strconv.Atoi(row[0])
  1853. if err != nil {
  1854. return nil, err
  1855. }
  1856. date := columnDate[:4] + "-" + fmt.Sprintf("%02d", atoi)
  1857. lastDayOfMonth, err := utils.GetLastDayOfMonth(date)
  1858. if err != nil {
  1859. return nil, err
  1860. }
  1861. paramsLib := make(map[string]interface{})
  1862. paramsLib["IndexId"] = indexId
  1863. paramsLib["DataTime"] = format
  1864. postEdbLib, err := httpRequestFill(paramsLib, utils.GET_LY_DATA_BY_INDEX_ID_AND_DATA_TIME)
  1865. if err != nil {
  1866. logs.Error("ProcessingProfitProcessor Process() : Failed to get data by index id and date: %v", err)
  1867. continue
  1868. }
  1869. var requestResponse models.RequestResponse[[]models.BaseFromLyData]
  1870. err = json.Unmarshal(postEdbLib, &requestResponse)
  1871. indexData := requestResponse.Data
  1872. if len(indexData) > 0 {
  1873. logs.Info("ProcessingProfitProcessor Process() : Data already exists for index %d and date %s", indexId, dateText)
  1874. continue
  1875. }
  1876. valueStr := row[columnIdx]
  1877. value, err := strconv.ParseFloat(valueStr, 64)
  1878. if err != nil {
  1879. return []models.BaseFromLyData{}, fmt.Errorf("failed to parse value '%s': %v", valueStr, err)
  1880. }
  1881. // 创建并添加到结果列表
  1882. baseFromLyData := models.BaseFromLyData{
  1883. DataTime: lastDayOfMonth,
  1884. Value: value,
  1885. BaseFromLyIndexId: indexId,
  1886. IndexCode: indexCode,
  1887. }
  1888. result = append(result, baseFromLyData)
  1889. continue
  1890. } else {
  1891. log.Printf("ProcessingProfitProcessor Process() : Column index out of range for row '%s'", columnDate)
  1892. }
  1893. break
  1894. }
  1895. }
  1896. }
  1897. }
  1898. return result, nil
  1899. }
  1900. // ExtractValueInParentheses 从字符串中提取括号中的值
  1901. func extractValueInParentheses(input string) (string, error) {
  1902. re := regexp.MustCompile(`(([^)]+))`)
  1903. matches := re.FindStringSubmatch(input)
  1904. if len(matches) > 1 {
  1905. return matches[1], nil
  1906. }
  1907. return "", fmt.Errorf("no value found in parentheses")
  1908. }
  1909. // 获取指标id,根据指标名称判断,没有插入指标生成返回
  1910. func getIndexId(indexCode string, indexName string, classifyId int, sourceName string, frequency string, unit string) (int, error) {
  1911. if indexCode == "lysww" {
  1912. return 0, fmt.Errorf("indexCode is error")
  1913. }
  1914. // 判断指标是否存在
  1915. var indexId int
  1916. paramsLib := make(map[string]interface{})
  1917. paramsLib["IndexCode"] = indexCode
  1918. postEdbLib, err := httpRequestFill(paramsLib, utils.GET_LY_INDEX_BY_CODE)
  1919. if err != nil {
  1920. return 0, fmt.Errorf("getIndexId() : Failed to get ly index by code: %v", err)
  1921. }
  1922. var requestResponse models.RequestResponse[models.BaseFromLyIndex]
  1923. err = json.Unmarshal(postEdbLib, &requestResponse)
  1924. if err != nil {
  1925. return 0, fmt.Errorf("getIndexId() : Failed to unmarshal response: %v", err)
  1926. }
  1927. indexInfo := requestResponse.Data
  1928. if indexInfo.IndexName == "" {
  1929. // 新增指标
  1930. index, err := addLyIndex(classifyId, indexCode, indexName, frequency, unit)
  1931. if err != nil {
  1932. return 0, err
  1933. }
  1934. indexId = index
  1935. } else {
  1936. indexId = indexInfo.BaseFromLyIndexId
  1937. }
  1938. return indexId, nil
  1939. }
  1940. // 获取页面时间信息
  1941. func getDateInfo(ctx context.Context) (string, error) {
  1942. var dateText string
  1943. err := chromedp.Run(ctx,
  1944. chromedp.Evaluate(`document.querySelector('div.a_date span').innerText`, &dateText),
  1945. )
  1946. if err != nil {
  1947. return "", fmt.Errorf("processing Process() : Failed to extract report date: %v", err)
  1948. }
  1949. logs.Info("Processing Process() : Report Extracted Date: %s", dateText)
  1950. return dateText, nil
  1951. }
  1952. // 获取所有表格数据 获取表格中有thead标签的数据
  1953. func getAllTableData(reportContent string) []TableData {
  1954. var tableData []TableData
  1955. doc, err := goquery.NewDocumentFromReader(strings.NewReader(reportContent))
  1956. if err != nil {
  1957. log.Fatal(err)
  1958. }
  1959. // 选择 id 为 "a_content" 的 div
  1960. doc.Find("#a_content").Each(func(index int, item *goquery.Selection) {
  1961. item.Find("table").Each(func(index int, table *goquery.Selection) {
  1962. var headers []string
  1963. var rows [][]string
  1964. // 提取表头
  1965. table.Find("thead th").Each(func(index int, th *goquery.Selection) {
  1966. headers = append(headers, th.Text())
  1967. })
  1968. // 提取表格行数据
  1969. table.Find("tbody tr").Each(func(index int, row *goquery.Selection) {
  1970. var rowData []string
  1971. row.Find("td").Each(func(index int, td *goquery.Selection) {
  1972. rowData = append(rowData, td.Text())
  1973. })
  1974. rows = append(rows, rowData)
  1975. })
  1976. // 仅在表头存在时添加到结果中
  1977. if len(headers) > 0 {
  1978. tableData = append(tableData, TableData{
  1979. Headers: headers,
  1980. Rows: rows,
  1981. })
  1982. }
  1983. })
  1984. })
  1985. return tableData
  1986. }
  1987. // 获取无头表格数据
  1988. func getNoHeadTableData(reportContent string) []TableData {
  1989. var tableData []TableData
  1990. doc, err := goquery.NewDocumentFromReader(strings.NewReader(reportContent))
  1991. if err != nil {
  1992. log.Fatal(err)
  1993. }
  1994. // Find the div with id "a_content"
  1995. doc.Find("#a_content").Each(func(index int, div *goquery.Selection) {
  1996. // Find all tables within the div
  1997. div.Find("table").Each(func(index int, table *goquery.Selection) {
  1998. var headers []string
  1999. var rows [][]string
  2000. // Extract table headers if any
  2001. table.Find("tr").Each(func(index int, tr *goquery.Selection) {
  2002. var rowData []string
  2003. tr.Find("td, th").Each(func(index int, cell *goquery.Selection) {
  2004. cellText := cell.Text()
  2005. rowData = append(rowData, cellText)
  2006. })
  2007. if index == 0 && len(rowData) > 0 {
  2008. // The first row is treated as the header row
  2009. headers = rowData
  2010. } else if len(rowData) > 0 {
  2011. // Add the row data to the rows slice
  2012. rows = append(rows, rowData)
  2013. }
  2014. })
  2015. // Only add table data if headers are present
  2016. if len(headers) > 0 {
  2017. tableData = append(tableData, TableData{
  2018. Headers: headers,
  2019. Rows: rows,
  2020. })
  2021. }
  2022. })
  2023. })
  2024. return tableData
  2025. }
  2026. // 获取表格数据 获取id 为 a_content 的 div 中的第一个表格 左上角那个单元格会拼在第一个,会拼上列上的合并单元格
  2027. func getTableData(reportContent string, isFirst bool) TableData {
  2028. doc, err := goquery.NewDocumentFromReader(strings.NewReader(reportContent))
  2029. if err != nil {
  2030. log.Fatal(err)
  2031. }
  2032. tableData := &TableData{}
  2033. // 只提取 id 为 a_content 的 div 中的第一个表格
  2034. var firstTable *goquery.Selection
  2035. if isFirst {
  2036. firstTable = doc.Find("div#a_content table").First()
  2037. } else {
  2038. firstTable = doc.Find("div#a_content table").Last()
  2039. }
  2040. var combinedHeaders []string
  2041. // 提取表头
  2042. firstTable.Find("tr").Each(func(i int, row *goquery.Selection) {
  2043. if i == 0 {
  2044. // 第一行处理合并单元格,保存到 combinedHeaders
  2045. row.Find("td,th").Each(func(j int, cell *goquery.Selection) {
  2046. if j == 0 {
  2047. // 把左上角的“年度(10/9月)”放入 Headers 第一个元素
  2048. tableData.Headers = append(tableData.Headers, strings.TrimSpace(cell.Text()))
  2049. } else {
  2050. // 处理其他单元格
  2051. colspan, exists := cell.Attr("colspan")
  2052. if exists {
  2053. spanCount := 0
  2054. fmt.Sscanf(colspan, "%d", &spanCount)
  2055. for k := 0; k < spanCount; k++ {
  2056. combinedHeaders = append(combinedHeaders, strings.TrimSpace(cell.Text()))
  2057. }
  2058. } else {
  2059. combinedHeaders = append(combinedHeaders, strings.TrimSpace(cell.Text()))
  2060. }
  2061. }
  2062. })
  2063. } else if i == 1 {
  2064. // 第二行处理具体标题,组合后保存到 Headers
  2065. row.Find("td,th").Each(func(j int, cell *goquery.Selection) {
  2066. if j < len(combinedHeaders) {
  2067. fullHeader := combinedHeaders[j] + strings.TrimSpace(cell.Text())
  2068. tableData.Headers = append(tableData.Headers, fullHeader)
  2069. }
  2070. })
  2071. } else {
  2072. // 处理数据行
  2073. var rowData []string
  2074. row.Find("td").Each(func(j int, cell *goquery.Selection) {
  2075. rowData = append(rowData, strings.TrimSpace(cell.Text()))
  2076. })
  2077. if len(rowData) > 0 {
  2078. tableData.Rows = append(tableData.Rows, rowData)
  2079. }
  2080. }
  2081. })
  2082. return *tableData
  2083. }
  2084. // 获取采购装船表格数据
  2085. func getPurchaseShippingTableData(reportContent string) TableData {
  2086. doc, err := goquery.NewDocumentFromReader(strings.NewReader(reportContent))
  2087. if err != nil {
  2088. log.Fatal(err)
  2089. }
  2090. var tableData TableData
  2091. // 只提取 id 为 a_content 的 div 中的第一个表格
  2092. firstTable := doc.Find("div#a_content table").First()
  2093. // 提取表头
  2094. var headers []string
  2095. var subHeaders []string
  2096. firstTable.Find("thead tr").Each(func(i int, row *goquery.Selection) {
  2097. row.Find("th").Each(func(j int, cell *goquery.Selection) {
  2098. headerText := strings.TrimSpace(cell.Text())
  2099. if i == 0 {
  2100. // 处理第一行表头
  2101. colspan, exists := cell.Attr("colspan")
  2102. if exists {
  2103. spanCount := 0
  2104. fmt.Sscanf(colspan, "%d", &spanCount)
  2105. for k := 0; k < spanCount; k++ {
  2106. headers = append(headers, headerText)
  2107. }
  2108. } else {
  2109. headers = append(headers, headerText)
  2110. }
  2111. } else if i == 1 {
  2112. // 处理第二行表头
  2113. subHeaders = append(subHeaders, headerText)
  2114. }
  2115. })
  2116. })
  2117. // 合并第一行和第二行表头信息
  2118. if len(subHeaders) > 0 {
  2119. for i := 0; i < len(subHeaders); i++ {
  2120. // 从第四个单元格开始拼接
  2121. headers[3+i] = headers[3+i] + subHeaders[i]
  2122. }
  2123. }
  2124. tableData.Headers = headers
  2125. // 处理数据行
  2126. firstTable.Find("tbody tr").Each(func(i int, row *goquery.Selection) {
  2127. var rowData []string
  2128. row.Find("td").Each(func(j int, cell *goquery.Selection) {
  2129. rowData = append(rowData, strings.TrimSpace(cell.Text()))
  2130. })
  2131. if len(rowData) > 0 {
  2132. tableData.Rows = append(tableData.Rows, rowData)
  2133. }
  2134. })
  2135. return tableData
  2136. }
  2137. // 判断字符串是否是数字
  2138. func isNumeric(value string) bool {
  2139. // 正则表达式匹配整数和浮点数
  2140. re := regexp.MustCompile(`^[+-]?(\d+(\.\d*)?|\.\d+)$`)
  2141. return re.MatchString(value)
  2142. }
  2143. // 只保留汉字
  2144. func extractChinese(text string) string {
  2145. re := regexp.MustCompile(`[^\p{Han}]`) // 匹配非汉字字符
  2146. return re.ReplaceAllString(text, "")
  2147. }
  2148. // 去除括号中的内容 包含括号 ()
  2149. func removeParentheses(text string) string {
  2150. re := regexp.MustCompile(`\([^)]*\)`)
  2151. return re.ReplaceAllString(text, "")
  2152. }
  2153. // IsChinese 判断传入的是否是汉字
  2154. func IsChinese(str string) bool {
  2155. for _, r := range str {
  2156. if unicode.Is(unicode.Han, r) {
  2157. return true
  2158. }
  2159. }
  2160. return false
  2161. }
  2162. // 判断是否是数字
  2163. func isNumber(str string) bool {
  2164. _, err := strconv.ParseFloat(str, 64)
  2165. return err == nil
  2166. }