12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456 |
- // @Author gmy 2024/8/6 10:50:00
- package liangyou
- import (
- "context"
- "encoding/json"
- "eta/eta_data_analysis/models"
- "eta/eta_data_analysis/utils"
- "fmt"
- "github.com/PuerkitoBio/goquery"
- "github.com/beego/beego/v2/core/logs"
- "github.com/chromedp/chromedp"
- "log"
- "regexp"
- "strconv"
- "strings"
- "unicode"
- )
- var (
- sourceName = "lysww" // 粮油商务网
- )
- // TableData 用于存储表格的数据
- type TableData struct {
- Headers []string `json:"headers"`
- Rows [][]string `json:"rows"`
- }
- // ImportCostProcessor
- // @Description: 进口成本处理器
- type ImportCostProcessor struct{}
- func (p *ImportCostProcessor) Process(ctx context.Context, product string, reportContent string, keywords []string, classifyId int) ([]models.BaseFromLyData, error) {
- logs.Info("Processing import cost...")
- // 解析关键字
- if len(keywords) < 5 {
- return []models.BaseFromLyData{}, fmt.Errorf("ProcessingImportCostProcessor Process() : keywords must contain at least 5 elements")
- }
- // 拿到 行关键字和列关键字
- columnName := keywords[len(keywords)-4]
- rowVariety := keywords[0]
- rowPort := keywords[len(keywords)-3]
- indexNamePrefix := keywords[:1]
- indexNameSuffix := keywords[1:]
- // 提取所有表格数据
- tableData := getNoHeadTableData(reportContent)
- // 提取日期信息
- dateText, err := getDateInfo(ctx)
- if err != nil {
- return []models.BaseFromLyData{}, err
- }
- // 时间格式转换
- format, err := utils.ConvertTimeFormat(dateText)
- if err != nil {
- return []models.BaseFromLyData{}, err
- }
- // 解析日期并计算当前月份
- var targetMonths []string
- if product == "油菜籽" {
- targetMonths, err = utils.ParseDateAndMonthColzaOil(format)
- } else {
- targetMonths, err = utils.ParseDateAndMonth(dateText)
- }
- if err != nil {
- return []models.BaseFromLyData{}, fmt.Errorf("ProcessingImportCostProcessor Process() : Failed to parse date: %v", err)
- }
- fmt.Printf("Target Month: %s\n", targetMonths)
- // 处理提取的表格数据
- var result []models.BaseFromLyData
- for _, data := range tableData {
- tableHeaders := data.Headers
- tableRows := data.Rows
- // 查找目标列
- columnIdx := -1
- for i, header := range tableHeaders {
- if strings.Contains(header, columnName) {
- columnIdx = i
- break
- }
- }
- if columnIdx == -1 {
- log.Printf("ProcessingImportCostProcessor Process() : Column '%s' not found in table", columnName)
- continue
- }
- // 处理表格中的每一行
- //var flag bool = true
- var previousRowVariety string
- var previousRowPort string
- for rowIndex, row := range tableRows {
- if len(row) == len(tableHeaders) {
- previousRowVariety = row[0]
- previousRowPort = row[1]
- } else if len(row) == len(tableHeaders)-1 {
- previousRowPort = row[0]
- row = append([]string{previousRowVariety}, row...)
- tableRows[rowIndex] = row
- } else if len(row) == len(tableHeaders)-2 {
- row = append([]string{previousRowVariety, previousRowPort}, row...)
- tableRows[rowIndex] = row
- }
- for _, targetMonth := range targetMonths {
- if len(row) >= len(tableHeaders) && strings.Contains(rowVariety, row[0]) && row[1] == targetMonth && row[len(row)-1] == rowPort {
- if columnIdx < len(row) {
- // 指标名称
- indexNameList := append(indexNamePrefix, append([]string{targetMonth}, indexNameSuffix...)...)
- indexName := strings.Join(indexNameList[:len(keywords)-2], ":")
- // 指标编码
- indexCode := utils.GenerateIndexCode(sourceName, indexName)
- // 指标id获取
- indexId, err := getIndexId(indexCode, indexName, classifyId, sourceName, keywords[len(keywords)-2], keywords[len(keywords)-1])
- if err != nil {
- logs.Error("ProcessingImportCostProcessor Process() : Failed to get index id: %v", err)
- continue
- }
- paramsLib := make(map[string]interface{})
- paramsLib["IndexId"] = indexId
- paramsLib["DataTime"] = format
- postEdbLib, err := httpRequestFill(paramsLib, utils.GET_LY_DATA_BY_INDEX_ID_AND_DATA_TIME)
- if err != nil {
- logs.Error("ProcessingImportCostProcessor Process() : Failed to get data by index id and date: %v", err)
- continue
- }
- var requestResponse models.RequestResponse[[]models.BaseFromLyData]
- err = json.Unmarshal(postEdbLib, &requestResponse)
- indexData := requestResponse.Data
- if len(indexData) > 0 {
- logs.Info("ProcessingImportCostProcessor Process() : Data already exists for index %d and date %s", indexId, dateText)
- continue
- }
- valueStr := row[columnIdx]
- value, err := strconv.ParseFloat(valueStr, 64)
- if err != nil {
- return []models.BaseFromLyData{}, fmt.Errorf("failed to parse value '%s': %v", valueStr, err)
- }
- // 创建并添加到结果列表
- baseFromLyData := models.BaseFromLyData{
- DataTime: format,
- Value: value,
- BaseFromLyIndexId: indexId,
- IndexCode: indexCode,
- }
- result = append(result, baseFromLyData)
- } else {
- log.Printf("ProcessingImportCostProcessor Process() : Column index out of range for row '%s', '%s'", rowVariety, rowPort)
- }
- break
- }
- }
- }
- }
- return result, nil
- }
- // ProcessingProfitProcessor
- // @Description: 加工利润处理器
- type ProcessingProfitProcessor struct{}
- func (p *ProcessingProfitProcessor) Process(ctx context.Context, product string, reportContent string, keywords []string, classifyId int) ([]models.BaseFromLyData, error) {
- fmt.Println("Processing processing profit...")
- // 解析关键字
- if len(keywords) < 4 {
- return []models.BaseFromLyData{}, fmt.Errorf("ProcessingProfitProcessor Process() : keywords must contain at least 4 elements")
- }
- // 拿到 行关键字和列关键字
- columnName := keywords[1]
- rowVariety := keywords[0]
- indexNamePrefix := keywords[:1]
- indexNameSuffix := keywords[1:]
- // 提取所有表格数据
- tableData := getNoHeadTableData(reportContent)
- // 提取日期信息
- dateText, err := getDateInfo(ctx)
- if err != nil {
- return []models.BaseFromLyData{}, err
- }
- // 时间格式转换
- format, err := utils.ConvertTimeFormat(dateText)
- if err != nil {
- return []models.BaseFromLyData{}, err
- }
- // 解析日期并计算当前月份 和 后两月
- yearMonths, err := utils.ConvertTimeFormatToYearMonth(format)
- if err != nil {
- return nil, err
- }
- fmt.Printf("Target yearMonth: %s\n", yearMonths)
- // 处理提取的表格数据
- var result []models.BaseFromLyData
- for _, data := range tableData {
- tableHeaders := data.Headers
- tableRows := data.Rows
- // 查找目标列
- columnIdx := -1
- for i, header := range tableHeaders {
- if strings.Contains(columnName, header) {
- columnIdx = i
- break
- }
- }
- if columnIdx == -1 {
- log.Printf("ProcessingProfitProcessor Process() : Column '%s' not found in table", columnName)
- continue
- }
- // 处理表格中的每一行
- var previousRowVariety string
- for rowIndex, row := range tableRows {
- if len(row) == len(tableHeaders) {
- previousRowVariety = row[0]
- } else if len(row) == len(tableHeaders)-1 {
- row = append([]string{previousRowVariety}, row...)
- tableRows[rowIndex] = row
- }
- for _, targetMonth := range yearMonths {
- if len(row) >= len(tableHeaders) && row[0] == rowVariety && row[1] == targetMonth {
- if columnIdx < len(row) {
- // 指标名称
- indexNameList := append(indexNamePrefix, append([]string{targetMonth}, indexNameSuffix...)...)
- indexName := strings.Join(indexNameList[:len(keywords)-1], ":")
- // 指标编码
- indexCode := utils.GenerateIndexCode(sourceName, indexName)
- // 指标id获取
- indexId, err := getIndexId(indexCode, indexName, classifyId, sourceName, keywords[len(keywords)-2], keywords[len(keywords)-1])
- if err != nil {
- logs.Error("ProcessingProfitProcessor Process() : Failed to get index id: %v", err)
- continue
- }
- paramsLib := make(map[string]interface{})
- paramsLib["IndexId"] = indexId
- paramsLib["DataTime"] = format
- postEdbLib, err := httpRequestFill(paramsLib, utils.GET_LY_DATA_BY_INDEX_ID_AND_DATA_TIME)
- if err != nil {
- logs.Error("ProcessingProfitProcessor Process() : Failed to get data by index id and date: %v", err)
- continue
- }
- var requestResponse models.RequestResponse[[]models.BaseFromLyData]
- err = json.Unmarshal(postEdbLib, &requestResponse)
- indexData := requestResponse.Data
- if len(indexData) > 0 {
- logs.Info("ProcessingProfitProcessor Process() : Data already exists for index %d and date %s", indexId, dateText)
- continue
- }
- valueStr := row[columnIdx]
- value, err := strconv.ParseFloat(valueStr, 64)
- if err != nil {
- return []models.BaseFromLyData{}, fmt.Errorf("failed to parse value '%s': %v", valueStr, err)
- }
- // 创建并添加到结果列表
- baseFromLyData := models.BaseFromLyData{
- DataTime: format,
- Value: value,
- BaseFromLyIndexId: indexId,
- IndexCode: indexCode,
- }
- result = append(result, baseFromLyData)
- } else {
- log.Printf("ProcessingProfitProcessor Process() : Column index out of range for row '%s', '%s'", rowVariety, columnName)
- }
- break
- }
- }
- }
- }
- return result, nil
- }
- // ShippingCostProcessor
- // @Description: 船运费用处理器
- type ShippingCostProcessor struct{}
- func (p *ShippingCostProcessor) Process(ctx context.Context, product string, reportContent string, keywords []string, classifyId int) ([]models.BaseFromLyData, error) {
- fmt.Println("Processing processing profit...")
- // 解析关键字
- if len(keywords) < 4 {
- return []models.BaseFromLyData{}, fmt.Errorf("ShippingCostProcessor Process() : keywords must contain at least 5 elements")
- }
- // 拿到 行关键字和列关键字
- columnName := keywords[len(keywords)-3]
- rowVariety := keywords[0]
- rowDestination := keywords[1]
- rowShipType := keywords[2]
- // 提取所有表格数据
- tableData := getNoHeadTableData(reportContent)
- // 提取日期信息
- dateText, err := getDateInfo(ctx)
- if err != nil {
- return []models.BaseFromLyData{}, err
- }
- // 时间格式转换
- format, err := utils.ConvertTimeFormat(dateText)
- if err != nil {
- return []models.BaseFromLyData{}, err
- }
- // 处理提取的表格数据
- var result []models.BaseFromLyData
- for _, data := range tableData {
- tableHeaders := data.Headers
- tableRows := data.Rows
- // 查找目标列
- columnIdx := -1
- for i, header := range tableHeaders {
- if strings.Contains(header, columnName) {
- columnIdx = i
- break
- }
- }
- if columnIdx == -1 {
- log.Printf("ShippingCostProcessor Process() : Column '%s' not found in table", columnName)
- continue
- }
- // 处理表格中的每一行
- for rowIndex, row := range tableRows {
- if len(row) == len(tableHeaders)-1 {
- row = append([]string{rowVariety}, row...)
- tableRows[rowIndex] = row
- rowShipType, err = extractValueInParentheses(rowVariety)
- if err != nil {
- logs.Error("ShippingCostProcessor Process() : Failed to extract value in parentheses: %v", err)
- continue
- }
- }
- if len(row) >= len(tableHeaders) && row[0] == rowVariety && (row[1] == rowDestination || strings.Contains(row[0], row[1])) && row[2] == rowShipType {
- if columnIdx < len(row) {
- // 指标名称
- indexName := strings.Join(keywords[:len(keywords)-3], `:`)
- // 指标编码
- indexCode := utils.GenerateIndexCode(sourceName, indexName)
- // 指标id获取
- indexId, err := getIndexId(indexCode, indexName, classifyId, sourceName, keywords[len(keywords)-2], keywords[len(keywords)-1])
- if err != nil {
- logs.Error("ShippingCostProcessor Process() : Failed to get index id: %v", err)
- continue
- }
- paramsLib := make(map[string]interface{})
- paramsLib["IndexId"] = indexId
- paramsLib["DataTime"] = format
- postEdbLib, err := httpRequestFill(paramsLib, utils.GET_LY_DATA_BY_INDEX_ID_AND_DATA_TIME)
- if err != nil {
- logs.Error("ShippingCostProcessor Process() : Failed to get data by index id and date: %v", err)
- continue
- }
- var requestResponse models.RequestResponse[[]models.BaseFromLyData]
- err = json.Unmarshal(postEdbLib, &requestResponse)
- indexData := requestResponse.Data
- if len(indexData) > 0 {
- logs.Info("ShippingCostProcessor Process() : Data already exists for index %d and date %s", indexId, dateText)
- continue
- }
- valueStr := row[columnIdx]
- value, err := strconv.ParseFloat(valueStr, 64)
- if err != nil {
- return []models.BaseFromLyData{}, fmt.Errorf("failed to parse value '%s': %v", valueStr, err)
- }
- // 创建并添加到结果列表
- baseFromLyData := models.BaseFromLyData{
- DataTime: format,
- Value: value,
- BaseFromLyIndexId: indexId,
- IndexCode: indexCode,
- }
- result = append(result, baseFromLyData)
- } else {
- log.Printf("ShippingCostProcessor Process() : Column index out of range for row '%s', '%s'", rowVariety, columnName)
- }
- break
- }
- }
- }
- return result, nil
- }
- // SupplyDemandBalanceProcessor
- // @Description: 供需平衡处理器
- type SupplyDemandBalanceProcessor struct{}
- func (p *SupplyDemandBalanceProcessor) Process(ctx context.Context, product string, reportContent string, keywords []string, classifyId int) ([]models.BaseFromLyData, error) {
- // https://www.fao.com.cn/art/gG7gKTCNDHLJNsq9QRYjoQ==.htm
- logs.Info("Processing processing report...")
- // 解析关键字
- if len(keywords) < 4 {
- return []models.BaseFromLyData{}, fmt.Errorf("SupplyDemandBalanceProcessor Process() : keywords must contain at least 4 elements")
- }
- // 拿到 行关键字和列关键字
- var columnName string
- rowVariety := keywords[1]
- // 提取所有表格数据
- tableData := getTableData(reportContent, true)
- logs.Info("SupplyDemandBalanceProcessor Process() : Table data: %v", tableData)
- // 提取日期信息
- dateText, err := getDateInfo(ctx)
- if err != nil {
- return []models.BaseFromLyData{}, err
- }
- // 时间格式转换
- format, err := utils.ConvertTimeFormat(dateText)
- if err != nil {
- return []models.BaseFromLyData{}, err
- }
- currentYearAndNextYear, err := utils.GetCurrentYearAndNextYear(format)
- if err != nil {
- return nil, err
- }
- month, err := utils.GetCurrentMonth(format)
- if err != nil {
- return nil, err
- }
- monthSuffix := "预估"
- logs.Info("SupplyDemandBalanceProcessor Process() : Target Year: %s:%s\n", currentYearAndNextYear, month+monthSuffix)
- // 处理提取的表格数据
- var result []models.BaseFromLyData
- headers := tableData.Headers
- rows := tableData.Rows
- for _, year := range currentYearAndNextYear {
- columnName = year + month + monthSuffix
- isCurrentYear, err := utils.IsCurrentYear(year)
- if err != nil {
- logs.Error("SupplyDemandBalanceProcessor Process() : Failed to determine if year is current year: %v", err)
- continue
- }
- if !isCurrentYear {
- format, err = utils.GetNextYearLastDay(format)
- if err != nil {
- logs.Error("SupplyDemandBalanceProcessor Process() : Failed to get next year last day: %v", err)
- continue
- }
- }
- // 查找目标列
- columnIdx := -1
- for i, header := range headers {
- if strings.Contains(columnName, header) {
- columnIdx = i
- break
- }
- }
- if columnIdx == -1 {
- logs.Error("SupplyDemandBalanceProcessor Process() : Column '%s' not found in table", columnName)
- continue
- }
- // 处理表格中的每一行
- for _, row := range rows {
- if len(row) >= len(headers) && row[0] == rowVariety {
- if columnIdx < len(row) {
- // 指标名称
- indexName := strings.Join(keywords[:len(keywords)-2], ":")
- // 指标编码
- indexCode := utils.GenerateIndexCode(sourceName, indexName)
- // 指标id获取
- indexId, err := getIndexId(indexCode, indexName, classifyId, sourceName, keywords[len(keywords)-2], keywords[len(keywords)-1])
- if err != nil {
- logs.Error("SupplyDemandBalanceProcessor Process() : Failed to get index id: %v", err)
- continue
- }
- valueStr := row[columnIdx]
- value, err := strconv.ParseFloat(valueStr, 64)
- if err != nil {
- return []models.BaseFromLyData{}, fmt.Errorf("SupplyDemandBalanceProcessor Process() : failed to parse value '%s': %v", valueStr, err)
- }
- yearMonth, err := utils.GetYearMonth(format)
- if err != nil {
- logs.Error("SupplyDemandBalanceProcessor Process() : Failed to get year month: %v", err)
- continue
- }
- paramsLib := make(map[string]interface{})
- paramsLib["IndexId"] = indexId
- paramsLib["YearMonth"] = format
- postEdbLib, err := httpRequestFill(paramsLib, utils.GET_LY_DATA_BY_INDEX_ID_AND_DATA_TIME_YM)
- if err != nil {
- logs.Error("SupplyDemandBalanceProcessor Process() : Failed to get data by index id and date: %v", err)
- continue
- }
- var requestResponse models.RequestResponse[[]models.BaseFromLyData]
- err = json.Unmarshal(postEdbLib, &requestResponse)
- indexData := requestResponse.Data
- if len(indexData) > 0 {
- logs.Info("SupplyDemandBalanceProcessor Process() : Data already exists for index %d and date %s", indexId, dateText)
- // 存在走更新逻辑 主要更新今年在去年的预估值
- indexData := indexData[0]
- if indexData.Value != value {
- time, err := utils.StringToTime(indexData.ModifyTime)
- if err != nil {
- return nil, err
- }
- timeZero, err := utils.StringToTimeZero(format)
- if err != nil {
- return nil, err
- }
- if time.Before(timeZero) {
- // 更新指标数据
- paramsLib := make(map[string]interface{})
- paramsLib["Id"] = indexData.BaseFromLyDataId
- paramsLib["Value"] = value
- _, err := httpRequestFill(paramsLib, utils.UPDATE_LY_DATA_BY_ID)
- if err != nil {
- return nil, fmt.Errorf("SupplyDemandBalanceProcessor Process() : failed to parse value '%s': %v", valueStr, err)
- }
- // 更新指标库数据
- paramsLib = make(map[string]interface{})
- paramsLib["IndexCode"] = indexData.IndexCode
- paramsLib["DataTime"] = yearMonth
- postEdbLib, err := httpRequestFill(paramsLib, utils.GET_LY_EDB_DATA_BY_INDEX_CODE_AND_DATA_TIME)
- if err != nil {
- logs.Error("SupplyDemandBalanceProcessor Process() : Failed to get data by index id and date: %v", err)
- continue
- }
- var requestResponse models.RequestResponse[[]models.EdbDataLy]
- err = json.Unmarshal(postEdbLib, &requestResponse)
- if err != nil {
- return nil, err
- }
- edbIndexData := requestResponse.Data
- if len(edbIndexData) > 0 {
- paramsLib := make(map[string]interface{})
- paramsLib["Id"] = edbIndexData[0].EdbInfoId
- paramsLib["Value"] = value
- _, err := httpRequestFill(paramsLib, utils.UPDATE_LY_EDB_DATA_BY_ID)
- if err != nil {
- return nil, fmt.Errorf("SupplyDemandBalanceProcessor Process() : failed to parse value '%s': %v", valueStr, err)
- }
- }
- }
- }
- continue
- }
- // 创建并添加到结果列表
- baseFromLyData := models.BaseFromLyData{
- DataTime: format,
- Value: value,
- BaseFromLyIndexId: indexId,
- IndexCode: indexCode,
- }
- result = append(result, baseFromLyData)
- } else {
- log.Printf("SupplyDemandBalanceProcessor Process() : Column index out of range for row '%s', '%s'", rowVariety, columnName)
- }
- break
- }
- }
- }
- return result, nil
- }
- // PurchaseShippingProcessor
- // @Description: 采购装船处理器
- type PurchaseShippingProcessor struct{}
- func (p *PurchaseShippingProcessor) Process(ctx context.Context, product string, reportContent string, keywords []string, classifyId int) ([]models.BaseFromLyData, error) {
- logs.Info("Processing purchase shipping...")
- // 解析关键字
- if len(keywords) < 3 {
- return []models.BaseFromLyData{}, fmt.Errorf("SupplyDemandBalanceProcessor Process() : keywords must contain at least 3 elements")
- }
- // 拿到 行关键字和列关键字
- columnName := keywords[len(keywords)-3]
- // 提取所有表格数据
- tableData := getPurchaseShippingTableData(reportContent)
- logs.Info("SupplyDemandBalanceProcessor Process() : Table data: %v", tableData)
- // 提取日期信息
- dateText, err := getDateInfo(ctx)
- if err != nil {
- return []models.BaseFromLyData{}, err
- }
- // 时间格式转换
- format, err := utils.ConvertTimeFormat(dateText)
- if err != nil {
- return []models.BaseFromLyData{}, err
- }
- // 处理提取的表格数据
- var result []models.BaseFromLyData
- headers := tableData.Headers
- rows := tableData.Rows
- // 查找目标列
- columnIdx := -1
- for i, header := range headers {
- if strings.Contains(columnName, header) {
- columnIdx = i
- break
- }
- }
- if columnIdx == -1 {
- log.Printf("SupplyDemandBalanceProcessor Process() : Column '%s' not found in table", columnName)
- } else {
- // 处理表格中的每一行
- for _, row := range rows {
- if len(row) >= len(headers) {
- if columnIdx < len(row) {
- if !isNumber(row[columnIdx]) {
- continue
- }
- // 指标名称
- indexName := strings.Join(keywords[:len(keywords)-3], ":")
- // 指标编码
- indexCode := utils.GenerateIndexCode(sourceName, indexName)
- // 指标id获取
- indexId, err := getIndexId(indexCode, indexName, classifyId, sourceName, keywords[len(keywords)-2], keywords[len(keywords)-1])
- if err != nil {
- logs.Error("SupplyDemandBalanceProcessor Process() : Failed to get index id: %v", err)
- continue
- }
- var yearMonth string
- number, err := utils.ConvertMonthToNumber(row[1])
- if err != nil {
- return nil, err
- }
- yearMonth = row[0] + "-" + number
- isSameMonth, err := utils.IsSameMonth(format, yearMonth)
- if err != nil {
- return nil, err
- }
- if isSameMonth {
- yearMonth = format
- } else {
- lastDayOfMonth, err := utils.GetLastDayOfMonth(yearMonth)
- if err != nil {
- return nil, err
- }
- yearMonth = lastDayOfMonth
- }
- valueStr := row[columnIdx]
- value, err := strconv.ParseFloat(valueStr, 64)
- if err != nil {
- return []models.BaseFromLyData{}, fmt.Errorf("SupplyDemandBalanceProcessor Process() : failed to parse value '%s': %v", valueStr, err)
- }
- month, err := utils.GetYearMonth(yearMonth)
- if err != nil {
- return nil, err
- }
- paramsLib := make(map[string]interface{})
- paramsLib["IndexId"] = indexId
- paramsLib["YearMonth"] = month
- postEdbLib, err := httpRequestFill(paramsLib, utils.GET_LY_DATA_BY_INDEX_ID_AND_DATA_TIME_YM)
- if err != nil {
- logs.Error("SupplyDemandBalanceProcessor Process() : Failed to get data by index id and date: %v", err)
- continue
- }
- var requestResponse models.RequestResponse[[]models.BaseFromLyData]
- err = json.Unmarshal(postEdbLib, &requestResponse)
- indexData := requestResponse.Data
- if len(indexData) > 0 {
- if indexData[0].Value != value {
- logs.Info("SupplyDemandBalanceProcessor Process() : Data already exists for index %d and date %s", indexId, dateText)
- lyData := indexData[0]
- time, err := utils.StringToTime(lyData.ModifyTime)
- if err != nil {
- return nil, err
- }
- timeZero, err := utils.StringToTimeZero(format)
- if err != nil {
- return nil, err
- }
- if time.Before(timeZero) {
- // 更新指标数据
- paramsLib := make(map[string]interface{})
- paramsLib["Id"] = lyData.BaseFromLyDataId
- paramsLib["Value"] = value
- _, err := httpRequestFill(paramsLib, utils.UPDATE_LY_DATA_BY_ID)
- if err != nil {
- return nil, fmt.Errorf("SupplyDemandBalanceProcessor Process() : failed to parse value '%s': %v", valueStr, err)
- }
- // 同步更新指标库数据 须根据指标编码和日期更新
- paramsLib = make(map[string]interface{})
- paramsLib["IndexCode"] = lyData.IndexCode
- paramsLib["DataTime"] = yearMonth
- postEdbLib, err := httpRequestFill(paramsLib, utils.GET_LY_EDB_DATA_BY_INDEX_CODE_AND_DATA_TIME)
- if err != nil {
- logs.Error("SupplyDemandBalanceProcessor Process() : Failed to get data by index id and date: %v", err)
- continue
- }
- var requestResponse models.RequestResponse[[]models.EdbDataLy]
- err = json.Unmarshal(postEdbLib, &requestResponse)
- edbIndexData := requestResponse.Data
- if err != nil {
- return nil, err
- }
- if len(edbIndexData) > 0 {
- paramsLib := make(map[string]interface{})
- paramsLib["Id"] = edbIndexData[0].EdbInfoId
- paramsLib["Value"] = value
- _, err := httpRequestFill(paramsLib, utils.UPDATE_LY_EDB_DATA_BY_ID)
- if err != nil {
- return nil, fmt.Errorf("SupplyDemandBalanceProcessor Process() : failed to parse value '%s': %v", valueStr, err)
- }
- }
- }
- }
- continue
- }
- // 创建并添加到结果列表
- baseFromLyData := models.BaseFromLyData{
- DataTime: yearMonth,
- Value: value,
- BaseFromLyIndexId: indexId,
- IndexCode: indexCode,
- }
- result = append(result, baseFromLyData)
- continue
- } else {
- log.Printf("SupplyDemandBalanceProcessor Process() : Column index out of range for row '%s'", columnName)
- }
- break
- }
- }
- }
- return result, nil
- }
- // ProcessingReportProcessor
- // @Description: 加工报告处理器
- type ProcessingReportProcessor struct {
- }
- func (p *ProcessingReportProcessor) Process(ctx context.Context, product string, reportContent string, keywords []string, classifyId int) ([]models.BaseFromLyData, error) {
- logs.Info("Processing processing report...")
- // 解析关键字
- if len(keywords) < 3 {
- return []models.BaseFromLyData{}, fmt.Errorf("ProcessingReportProcessor Process() : keywords must contain at least 3 elements")
- }
- // 拿到 行关键字和列关键字
- columnName := keywords[0]
- rowName := keywords[1]
- // 提取所有表格数据
- tableData := getAllTableData(reportContent)
- // 提取日期信息
- dateText, err := getDateInfo(ctx)
- if err != nil {
- return []models.BaseFromLyData{}, err
- }
- indexName := strings.Join(keywords[:len(keywords)-2], ":")
- // 指标编码
- indexCode := utils.GenerateIndexCode(sourceName, indexName)
- // 指标id获取
- indexId, err := getIndexId(indexCode, indexName, classifyId, sourceName, keywords[len(keywords)-2], keywords[len(keywords)-1])
- if err != nil {
- return nil, err
- }
- // 校验指标数据是否存在 根据指标id和日期 存在则跳过,不存在正常往下走
- format, err := utils.ConvertTimeFormat(dateText)
- if err != nil {
- return []models.BaseFromLyData{}, err
- }
- paramsLib := make(map[string]interface{})
- paramsLib["IndexId"] = indexId
- paramsLib["DataTime"] = format
- postEdbLib, err := httpRequestFill(paramsLib, utils.GET_LY_DATA_BY_INDEX_ID_AND_DATA_TIME)
- if err != nil {
- return []models.BaseFromLyData{}, fmt.Errorf("ProcessingReportProcessor Process() : Failed to get data by index id and date: %v", err)
- }
- var requestResponse models.RequestResponse[[]models.BaseFromLyData]
- err = json.Unmarshal(postEdbLib, &requestResponse)
- indexData := requestResponse.Data
- if len(indexData) > 0 {
- logs.Info("ProcessingReportProcessor Process() : Data already exists for index %d and date %s", indexId, dateText)
- // 不必做更新处理,报告每周刷新,即使本周和上周数据一致,也需要每周记录
- return []models.BaseFromLyData{}, nil
- }
- // 解析日期并计算当前周数
- targetWeek, err := utils.ParseDateAndWeek(dateText)
- if err != nil {
- return []models.BaseFromLyData{}, fmt.Errorf("ProcessingReportProcessor Process() : Failed to parse date: %v", err)
- }
- fmt.Printf("Target Week: %s\n", targetWeek)
- var result []models.BaseFromLyData
- // 处理提取的表格数据
- for _, data := range tableData {
- tableHeaders := data.Headers
- tableRows := data.Rows
- // 查找目标列
- columnIdx := -1
- for i, header := range tableHeaders {
- headerString := extractChinese(header)
- if strings.Contains(columnName, headerString) {
- // 这个表格不是很好处理,这里写的有些僵硬,后续需要优化
- if columnName == "国内大豆开机率" {
- i = i + 2
- }
- columnIdx = i
- break
- }
- }
- if columnIdx == -1 {
- logs.Error("ProcessingReportProcessor Process() : Column '%s' not found in table", columnName)
- continue
- }
- // 查找本周的列位置
- weekIdx := -1
- for i, header := range tableHeaders {
- if strings.Contains(header, targetWeek) && i > columnIdx {
- weekIdx = i
- break
- }
- }
- if weekIdx == -1 {
- fmt.Printf("Week column '%s' not found in table\n", targetWeek)
- continue
- }
- // 查找目标行
- for _, row := range tableRows {
- if strings.Contains(row[0], rowName) {
- if columnIdx < len(row) {
- // 指标名称
- indexName := strings.Join(keywords[:len(keywords)-2], ":")
- // 指标编码
- indexCode := utils.GenerateIndexCode(sourceName, indexName)
- // 指标id获取
- indexId, err := getIndexId(indexCode, indexName, classifyId, sourceName, keywords[len(keywords)-2], keywords[len(keywords)-1])
- if err != nil {
- logs.Error("ProcessingReportProcessor Process() : Failed to get index id: %v", err)
- continue
- }
- paramsLib := make(map[string]interface{})
- paramsLib["IndexId"] = indexId
- paramsLib["DataTime"] = format
- postEdbLib, err := httpRequestFill(paramsLib, utils.GET_LY_DATA_BY_INDEX_ID_AND_DATA_TIME)
- if err != nil {
- logs.Error("ProcessingReportProcessor Process() : Failed to get data by index id and date: %v", err)
- continue
- }
- var requestResponse models.RequestResponse[[]models.BaseFromLyData]
- err = json.Unmarshal(postEdbLib, &requestResponse)
- indexData := requestResponse.Data
- if len(indexData) > 0 {
- logs.Info("ProcessingReportProcessor Process() : Data already exists for index %d and date %s", indexId, dateText)
- // 无需走更新逻辑,报告每日更新,即使今天和昨天数据一致,也需要每天记录,如果到这里也只是说,今天这个报告被读取了两次
- continue
- }
- valueStr := row[columnIdx]
- value, err := strconv.ParseFloat(valueStr, 64)
- if err != nil {
- return []models.BaseFromLyData{}, fmt.Errorf("ProcessingReportProcessor Process() : failed to parse value '%s': %v", valueStr, err)
- }
- // 创建并添加到结果列表
- baseFromLyData := models.BaseFromLyData{
- DataTime: format,
- Value: value,
- BaseFromLyIndexId: indexId,
- IndexCode: indexCode,
- }
- result = append(result, baseFromLyData)
- continue
- } else {
- log.Printf("ProcessingReportProcessor Process() : Column index out of range for row '%s', '%s'", rowName, columnName)
- }
- break
- }
- /*if len(row) > 0 && strings.Contains(row[0], rowName) {
- if weekIdx < len(row) {
- logs.Info("Value in column '%s' - '%s': %s", columnName, rowName, row[columnIdx])
- numFlag := isNumeric(row[columnIdx])
- if numFlag {
- value, err := strconv.ParseFloat(row[columnIdx], 64)
- if err != nil {
- logs.Error("ProcessingReportProcessor Process() : Error converting value to float64: %v", err)
- return []models.BaseFromLyData{}, err
- }
- // 返回BaseFromLyData对象的数据
- baseFromLyData := models.BaseFromLyData{
- DataTime: dateText,
- Value: value,
- }
- result = append(result, baseFromLyData)
- }
- } else {
- logs.Error("ProcessingReportProcessor Process() : Column index out of range")
- }
- }*/
- }
- }
- return result, nil
- }
- // InventoryAnalysisProcessor
- // @Description: 库存分析处理器
- type InventoryAnalysisProcessor struct{}
- func (p *InventoryAnalysisProcessor) Process(ctx context.Context, product string, reportContent string, keywords []string, classifyId int) ([]models.BaseFromLyData, error) {
- // https://www.fao.com.cn/art/yg1IKj9FpPEIDv2LefnPhQ==.htm
- logs.Info("Processing inventory analysis...")
- // 解析关键字
- if len(keywords) < 4 {
- return []models.BaseFromLyData{}, fmt.Errorf("SupplyDemandBalanceProcessor Process() : keywords must contain at least 4 elements")
- }
- // 拿到 行关键字和列关键字
- columnName := keywords[0]
- rowVariety := keywords[1]
- columnSuffix := "本周"
- columnName = columnName + columnSuffix
- // 提取所有表格数据
- tableData := getTableData(reportContent, true)
- logs.Info("SupplyDemandBalanceProcessor Process() : Table data: %v", tableData)
- // 提取日期信息
- dateText, err := getDateInfo(ctx)
- if err != nil {
- return []models.BaseFromLyData{}, err
- }
- // 时间格式转换
- format, err := utils.ConvertTimeFormat(dateText)
- if err != nil {
- return []models.BaseFromLyData{}, err
- }
- // 处理提取的表格数据
- var result []models.BaseFromLyData
- headers := tableData.Headers
- rows := tableData.Rows
- // 查找目标列
- columnIdx := -1
- for i, header := range headers {
- header := removeParentheses(header)
- if strings.Contains(columnName, header) {
- columnIdx = i
- break
- }
- }
- if columnIdx == -1 {
- logs.Error("SupplyDemandBalanceProcessor Process() : Column '%s' not found in table", columnName)
- } else {
- // 处理表格中的每一行
- for _, row := range rows {
- if len(row) >= len(headers) && strings.Contains(row[0], rowVariety) {
- if columnIdx < len(row) {
- // 指标名称
- indexName := strings.Join(keywords[:len(keywords)-2], ":")
- indexName = removeParentheses(indexName)
- // 指标编码
- indexCode := utils.GenerateIndexCode(sourceName, indexName)
- // 指标id获取
- indexId, err := getIndexId(indexCode, indexName, classifyId, sourceName, keywords[len(keywords)-2], keywords[len(keywords)-1])
- if err != nil {
- logs.Error("SupplyDemandBalanceProcessor Process() : Failed to get index id: %v", err)
- continue
- }
- paramsLib := make(map[string]interface{})
- paramsLib["IndexId"] = indexId
- paramsLib["DataTime"] = format
- postEdbLib, err := httpRequestFill(paramsLib, utils.GET_LY_DATA_BY_INDEX_ID_AND_DATA_TIME)
- if err != nil {
- logs.Error("SupplyDemandBalanceProcessor Process() : Failed to get data by index id and date: %v", err)
- continue
- }
- var requestResponse models.RequestResponse[[]models.BaseFromLyData]
- err = json.Unmarshal(postEdbLib, &requestResponse)
- indexData := requestResponse.Data
- if len(indexData) > 0 {
- logs.Info("SupplyDemandBalanceProcessor Process() : Data already exists for index %d and date %s", indexId, dateText)
- // 无需走更新逻辑,报告每周更新,即使本周和上周数据一致,也需要每周记录,如果到这里也只是说,今天这个报告被读取了两次
- continue
- }
- valueStr := row[columnIdx]
- value, err := strconv.ParseFloat(valueStr, 64)
- if err != nil {
- return []models.BaseFromLyData{}, fmt.Errorf("SupplyDemandBalanceProcessor Process() : failed to parse value '%s': %v", valueStr, err)
- }
- // 创建并添加到结果列表
- baseFromLyData := models.BaseFromLyData{
- DataTime: format,
- Value: value,
- BaseFromLyIndexId: indexId,
- IndexCode: indexCode,
- }
- result = append(result, baseFromLyData)
- continue
- } else {
- log.Printf("SupplyDemandBalanceProcessor Process() : Column index out of range for row '%s', '%s'", rowVariety, columnName)
- }
- break
- }
- }
- }
- return result, nil
- }
- // PriceSpreadArbitrageProcessor
- // @Description: 价差套利处理器
- type PriceSpreadArbitrageProcessor struct{}
- func (p *PriceSpreadArbitrageProcessor) Process(ctx context.Context, product string, reportContent string, keywords []string, classifyId int) ([]models.BaseFromLyData, error) {
- fmt.Println("Processing processing profit...")
- // 解析关键字
- if len(keywords) < 4 {
- return []models.BaseFromLyData{}, fmt.Errorf("ProcessingProfitProcessor Process() : keywords must contain at least 4 elements")
- }
- // 拿到 行关键字和列关键字
- var columnDate string
- rowVariety := keywords[0]
- rowBourse := keywords[1]
- // 提取所有表格数据
- tableData := getNoHeadTableData(reportContent)
- // 提取日期信息
- dateText, err := getDateInfo(ctx)
- if err != nil {
- return []models.BaseFromLyData{}, err
- }
- // 时间格式转换
- format, err := utils.ConvertTimeFormat(dateText)
- if err != nil {
- return []models.BaseFromLyData{}, err
- }
- day, err := utils.ConvertTimeFormatToYearMonthDay(format)
- if err != nil {
- return nil, err
- }
- columnDate = day
- // 处理提取的表格数据
- var result []models.BaseFromLyData
- for _, data := range tableData {
- tableHeaders := data.Headers
- tableRows := data.Rows
- // 查找目标列
- columnIdx := -1
- for i, header := range tableHeaders {
- if strings.Contains(header, columnDate) {
- columnIdx = i
- break
- }
- }
- if columnIdx == -1 {
- log.Printf("ProcessingProfitProcessor Process() : Column '%s' not found in table", columnDate)
- continue
- }
- // 处理表格中的每一行
- for _, row := range tableRows {
- if len(row) >= len(tableHeaders) && row[0] == rowVariety && row[1] == rowBourse {
- if columnIdx < len(row) {
- // 指标名称
- indexName := strings.Join(keywords[:len(keywords)-2], ":")
- // 指标编码
- indexCode := utils.GenerateIndexCode(sourceName, indexName)
- // 指标id获取
- indexId, err := getIndexId(indexCode, indexName, classifyId, sourceName, keywords[len(keywords)-2], keywords[len(keywords)-1])
- if err != nil {
- logs.Error("ProcessingProfitProcessor Process() : Failed to get index id: %v", err)
- continue
- }
- paramsLib := make(map[string]interface{})
- paramsLib["IndexId"] = indexId
- paramsLib["DataTime"] = format
- postEdbLib, err := httpRequestFill(paramsLib, utils.GET_LY_DATA_BY_INDEX_ID_AND_DATA_TIME)
- if err != nil {
- logs.Error("ProcessingProfitProcessor Process() : Failed to get data by index id and date: %v", err)
- continue
- }
- var requestResponse models.RequestResponse[[]models.BaseFromLyData]
- err = json.Unmarshal(postEdbLib, &requestResponse)
- indexData := requestResponse.Data
- if len(indexData) > 0 {
- logs.Info("ProcessingProfitProcessor Process() : Data already exists for index %d and date %s", indexId, dateText)
- // 无需走更新逻辑,报告每天更新,即使今天和每天数据一致,也需要每天记录,如果到这里也只是说,今天这个报告被读取了两次
- continue
- }
- valueStr := row[columnIdx]
- value, err := strconv.ParseFloat(valueStr, 64)
- if err != nil {
- return []models.BaseFromLyData{}, fmt.Errorf("failed to parse value '%s': %v", valueStr, err)
- }
- // 创建并添加到结果列表
- baseFromLyData := models.BaseFromLyData{
- DataTime: format,
- Value: value,
- BaseFromLyIndexId: indexId,
- IndexCode: indexCode,
- }
- result = append(result, baseFromLyData)
- } else {
- log.Printf("ProcessingProfitProcessor Process() : Column index out of range for row '%s', '%s'", rowVariety, columnDate)
- }
- break
- }
- }
- }
- return result, nil
- }
- // DailyTransactionProcessor
- // @Description: 每日成交处理器
- type DailyTransactionProcessor struct{}
- func (p *DailyTransactionProcessor) Process(ctx context.Context, product string, reportContent string, keywords []string, classifyId int) ([]models.BaseFromLyData, error) {
- fmt.Println("Processing processing profit...")
- // 解析关键字
- if len(keywords) < 4 {
- return []models.BaseFromLyData{}, fmt.Errorf("DailyTransactionProcessor Process() : keywords must contain at least 4 elements")
- }
- // 获取第一个表格
- areaTableDataList := getNoHeadTableData(reportContent)
- if len(areaTableDataList) == 0 {
- return []models.BaseFromLyData{}, fmt.Errorf("DailyTransactionProcessor Process() : No table data found")
- }
- areaTableData := areaTableDataList[0]
- // 获取第二个表格
- blocTableData := getTableData(reportContent, false)
- if blocTableData.Headers == nil {
- return []models.BaseFromLyData{}, fmt.Errorf("DailyTransactionProcessor Process() : No table data found")
- }
- logs.Info("SupplyDemandBalanceProcessor Process() : areaTableData data: %v, blocTableData data: %v", areaTableData, blocTableData)
- // 提取日期信息
- dateText, err := getDateInfo(ctx)
- if err != nil {
- return []models.BaseFromLyData{}, err
- }
- // 时间格式转换
- format, err := utils.ConvertTimeFormat(dateText)
- if err != nil {
- return []models.BaseFromLyData{}, err
- }
- // 处理提取的表格数据
- var result []models.BaseFromLyData
- areaHeaders := areaTableData.Headers
- areaRows := areaTableData.Rows
- // 第一个表格
- // 拿到 行关键字和列关键字
- columnArea := keywords[1]
- var rowAreaMonthDays []string
- rowWeek := "地区总计"
- monthDay, err := utils.GetWeekdaysInSameWeek(format)
- if err != nil {
- return nil, err
- }
- rowAreaMonthDays = monthDay
- // 查找目标列
- areaColumnIdx := -1
- for i, header := range areaHeaders {
- if strings.Contains(header, columnArea) {
- areaColumnIdx = i
- break
- }
- }
- if areaColumnIdx == -1 {
- log.Printf("DailyTransactionProcessor Process() : One Column '%s' not found in table", columnArea)
- } else if !strings.Contains(strings.Join(keywords[:len(keywords)-3], ":"), "主要集团") {
- for _, row := range areaRows {
- if len(row) >= len(areaHeaders) && row[0] == rowWeek {
- if areaColumnIdx < len(row) {
- // 指标名称
- indexName := strings.Join(keywords[:len(keywords)-3], ":")
- // 指标编码
- indexCode := utils.GenerateIndexCode(sourceName, indexName)
- // 指标id获取
- indexId, err := getIndexId(indexCode, indexName, classifyId, sourceName, keywords[len(keywords)-2], keywords[len(keywords)-1])
- if err != nil {
- logs.Error("DailyTransactionProcessor Process() : Failed to get index id: %v", err)
- continue
- }
- paramsLib := make(map[string]interface{})
- paramsLib["IndexId"] = indexId
- paramsLib["DataTime"] = format
- postEdbLib, err := httpRequestFill(paramsLib, utils.GET_LY_DATA_BY_INDEX_ID_AND_DATA_TIME)
- if err != nil {
- logs.Error("DailyTransactionProcessor Process() : Failed to get data by index id and date: %v", err)
- continue
- }
- var requestResponse models.RequestResponse[[]models.BaseFromLyData]
- err = json.Unmarshal(postEdbLib, &requestResponse)
- indexData := requestResponse.Data
- if len(indexData) > 0 {
- logs.Info("DailyTransactionProcessor Process() : Data already exists for index %d and date %s", indexId, dateText)
- // 无需走更新逻辑,报告每周更新,一周出来一周中每天得数据,即使本周和上周数据一致,也需要每天记录,如果到这里也只是说,今天这个报告被读取了两次
- continue
- }
- valueStr := row[areaColumnIdx]
- isChinese := IsChinese(valueStr)
- if isChinese {
- continue
- }
- value, err := strconv.ParseFloat(valueStr, 64)
- if err != nil {
- return []models.BaseFromLyData{}, fmt.Errorf("failed to parse value '%s': %v", valueStr, err)
- }
- // 创建并添加到结果列表
- var dealDate string
- if row[0] == rowWeek {
- dealDate = format
- } else {
- date, err := utils.ConvertToDate(row[0])
- if err != nil {
- return nil, err
- }
- dealDate = date
- }
- baseFromLyData := models.BaseFromLyData{
- DataTime: dealDate,
- Value: value,
- BaseFromLyIndexId: indexId,
- IndexCode: indexCode,
- }
- result = append(result, baseFromLyData)
- } else {
- log.Printf("DailyTransactionProcessor Process() : Column index out of range for row '%s', '%s'", monthDay, columnArea)
- }
- break
- } else {
- for _, monthDay := range rowAreaMonthDays {
- if len(row) >= len(areaHeaders) && (row[0] == monthDay && !strings.Contains(strings.Join(keywords[:len(keywords)-3], ":"), "周度")) {
- if areaColumnIdx < len(row) {
- // 指标名称
- indexName := strings.Join(keywords[:len(keywords)-3], ":")
- // 指标编码
- indexCode := utils.GenerateIndexCode(sourceName, indexName)
- // 指标id获取
- indexId, err := getIndexId(indexCode, indexName, classifyId, sourceName, keywords[len(keywords)-2], keywords[len(keywords)-1])
- if err != nil {
- logs.Error("DailyTransactionProcessor Process() : Failed to get index id: %v", err)
- continue
- }
- paramsLib := make(map[string]interface{})
- paramsLib["IndexId"] = indexId
- paramsLib["DataTime"] = format
- postEdbLib, err := httpRequestFill(paramsLib, utils.GET_LY_DATA_BY_INDEX_ID_AND_DATA_TIME)
- if err != nil {
- logs.Error("DailyTransactionProcessor Process() : Failed to get data by index id and date: %v", err)
- continue
- }
- var requestResponse models.RequestResponse[[]models.BaseFromLyData]
- err = json.Unmarshal(postEdbLib, &requestResponse)
- indexData := requestResponse.Data
- if len(indexData) > 0 {
- logs.Info("DailyTransactionProcessor Process() : Data already exists for index %d and date %s", indexId, dateText)
- // 无需走更新逻辑,报告每周更新,即使本周和上周数据一致,也需要每周记录,如果到这里也只是说,今天这个报告被读取了两次
- continue
- }
- valueStr := row[areaColumnIdx]
- isChinese := IsChinese(valueStr)
- if isChinese {
- continue
- }
- value, err := strconv.ParseFloat(valueStr, 64)
- if err != nil {
- return []models.BaseFromLyData{}, fmt.Errorf("failed to parse value '%s': %v", valueStr, err)
- }
- // 创建并添加到结果列表
- var dealDate string
- if row[0] == rowWeek {
- dealDate = format
- } else {
- date, err := utils.ConvertToDate(row[0])
- if err != nil {
- return nil, err
- }
- dealDate = date
- }
- baseFromLyData := models.BaseFromLyData{
- DataTime: dealDate,
- Value: value,
- BaseFromLyIndexId: indexId,
- IndexCode: indexCode,
- }
- result = append(result, baseFromLyData)
- } else {
- log.Printf("DailyTransactionProcessor Process() : Column index out of range for row '%s', '%s'", monthDay, columnArea)
- }
- break
- }
- }
- }
- }
- }
- // 第二个表格
- // 拿到 行关键字和列关键字
- columnBloc := keywords[len(keywords)-3]
- rowBloc := keywords[1]
- blocHeaders := blocTableData.Headers
- blocRows := blocTableData.Rows
- // 查找目标列
- blocColumnIdx := -1
- for i, header := range blocHeaders {
- if strings.Contains(header, columnBloc) {
- blocColumnIdx = i
- break
- }
- }
- if blocColumnIdx == -1 {
- log.Printf("DailyTransactionProcessor Process() : Two Column '%s' not found in table", columnBloc)
- } else {
- // 处理表格中的每一行
- for _, row := range blocRows {
- if len(row) >= len(blocHeaders) && strings.Contains(row[0], rowBloc) {
- if blocColumnIdx < len(row) {
- // 指标名称
- indexName := strings.Join(keywords[:len(keywords)-3], ":")
- indexName = removeParentheses(indexName)
- // 指标编码
- indexCode := utils.GenerateIndexCode(sourceName, indexName)
- // 指标id获取
- indexId, err := getIndexId(indexCode, indexName, classifyId, sourceName, keywords[len(keywords)-2], keywords[len(keywords)-1])
- if err != nil {
- logs.Error("SupplyDemandBalanceProcessor Process() : Failed to get index id: %v", err)
- continue
- }
- paramsLib := make(map[string]interface{})
- paramsLib["IndexId"] = indexId
- paramsLib["DataTime"] = format
- postEdbLib, err := httpRequestFill(paramsLib, utils.GET_LY_DATA_BY_INDEX_ID_AND_DATA_TIME)
- if err != nil {
- logs.Error("SupplyDemandBalanceProcessor Process() : Failed to get data by index id and date: %v", err)
- continue
- }
- var requestResponse models.RequestResponse[[]models.BaseFromLyData]
- err = json.Unmarshal(postEdbLib, &requestResponse)
- indexData := requestResponse.Data
- if len(indexData) > 0 {
- logs.Info("SupplyDemandBalanceProcessor Process() : Data already exists for index %d and date %s", indexId, dateText)
- continue
- }
- valueStr := row[blocColumnIdx]
- value, err := strconv.ParseFloat(valueStr, 64)
- if err != nil {
- return []models.BaseFromLyData{}, fmt.Errorf("SupplyDemandBalanceProcessor Process() : failed to parse value '%s': %v", valueStr, err)
- }
- // 创建并添加到结果列表
- baseFromLyData := models.BaseFromLyData{
- DataTime: format,
- Value: value,
- BaseFromLyIndexId: indexId,
- IndexCode: indexCode,
- }
- result = append(result, baseFromLyData)
- } else {
- log.Printf("SupplyDemandBalanceProcessor Process() : Column index out of range for row '%s', '%s'", rowBloc, columnBloc)
- }
- break
- }
- }
- }
- return result, nil
- }
- // PalmOilImportCostProcessor 棕榈油进口成本
- type PalmOilImportCostProcessor struct{}
- func (p *PalmOilImportCostProcessor) Process(ctx context.Context, product string, reportContent string, keywords []string, classifyId int) ([]models.BaseFromLyData, error) {
- logs.Info("Processing palm oil import cost...")
- // 解析关键字
- if len(keywords) < 5 {
- return []models.BaseFromLyData{}, fmt.Errorf("PalmOilImportCostProcessor Process() : keywords must contain at least 5 elements")
- }
- // 拿到 行关键字和列关键字
- columnName := keywords[len(keywords)-4]
- rowVariety := keywords[0]
- rowPort := keywords[len(keywords)-3]
- indexNamePrefix := keywords[:1]
- indexNameSuffix := keywords[1:]
- // 提取所有表格数据
- tableData := getNoHeadTableData(reportContent)
- // 提取日期信息
- dateText, err := getDateInfo(ctx)
- if err != nil {
- return []models.BaseFromLyData{}, err
- }
- // 时间格式转换
- format, err := utils.ConvertTimeFormat(dateText)
- if err != nil {
- return []models.BaseFromLyData{}, err
- }
- // 解析日期并计算当前月份
- targetMonths, err := utils.GetYearMonthNoYear(format)
- if err != nil {
- return []models.BaseFromLyData{}, fmt.Errorf("PalmOilImportCostProcessor Process() : Failed to parse date: %v", err)
- }
- fmt.Printf("Target Month: %s\n", targetMonths)
- // 处理提取的表格数据
- var result []models.BaseFromLyData
- for _, data := range tableData {
- tableHeaders := data.Headers
- tableRows := data.Rows
- // 查找目标列
- columnIdx := -1
- for i, header := range tableHeaders {
- if strings.Contains(header, columnName) {
- columnIdx = i
- break
- }
- }
- if columnIdx == -1 {
- log.Printf("PalmOilImportCostProcessor Process() : Column '%s' not found in table", columnName)
- continue
- }
- // 处理表格中的每一行
- //var flag bool = true
- var previousRowVariety string
- var previousRowPort string
- var previousRowFob string
- for rowIndex, row := range tableRows {
- if len(row) == len(tableHeaders) {
- previousRowVariety = row[0]
- previousRowPort = row[1]
- previousRowFob = row[2]
- } else if len(row) == len(tableHeaders)-1 {
- previousRowPort = row[0]
- previousRowFob = row[1]
- row = append([]string{previousRowVariety}, row...)
- tableRows[rowIndex] = row
- } else if len(row) == len(tableHeaders)-2 {
- // 这段这里不需要。。。先保留吧
- previousRowFob = row[0]
- row = append([]string{previousRowVariety, previousRowPort}, row...)
- tableRows[rowIndex] = row
- } else if len(row) == len(tableHeaders)-3 {
- row = append([]string{previousRowVariety, previousRowPort, previousRowFob}, row...)
- tableRows[rowIndex] = row
- }
- for _, targetMonth := range targetMonths {
- if len(row) >= len(tableHeaders) && strings.Contains(rowVariety, row[0]) && row[1] == targetMonth && row[len(row)-1] == rowPort {
- if columnIdx < len(row) {
- // 指标名称
- indexNameList := append(indexNamePrefix, append([]string{targetMonth}, indexNameSuffix...)...)
- indexName := strings.Join(indexNameList[:len(keywords)-2], ":")
- // 指标编码
- indexCode := utils.GenerateIndexCode(sourceName, indexName)
- // 指标id获取
- indexId, err := getIndexId(indexCode, indexName, classifyId, sourceName, keywords[len(keywords)-2], keywords[len(keywords)-1])
- if err != nil {
- logs.Error("PalmOilImportCostProcessor Process() : Failed to get index id: %v", err)
- continue
- }
- paramsLib := make(map[string]interface{})
- paramsLib["IndexId"] = indexId
- paramsLib["DataTime"] = format
- postEdbLib, err := httpRequestFill(paramsLib, utils.GET_LY_DATA_BY_INDEX_ID_AND_DATA_TIME)
- if err != nil {
- logs.Error("PalmOilImportCostProcessor Process() : Failed to get data by index id and date: %v", err)
- continue
- }
- var requestResponse models.RequestResponse[[]models.BaseFromLyData]
- err = json.Unmarshal(postEdbLib, &requestResponse)
- indexData := requestResponse.Data
- if len(indexData) > 0 {
- logs.Info("PalmOilImportCostProcessor Process() : Data already exists for index %d and date %s", indexId, dateText)
- continue
- }
- valueStr := row[columnIdx]
- value, err := strconv.ParseFloat(valueStr, 64)
- if err != nil {
- return []models.BaseFromLyData{}, fmt.Errorf("failed to parse value '%s': %v", valueStr, err)
- }
- // 创建并添加到结果列表
- baseFromLyData := models.BaseFromLyData{
- DataTime: format,
- Value: value,
- BaseFromLyIndexId: indexId,
- IndexCode: indexCode,
- }
- result = append(result, baseFromLyData)
- } else {
- log.Printf("PalmOilImportCostProcessor Process() : Column index out of range for row '%s', '%s'", rowVariety, rowPort)
- }
- break
- }
- }
- }
- }
- return result, nil
- }
- // ImportEstimateProcessor
- // @Description: 进口预估处理器
- type ImportEstimateProcessor struct{}
- func (p *ImportEstimateProcessor) Process(ctx context.Context, product string, reportContent string, keywords []string, classifyId int) ([]models.BaseFromLyData, error) {
- logs.Info("Processing import estimate...")
- // 解析关键字
- if len(keywords) < 4 {
- return []models.BaseFromLyData{}, fmt.Errorf("ImportEstimateProcessor Process() : keywords must contain at least 4 elements")
- }
- // 拿到 行关键字和列关键字
- var columnDates []string
- rowVariety := keywords[1]
- // 提取所有表格数据
- tableData := getNoHeadTableData(reportContent)
- // 提取日期信息
- dateText, err := getDateInfo(ctx)
- if err != nil {
- return []models.BaseFromLyData{}, err
- }
- // 时间格式转换
- format, err := utils.ConvertTimeFormat(dateText)
- if err != nil {
- return []models.BaseFromLyData{}, err
- }
- columnDates, err = utils.GetNextThreeMonthsNoYear(format)
- if err != nil {
- return nil, err
- }
- monthsLastDay, err := utils.GetNextThreeMonthsLastDay(format)
- if err != nil {
- return nil, err
- }
- // 处理提取的表格数据
- var result []models.BaseFromLyData
- for _, data := range tableData {
- tableHeaders := data.Headers
- tableRows := data.Rows
- // 查找目标列
- for _, columnDate := range columnDates {
- columnIdx := -1
- for i, tableHeader := range tableHeaders {
- if strings.Contains(tableHeader, columnDate) {
- columnIdx = i
- break
- }
- }
- if columnIdx == -1 {
- log.Printf("ImportEstimateProcessor Process() : Column '%s' not found in table", columnDate)
- continue
- } else {
- // 处理表格中的每一行
- for _, row := range tableRows {
- if len(row) >= len(tableHeaders) && strings.Contains(row[0], rowVariety) && isNumber(row[columnIdx]) {
- if columnIdx < len(row) {
- // 指标名称
- indexName := strings.Join(keywords[:len(keywords)-2], `:`)
- // 指标编码
- indexCode := utils.GenerateIndexCode(sourceName, indexName)
- // 指标id获取
- indexId, err := getIndexId(indexCode, indexName, classifyId, sourceName, keywords[len(keywords)-2], keywords[len(keywords)-1])
- if err != nil {
- logs.Error("ImportEstimateProcessor Process() : Failed to get index id: %v", err)
- continue
- }
- toNumber, err := utils.ConvertMonthToNumber(columnDate)
- if err != nil {
- logs.Error("ImportEstimateProcessor Process() : Failed to convert month to number: %v", err)
- continue
- }
- slice, err := utils.GetElementInSlice(monthsLastDay, toNumber)
- if err != nil {
- logs.Error("ImportEstimateProcessor Process() : Failed to get element in slice: %v", err)
- continue
- }
- paramsLib := make(map[string]interface{})
- paramsLib["IndexId"] = indexId
- paramsLib["DataTime"] = format
- postEdbLib, err := httpRequestFill(paramsLib, utils.GET_LY_DATA_BY_INDEX_ID_AND_DATA_TIME)
- if err != nil {
- logs.Error("ImportEstimateProcessor Process() : Failed to get data by index id and date: %v", err)
- continue
- }
- var requestResponse models.RequestResponse[[]models.BaseFromLyData]
- err = json.Unmarshal(postEdbLib, &requestResponse)
- indexData := requestResponse.Data
- valueStr := row[columnIdx]
- value, err := strconv.ParseFloat(valueStr, 64)
- if err != nil {
- return []models.BaseFromLyData{}, fmt.Errorf("failed to parse value '%s': %v", valueStr, err)
- }
- if len(indexData) > 0 {
- if indexData[0].Value != value {
- logs.Info("ImportEstimateProcessor Process() : Data already exists for index %d and date %s", indexId, dateText)
- lyData := indexData[0]
- time, err := utils.StringToTime(lyData.ModifyTime)
- if err != nil {
- return nil, err
- }
- timeZero, err := utils.StringToTimeZero(format)
- if err != nil {
- return nil, err
- }
- if lyData.Value != value && time.Before(timeZero) {
- // 更新指标数据
- paramsLib := make(map[string]interface{})
- paramsLib["Id"] = lyData.BaseFromLyDataId
- paramsLib["Value"] = value
- _, err := httpRequestFill(paramsLib, utils.UPDATE_LY_DATA_BY_ID)
- if err != nil {
- return nil, fmt.Errorf("ImportEstimateProcessor Process() : failed to parse value '%s': %v", valueStr, err)
- }
- // 同步更新指标库数据
- paramsLib = make(map[string]interface{})
- paramsLib["IndexCode"] = lyData.IndexCode
- paramsLib["DataTime"] = lyData.DataTime
- postEdbLib, err := httpRequestFill(paramsLib, utils.GET_LY_EDB_DATA_BY_INDEX_CODE_AND_EXACT_DATA_TIME)
- if err != nil {
- logs.Error("ImportEstimateProcessor Process() : Failed to get ly edb data by index code and exact data time: %v", err)
- continue
- }
- var requestResponse models.RequestResponse[[]models.EdbDataLy]
- err = json.Unmarshal(postEdbLib, &requestResponse)
- if err != nil {
- return nil, err
- }
- lyEdbIndexData := requestResponse.Data
- if len(lyEdbIndexData) > 0 {
- paramsLib := make(map[string]interface{})
- paramsLib["Id"] = lyEdbIndexData[0].EdbInfoId
- paramsLib["Value"] = value
- _, err := httpRequestFill(paramsLib, utils.UPDATE_LY_EDB_DATA_BY_ID)
- if err != nil {
- return nil, fmt.Errorf("ImportEstimateProcessor Process() : failed to parse value '%s': %v", valueStr, err)
- }
- }
- }
- }
- continue
- }
- // 创建并添加到结果列表
- baseFromLyData := models.BaseFromLyData{
- DataTime: slice,
- Value: value,
- BaseFromLyIndexId: indexId,
- IndexCode: indexCode,
- }
- result = append(result, baseFromLyData)
- } else {
- log.Printf("ImportEstimateProcessor Process() : Column index out of range for row '%s', '%s'", rowVariety, columnDate)
- }
- break
- }
- }
- }
- }
- }
- return result, nil
- }
- // InternationalPriceProcessor
- // @Description: 国际价格处理器
- type InternationalPriceProcessor struct{}
- func (p *InternationalPriceProcessor) Process(ctx context.Context, product string, reportContent string, keywords []string, classifyId int) ([]models.BaseFromLyData, error) {
- logs.Info("Processing international price...")
- // 解析关键字
- if len(keywords) < 4 {
- return []models.BaseFromLyData{}, fmt.Errorf("InternationalPriceProcessor Process() : keywords must contain at least 4 elements")
- }
- // 拿到 行关键字和列关键字
- columnName := keywords[1]
- rowVariety := keywords[0]
- indexNamePrefix := keywords[:1]
- indexNameSuffix := keywords[1:]
- // 提取所有表格数据
- tableData := getNoHeadTableData(reportContent)
- // 提取日期信息
- dateText, err := getDateInfo(ctx)
- if err != nil {
- return []models.BaseFromLyData{}, err
- }
- // 时间格式转换
- format, err := utils.ConvertTimeFormat(dateText)
- if err != nil {
- return []models.BaseFromLyData{}, err
- }
- // 解析日期并计算当前月份 和 后两月
- yearMonths, err := utils.ConvertTimeFormatToYearMonth(format)
- if err != nil {
- return nil, err
- }
- fmt.Printf("Target yearMonth: %s\n", yearMonths)
- // 处理提取的表格数据
- var result []models.BaseFromLyData
- for _, data := range tableData {
- tableHeaders := data.Headers
- tableRows := data.Rows
- // 查找目标列
- columnIdx := -1
- for i, header := range tableHeaders {
- if strings.Contains(header, columnName) {
- columnIdx = i
- break
- }
- }
- if columnIdx == -1 {
- log.Printf("InternationalPriceProcessor Process() : Column '%s' not found in table", columnName)
- continue
- }
- // 处理表格中的每一行
- var previousRowVariety string
- for rowIndex, row := range tableRows {
- if len(row) == len(tableHeaders) {
- previousRowVariety = row[0]
- } else if len(row) == len(tableHeaders)-1 {
- row = append([]string{previousRowVariety}, row...)
- tableRows[rowIndex] = row
- }
- for _, targetMonth := range yearMonths {
- if len(row) >= len(tableHeaders) && row[0] == rowVariety && row[1] == targetMonth {
- if columnIdx < len(row) {
- // 指标名称
- indexNameList := append(indexNamePrefix, append([]string{targetMonth}, indexNameSuffix...)...)
- indexName := strings.Join(indexNameList[:len(keywords)-2], ":")
- // 指标编码
- indexCode := utils.GenerateIndexCode(sourceName, indexName)
- // 指标id获取
- indexId, err := getIndexId(indexCode, indexName, classifyId, sourceName, keywords[len(keywords)-2], keywords[len(keywords)-1])
- if err != nil {
- logs.Error("InternationalPriceProcessor Process() : Failed to get index id: %v", err)
- continue
- }
- paramsLib := make(map[string]interface{})
- paramsLib["IndexId"] = indexId
- paramsLib["DataTime"] = format
- postEdbLib, err := httpRequestFill(paramsLib, utils.GET_LY_DATA_BY_INDEX_ID_AND_DATA_TIME)
- if err != nil {
- logs.Error("InternationalPriceProcessor Process() : Failed to get data by index id and date: %v", err)
- continue
- }
- var requestResponse models.RequestResponse[[]models.BaseFromLyData]
- err = json.Unmarshal(postEdbLib, &requestResponse)
- indexData := requestResponse.Data
- if len(indexData) > 0 {
- logs.Info("InternationalPriceProcessor Process() : Data already exists for index %d and date %s", indexId, dateText)
- // 无需更新 指标展示本月和后两月的数据,报告每天更新,每天的值可能会改变,即使今天和每天数据一致,也需要每天记录,如果到这里也只是说,今天这个报告被读取了两次
- continue
- }
- valueStr := row[columnIdx]
- value, err := strconv.ParseFloat(valueStr, 64)
- if err != nil {
- return []models.BaseFromLyData{}, fmt.Errorf("failed to parse value '%s': %v", valueStr, err)
- }
- // 创建并添加到结果列表
- baseFromLyData := models.BaseFromLyData{
- DataTime: format,
- Value: value,
- BaseFromLyIndexId: indexId,
- IndexCode: indexCode,
- }
- result = append(result, baseFromLyData)
- } else {
- log.Printf("InternationalPriceProcessor Process() : Column index out of range for row '%s', '%s'", rowVariety, columnName)
- }
- break
- }
- }
- }
- }
- return result, nil
- }
- // CanadaStatisticsBureauProcessor
- // @Description: 加拿大统计局处理器
- type CanadaStatisticsBureauProcessor struct{}
- func (p *CanadaStatisticsBureauProcessor) Process(ctx context.Context, product string, reportContent string, keywords []string, classifyId int) ([]models.BaseFromLyData, error) {
- logs.Info("Processing Canada statistics bureau...")
- // 解析关键字
- if len(keywords) < 4 {
- return []models.BaseFromLyData{}, fmt.Errorf("CanadaStatisticsBureauProcessor Process() : keywords must contain at least 4 elements")
- }
- // 拿到 行关键字和列关键字
- columnDate := "本周"
- rowVariety := keywords[1]
- // 提取所有表格数据
- tableData := getNoHeadTableData(reportContent)
- // 提取日期信息
- dateText, err := getDateInfo(ctx)
- if err != nil {
- return []models.BaseFromLyData{}, err
- }
- // 时间格式转换
- format, err := utils.ConvertTimeFormat(dateText)
- if err != nil {
- return []models.BaseFromLyData{}, err
- }
- // 处理提取的表格数据
- var result []models.BaseFromLyData
- for _, data := range tableData {
- tableHeaders := data.Headers
- tableRows := data.Rows
- // 查找目标列
- columnIdx := -1
- for i, header := range tableHeaders {
- if strings.Contains(header, columnDate) {
- columnIdx = i
- break
- }
- }
- if columnIdx == -1 {
- log.Printf("CanadaStatisticsBureauProcessor Process() : Column '%s' not found in table", columnDate)
- continue
- }
- // 处理表格中的每一行
- for _, row := range tableRows {
- if len(row) >= len(tableHeaders) {
- if columnIdx < len(row) {
- if row[0] != rowVariety {
- continue
- }
- // 指标名称
- indexName := strings.Join(keywords[:len(keywords)-2], ":")
- // 指标编码
- indexCode := utils.GenerateIndexCode(sourceName, indexName)
- // 指标id获取
- indexId, err := getIndexId(indexCode, indexName, classifyId, sourceName, keywords[len(keywords)-2], keywords[len(keywords)-1])
- if err != nil {
- logs.Error("CanadaStatisticsBureauProcessor Process() : Failed to get index id: %v", err)
- continue
- }
- paramsLib := make(map[string]interface{})
- paramsLib["IndexId"] = indexId
- paramsLib["DataTime"] = format
- postEdbLib, err := httpRequestFill(paramsLib, utils.GET_LY_DATA_BY_INDEX_ID_AND_DATA_TIME)
- if err != nil {
- logs.Error("CanadaStatisticsBureauProcessor Process() : Failed to get data by index id and date: %v", err)
- continue
- }
- var requestResponse models.RequestResponse[[]models.BaseFromLyData]
- err = json.Unmarshal(postEdbLib, &requestResponse)
- indexData := requestResponse.Data
- if len(indexData) > 0 {
- logs.Info("CanadaStatisticsBureauProcessor Process() : Data already exists for index %d and date %s", indexId, dateText)
- // 无需更新 指标展示本周的数据,报告每周更新,即使本周和上周数据一致,也需要每周记录,如果到这里也只是说,今天这个报告被读取了两次
- continue
- }
- valueStr := row[columnIdx]
- value, err := strconv.ParseFloat(valueStr, 64)
- if err != nil {
- return []models.BaseFromLyData{}, fmt.Errorf("failed to parse value '%s': %v", valueStr, err)
- }
- // 创建并添加到结果列表
- baseFromLyData := models.BaseFromLyData{
- DataTime: format,
- Value: value,
- BaseFromLyIndexId: indexId,
- IndexCode: indexCode,
- }
- result = append(result, baseFromLyData)
- } else {
- log.Printf("CanadaStatisticsBureauProcessor Process() : Column index out of range for row '%s'", columnDate)
- }
- break
- }
- }
- }
- return result, nil
- }
- // ImportExportAnalysisProcessor
- // @Description: 进出口分析处理器
- type ImportExportAnalysisProcessor struct{}
- func (p *ImportExportAnalysisProcessor) Process(ctx context.Context, product string, reportContent string, keywords []string, classifyId int) ([]models.BaseFromLyData, error) {
- fmt.Println("Processing processing profit...")
- // 解析关键字
- if len(keywords) < 3 {
- return []models.BaseFromLyData{}, fmt.Errorf("ProcessingProfitProcessor Process() : keywords must contain at least 3 elements")
- }
- // 拿到 行关键字和列关键字
- var columnDates []string
- // 提取所有表格数据
- tableData := getNoHeadTableData(reportContent)
- // 提取日期信息
- dateText, err := getDateInfo(ctx)
- if err != nil {
- return []models.BaseFromLyData{}, err
- }
- // 时间格式转换
- format, err := utils.ConvertTimeFormat(dateText)
- if err != nil {
- return []models.BaseFromLyData{}, err
- }
- // 2025年1月可能才出2024年12月的数据,所以往前取一年
- columnDates, err = utils.GetCurrentYearAndLastYear(format)
- if err != nil {
- return nil, err
- }
- // 处理提取的表格数据
- var result []models.BaseFromLyData
- for _, data := range tableData {
- tableHeaders := data.Headers
- tableRows := data.Rows
- for _, columnDate := range columnDates {
- // 查找目标列
- columnIdx := -1
- for i, header := range tableHeaders {
- if strings.Contains(header, columnDate) {
- columnIdx = i
- break
- }
- }
- if columnIdx == -1 {
- log.Printf("ProcessingProfitProcessor Process() : Column '%s' not found in table", columnDate)
- continue
- }
- // 处理表格中的每一行
- for _, row := range tableRows {
- if len(row) >= len(tableHeaders) {
- if columnIdx < len(row) && isNumber(row[columnIdx]) && isNumber(row[0]) {
- // 指标名称
- indexName := strings.Join(keywords[:len(keywords)-2], ":")
- // 指标编码
- indexCode := utils.GenerateIndexCode(sourceName, indexName)
- // 指标id获取
- indexId, err := getIndexId(indexCode, indexName, classifyId, sourceName, keywords[len(keywords)-2], keywords[len(keywords)-1])
- if err != nil {
- logs.Error("ProcessingProfitProcessor Process() : Failed to get index id: %v", err)
- continue
- }
- atoi, err := strconv.Atoi(row[0])
- if err != nil {
- return nil, err
- }
- date := columnDate[:4] + "-" + fmt.Sprintf("%02d", atoi)
- lastDayOfMonth, err := utils.GetLastDayOfMonth(date)
- if err != nil {
- return nil, err
- }
- paramsLib := make(map[string]interface{})
- paramsLib["IndexId"] = indexId
- paramsLib["DataTime"] = format
- postEdbLib, err := httpRequestFill(paramsLib, utils.GET_LY_DATA_BY_INDEX_ID_AND_DATA_TIME)
- if err != nil {
- logs.Error("ProcessingProfitProcessor Process() : Failed to get data by index id and date: %v", err)
- continue
- }
- var requestResponse models.RequestResponse[[]models.BaseFromLyData]
- err = json.Unmarshal(postEdbLib, &requestResponse)
- indexData := requestResponse.Data
- if len(indexData) > 0 {
- logs.Info("ProcessingProfitProcessor Process() : Data already exists for index %d and date %s", indexId, dateText)
- continue
- }
- valueStr := row[columnIdx]
- value, err := strconv.ParseFloat(valueStr, 64)
- if err != nil {
- return []models.BaseFromLyData{}, fmt.Errorf("failed to parse value '%s': %v", valueStr, err)
- }
- // 创建并添加到结果列表
- baseFromLyData := models.BaseFromLyData{
- DataTime: lastDayOfMonth,
- Value: value,
- BaseFromLyIndexId: indexId,
- IndexCode: indexCode,
- }
- result = append(result, baseFromLyData)
- continue
- } else {
- log.Printf("ProcessingProfitProcessor Process() : Column index out of range for row '%s'", columnDate)
- }
- break
- }
- }
- }
- }
- return result, nil
- }
- // ExtractValueInParentheses 从字符串中提取括号中的值
- func extractValueInParentheses(input string) (string, error) {
- re := regexp.MustCompile(`(([^)]+))`)
- matches := re.FindStringSubmatch(input)
- if len(matches) > 1 {
- return matches[1], nil
- }
- return "", fmt.Errorf("no value found in parentheses")
- }
- // 获取指标id,根据指标名称判断,没有插入指标生成返回
- func getIndexId(indexCode string, indexName string, classifyId int, sourceName string, frequency string, unit string) (int, error) {
- if indexCode == "lysww" {
- return 0, fmt.Errorf("indexCode is error")
- }
- // 判断指标是否存在
- var indexId int
- paramsLib := make(map[string]interface{})
- paramsLib["IndexCode"] = indexCode
- postEdbLib, err := httpRequestFill(paramsLib, utils.GET_LY_INDEX_BY_CODE)
- if err != nil {
- return 0, fmt.Errorf("getIndexId() : Failed to get ly index by code: %v", err)
- }
- var requestResponse models.RequestResponse[models.BaseFromLyIndex]
- err = json.Unmarshal(postEdbLib, &requestResponse)
- if err != nil {
- return 0, fmt.Errorf("getIndexId() : Failed to unmarshal response: %v", err)
- }
- indexInfo := requestResponse.Data
- if indexInfo.IndexName == "" {
- // 新增指标
- index, err := addLyIndex(classifyId, indexCode, indexName, frequency, unit)
- if err != nil {
- return 0, err
- }
- indexId = index
- } else {
- indexId = indexInfo.BaseFromLyIndexId
- }
- return indexId, nil
- }
- // 获取页面时间信息
- func getDateInfo(ctx context.Context) (string, error) {
- var dateText string
- err := chromedp.Run(ctx,
- chromedp.Evaluate(`document.querySelector('div.a_date span').innerText`, &dateText),
- )
- if err != nil {
- return "", fmt.Errorf("processing Process() : Failed to extract report date: %v", err)
- }
- logs.Info("Processing Process() : Report Extracted Date: %s", dateText)
- return dateText, nil
- }
- // 获取所有表格数据 获取表格中有thead标签的数据
- func getAllTableData(reportContent string) []TableData {
- var tableData []TableData
- doc, err := goquery.NewDocumentFromReader(strings.NewReader(reportContent))
- if err != nil {
- log.Fatal(err)
- }
- // 选择 id 为 "a_content" 的 div
- doc.Find("#a_content").Each(func(index int, item *goquery.Selection) {
- item.Find("table").Each(func(index int, table *goquery.Selection) {
- var headers []string
- var rows [][]string
- // 提取表头
- table.Find("thead th").Each(func(index int, th *goquery.Selection) {
- headers = append(headers, th.Text())
- })
- // 提取表格行数据
- table.Find("tbody tr").Each(func(index int, row *goquery.Selection) {
- var rowData []string
- row.Find("td").Each(func(index int, td *goquery.Selection) {
- rowData = append(rowData, td.Text())
- })
- rows = append(rows, rowData)
- })
- // 仅在表头存在时添加到结果中
- if len(headers) > 0 {
- tableData = append(tableData, TableData{
- Headers: headers,
- Rows: rows,
- })
- }
- })
- })
- return tableData
- }
- // 获取无头表格数据
- func getNoHeadTableData(reportContent string) []TableData {
- var tableData []TableData
- doc, err := goquery.NewDocumentFromReader(strings.NewReader(reportContent))
- if err != nil {
- log.Fatal(err)
- }
- // Find the div with id "a_content"
- doc.Find("#a_content").Each(func(index int, div *goquery.Selection) {
- // Find all tables within the div
- div.Find("table").Each(func(index int, table *goquery.Selection) {
- var headers []string
- var rows [][]string
- // Extract table headers if any
- table.Find("tr").Each(func(index int, tr *goquery.Selection) {
- var rowData []string
- tr.Find("td, th").Each(func(index int, cell *goquery.Selection) {
- cellText := cell.Text()
- rowData = append(rowData, cellText)
- })
- if index == 0 && len(rowData) > 0 {
- // The first row is treated as the header row
- headers = rowData
- } else if len(rowData) > 0 {
- // Add the row data to the rows slice
- rows = append(rows, rowData)
- }
- })
- // Only add table data if headers are present
- if len(headers) > 0 {
- tableData = append(tableData, TableData{
- Headers: headers,
- Rows: rows,
- })
- }
- })
- })
- return tableData
- }
- // 获取表格数据 获取id 为 a_content 的 div 中的第一个表格 左上角那个单元格会拼在第一个,会拼上列上的合并单元格
- func getTableData(reportContent string, isFirst bool) TableData {
- doc, err := goquery.NewDocumentFromReader(strings.NewReader(reportContent))
- if err != nil {
- log.Fatal(err)
- }
- tableData := &TableData{}
- // 只提取 id 为 a_content 的 div 中的第一个表格
- var firstTable *goquery.Selection
- if isFirst {
- firstTable = doc.Find("div#a_content table").First()
- } else {
- firstTable = doc.Find("div#a_content table").Last()
- }
- var combinedHeaders []string
- // 提取表头
- firstTable.Find("tr").Each(func(i int, row *goquery.Selection) {
- if i == 0 {
- // 第一行处理合并单元格,保存到 combinedHeaders
- row.Find("td,th").Each(func(j int, cell *goquery.Selection) {
- if j == 0 {
- // 把左上角的“年度(10/9月)”放入 Headers 第一个元素
- tableData.Headers = append(tableData.Headers, strings.TrimSpace(cell.Text()))
- } else {
- // 处理其他单元格
- colspan, exists := cell.Attr("colspan")
- if exists {
- spanCount := 0
- fmt.Sscanf(colspan, "%d", &spanCount)
- for k := 0; k < spanCount; k++ {
- combinedHeaders = append(combinedHeaders, strings.TrimSpace(cell.Text()))
- }
- } else {
- combinedHeaders = append(combinedHeaders, strings.TrimSpace(cell.Text()))
- }
- }
- })
- } else if i == 1 {
- // 第二行处理具体标题,组合后保存到 Headers
- row.Find("td,th").Each(func(j int, cell *goquery.Selection) {
- if j < len(combinedHeaders) {
- fullHeader := combinedHeaders[j] + strings.TrimSpace(cell.Text())
- tableData.Headers = append(tableData.Headers, fullHeader)
- }
- })
- } else {
- // 处理数据行
- var rowData []string
- row.Find("td").Each(func(j int, cell *goquery.Selection) {
- rowData = append(rowData, strings.TrimSpace(cell.Text()))
- })
- if len(rowData) > 0 {
- tableData.Rows = append(tableData.Rows, rowData)
- }
- }
- })
- return *tableData
- }
- // 获取采购装船表格数据
- func getPurchaseShippingTableData(reportContent string) TableData {
- doc, err := goquery.NewDocumentFromReader(strings.NewReader(reportContent))
- if err != nil {
- log.Fatal(err)
- }
- var tableData TableData
- // 只提取 id 为 a_content 的 div 中的第一个表格
- firstTable := doc.Find("div#a_content table").First()
- // 提取表头
- var headers []string
- var subHeaders []string
- firstTable.Find("thead tr").Each(func(i int, row *goquery.Selection) {
- row.Find("th").Each(func(j int, cell *goquery.Selection) {
- headerText := strings.TrimSpace(cell.Text())
- if i == 0 {
- // 处理第一行表头
- colspan, exists := cell.Attr("colspan")
- if exists {
- spanCount := 0
- fmt.Sscanf(colspan, "%d", &spanCount)
- for k := 0; k < spanCount; k++ {
- headers = append(headers, headerText)
- }
- } else {
- headers = append(headers, headerText)
- }
- } else if i == 1 {
- // 处理第二行表头
- subHeaders = append(subHeaders, headerText)
- }
- })
- })
- // 合并第一行和第二行表头信息
- if len(subHeaders) > 0 {
- for i := 0; i < len(subHeaders); i++ {
- // 从第四个单元格开始拼接
- headers[3+i] = headers[3+i] + subHeaders[i]
- }
- }
- tableData.Headers = headers
- // 处理数据行
- firstTable.Find("tbody tr").Each(func(i int, row *goquery.Selection) {
- var rowData []string
- row.Find("td").Each(func(j int, cell *goquery.Selection) {
- rowData = append(rowData, strings.TrimSpace(cell.Text()))
- })
- if len(rowData) > 0 {
- tableData.Rows = append(tableData.Rows, rowData)
- }
- })
- return tableData
- }
- // 判断字符串是否是数字
- func isNumeric(value string) bool {
- // 正则表达式匹配整数和浮点数
- re := regexp.MustCompile(`^[+-]?(\d+(\.\d*)?|\.\d+)$`)
- return re.MatchString(value)
- }
- // 只保留汉字
- func extractChinese(text string) string {
- re := regexp.MustCompile(`[^\p{Han}]`) // 匹配非汉字字符
- return re.ReplaceAllString(text, "")
- }
- // 去除括号中的内容 包含括号 ()
- func removeParentheses(text string) string {
- re := regexp.MustCompile(`\([^)]*\)`)
- return re.ReplaceAllString(text, "")
- }
- // IsChinese 判断传入的是否是汉字
- func IsChinese(str string) bool {
- for _, r := range str {
- if unicode.Is(unicode.Han, r) {
- return true
- }
- }
- return false
- }
- // 判断是否是数字
- func isNumber(str string) bool {
- _, err := strconv.ParseFloat(str, 64)
- return err == nil
- }
|