From 524e8eb7955a7db8e8b923a7d1ed2d4d4f23cd27 Mon Sep 17 00:00:00 2001 From: Joellensilva Date: Wed, 10 May 2023 12:32:39 -0300 Subject: [PATCH 1/2] removendo /v1 --- docs/docs.go | 2 +- docs/swagger.json | 2 +- docs/swagger.yaml | 2 +- main.go | 23 +---- papi/handlers.go | 137 ------------------------ uiapi/handlers.go | 257 +--------------------------------------------- 6 files changed, 7 insertions(+), 416 deletions(-) diff --git a/docs/docs.go b/docs/docs.go index f4ff678..7f30400 100644 --- a/docs/docs.go +++ b/docs/docs.go @@ -19,7 +19,7 @@ const docTemplate = `{ "host": "{{.Host}}", "basePath": "{{.BasePath}}", "paths": { - "/uiapi/v1/orgao/resumo/{orgao}": { + "/uiapi/v2/orgao/resumo/{orgao}": { "get": { "description": "Retorna os dados anuais de um orgão", "produces": [ diff --git a/docs/swagger.json b/docs/swagger.json index 0d96535..1fea4ff 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -9,7 +9,7 @@ "version": "1.0" }, "paths": { - "/uiapi/v1/orgao/resumo/{orgao}": { + "/uiapi/v2/orgao/resumo/{orgao}": { "get": { "description": "Retorna os dados anuais de um orgão", "produces": [ diff --git a/docs/swagger.yaml b/docs/swagger.yaml index 88f2207..5baa8d5 100644 --- a/docs/swagger.yaml +++ b/docs/swagger.yaml @@ -464,7 +464,7 @@ info: title: API do dadosjusbr.org version: "1.0" paths: - /uiapi/v1/orgao/resumo/{orgao}: + /uiapi/v2/orgao/resumo/{orgao}: get: description: Retorna os dados anuais de um orgão operationId: GetAnnualSummary diff --git a/main.go b/main.go index d138ac4..2d4adf9 100644 --- a/main.go +++ b/main.go @@ -168,23 +168,16 @@ func main() { log.Fatalf("Error creating uiapi handler: %q", err) } // Return a summary of an agency. This information will be used in the head of the agency page. - uiAPIGroup.GET("/v1/orgao/resumo/:orgao/:ano/:mes", uiApiHandler.GetSummaryOfAgency) uiAPIGroup.GET("/v2/orgao/resumo/:orgao/:ano/:mes", uiApiHandler.V2GetSummaryOfAgency) // TODO: Apagar essa rota (v1) quando o site migrar para a nova rota. - uiAPIGroup.GET("/v1/orgao/resumo/:orgao", uiApiHandler.GetAnnualSummary) uiAPIGroup.GET("/v2/orgao/resumo/:orgao", uiApiHandler.GetAnnualSummary) // Return all the salary of a month and year. This will be used in the point chart at the entity page. - uiAPIGroup.GET("/v1/orgao/salario/:orgao/:ano/:mes", uiApiHandler.GetSalaryOfAgencyMonthYear) uiAPIGroup.GET("/v2/orgao/salario/:orgao/:ano/:mes", uiApiHandler.V2GetSalaryOfAgencyMonthYear) // Return the total of salary of every month of a year of a agency. The salary is divided in Wage, Perks and Others. This will be used to plot the bars chart at the state page. - uiAPIGroup.GET("/v1/orgao/totais/:orgao/:ano", uiApiHandler.GetTotalsOfAgencyYear) uiAPIGroup.GET("/v2/orgao/totais/:orgao/:ano", uiApiHandler.V2GetTotalsOfAgencyYear) // Return basic information of a type or state - uiAPIGroup.GET("/v1/orgao/:grupo", uiApiHandler.GetBasicInfoOfType) uiAPIGroup.GET("/v2/orgao/:grupo", uiApiHandler.V2GetBasicInfoOfType) - uiAPIGroup.GET("/v1/geral/remuneracao/:ano", uiApiHandler.GetGeneralRemunerationFromYear) uiAPIGroup.GET("/v2/geral/remuneracao/:ano", uiApiHandler.V2GetGeneralRemunerationFromYear) - uiAPIGroup.GET("/v1/geral/resumo", uiApiHandler.GeneralSummaryHandler) uiAPIGroup.GET("/v2/geral/resumo", uiApiHandler.GetGeneralSummary) // Retorna um conjunto de dados a partir de filtros informados por query params uiAPIGroup.GET("/v2/pesquisar", uiApiHandler.SearchByUrl) @@ -192,25 +185,15 @@ func main() { uiAPIGroup.GET("/v2/download", uiApiHandler.DownloadByUrl) apiHandler := papi.NewHandler(pgS3Client, conf.DadosJusURL, conf.PackageRepoURL) - // Public API configuration - apiGroup := e.Group("/v1", middleware.CORSWithConfig(middleware.CORSConfig{ - AllowOrigins: []string{"*"}, - AllowHeaders: []string{echo.HeaderOrigin, echo.HeaderContentType, echo.HeaderAccept, echo.HeaderContentLength}, - })) - // Return agency - apiGroup.GET("/orgao/:orgao", apiHandler.V1GetAgencyById) - // Return all agencies - apiGroup.GET("/orgaos", apiHandler.V1GetAllAgencies) - // Return MIs by year - apiGroup.GET("/dados/:orgao/:ano", apiHandler.GetMonthlyInfo) - // Return MIs by month - apiGroup.GET("/dados/:orgao/:ano/:mes", apiHandler.GetMonthlyInfo) + // V2 public api, to be used by the new returned data apiGroupV2 := e.Group("/v2", middleware.CORSWithConfig(middleware.CORSConfig{ AllowOrigins: []string{"*"}, AllowHeaders: []string{echo.HeaderOrigin, echo.HeaderContentType, echo.HeaderAccept, echo.HeaderContentLength}, })) + // Return agency apiGroupV2.GET("/orgao/:orgao", apiHandler.V2GetAgencyById) + // Return all agencies apiGroupV2.GET("/orgaos", apiHandler.V2GetAllAgencies) // Return MIs by year apiGroupV2.GET("/dados/:orgao/:ano", apiHandler.GetMonthlyInfosByYear) diff --git a/papi/handlers.go b/papi/handlers.go index 1c1e66f..cb02ef6 100644 --- a/papi/handlers.go +++ b/papi/handlers.go @@ -26,17 +26,6 @@ func NewHandler(client *storage.Client, dadosJusURL, packageRepoURL string) *han } } -func (h handler) V1GetAgencyById(c echo.Context) error { - agencyName := c.Param("orgao") - agency, err := h.client.Db.GetAgency(agencyName) - if err != nil { - return c.JSON(http.StatusNotFound, "Agency not found") - } - host := c.Request().Host - agency.URL = fmt.Sprintf("%s/v1/orgao/%s", host, agency.ID) - return c.JSON(http.StatusOK, agency) -} - // @ID GetAgencyById // @Tags public_api // @Description Busca um órgão específico utilizando seu ID. @@ -77,19 +66,6 @@ func (h handler) V2GetAgencyById(c echo.Context) error { return c.JSON(http.StatusOK, agency) } -func (h handler) V1GetAllAgencies(c echo.Context) error { - agencies, err := h.client.Db.GetAllAgencies() - if err != nil { - fmt.Println("Error while listing agencies: %w", err) - return c.JSON(http.StatusInternalServerError, "Error while listing agencies") - } - host := c.Request().Host - for i := range agencies { - agencies[i].URL = fmt.Sprintf("%s/v1/orgao/%s", host, agencies[i].ID) - } - return c.JSON(http.StatusOK, agencies) -} - // @ID GetAllAgencies // @Tags public_api // @Description Busca todos os órgãos disponíveis. @@ -133,119 +109,6 @@ func (h handler) V2GetAllAgencies(c echo.Context) error { return c.JSON(http.StatusOK, agencies) } -func (h handler) GetMonthlyInfo(c echo.Context) error { - year, err := strconv.Atoi(c.Param("ano")) - if err != nil { - return c.JSON(http.StatusBadRequest, fmt.Sprintf("Parâmetro ano=%d inválido", year)) - } - agencyName := strings.ToLower(c.Param("orgao")) - var monthlyInfo map[string][]models.AgencyMonthlyInfo - month := c.Param("mes") - if month != "" { - m, err := strconv.Atoi(month) - if err != nil { - return c.JSON(http.StatusBadRequest, fmt.Sprintf("Parâmetro mes=%d inválido", m)) - } - oma, _, err := h.client.Db.GetOMA(m, year, agencyName) - if err != nil { - return c.JSON(http.StatusBadRequest, "Error getting OMA data") - } - monthlyInfo = map[string][]models.AgencyMonthlyInfo{ - agencyName: {*oma}, - } - } else { - monthlyInfo, err = h.client.Db.GetMonthlyInfo([]models.Agency{{ID: agencyName}}, year) - } - if err != nil { - log.Printf("[totals of agency year] error getting data for first screen(ano:%d, estado:%s):%q", year, agencyName, err) - return c.JSON(http.StatusBadRequest, fmt.Sprintf("Parâmetro ano=%d ou orgao=%s inválidos", year, agencyName)) - } - - if len(monthlyInfo[agencyName]) == 0 { - return c.NoContent(http.StatusNotFound) - } - - var sumMI []summaryzedMI - for i := range monthlyInfo { - for _, mi := range monthlyInfo[i] { - // Fazemos duas checagens no formato do ProcInfo para saber se ele é vazio pois alguns dados diferem, no banco de dados, quando o procinfo é nulo. - if mi.ProcInfo == nil || mi.ProcInfo.String() == "" { - sumMI = append( - sumMI, - summaryzedMI{ - AgencyID: mi.AgencyID, - Error: nil, - Month: mi.Month, - Year: mi.Year, - Package: &backup{ - URL: h.formatDownloadUrl(mi.Package.URL), - Hash: mi.Package.Hash, - Size: mi.Package.Size, - }, - Summary: &summaries{ - MemberActive: summary{ - Count: mi.Summary.Count, - BaseRemuneration: dataSummary{ - Max: mi.Summary.BaseRemuneration.Max, - Min: mi.Summary.BaseRemuneration.Min, - Average: mi.Summary.BaseRemuneration.Average, - Total: mi.Summary.BaseRemuneration.Total, - }, - OtherRemunerations: dataSummary{ - Max: mi.Summary.OtherRemunerations.Max, - Min: mi.Summary.OtherRemunerations.Min, - Average: mi.Summary.OtherRemunerations.Average, - Total: mi.Summary.OtherRemunerations.Total, - }, - }, - }, - Metadata: &metadata{ - OpenFormat: mi.Meta.OpenFormat, - Access: mi.Meta.Access, - Extension: mi.Meta.Extension, - StrictlyTabular: mi.Meta.StrictlyTabular, - ConsistentFormat: mi.Meta.ConsistentFormat, - HasEnrollment: mi.Meta.HaveEnrollment, - HasCapacity: mi.Meta.ThereIsACapacity, - HasPosition: mi.Meta.HasPosition, - BaseRevenue: mi.Meta.BaseRevenue, - OtherRecipes: mi.Meta.OtherRecipes, - Expenditure: mi.Meta.Expenditure, - }, - Score: &score{ - Score: mi.Score.Score, - CompletenessScore: mi.Score.CompletenessScore, - EasinessScore: mi.Score.EasinessScore, - }, - Collect: &collect{ - Duration: mi.Duration, - CrawlerRepo: mi.CrawlerRepo, - CrawlerVersion: mi.CrawlerVersion, - ParserRepo: mi.ParserRepo, - ParserVersion: mi.ParserVersion, - }}) - // The status 4 is a report from crawlers that data is unavailable or malformed. By removing them from the API results, we make sure they are displayed as if there is no data. - } else if mi.ProcInfo.Status != 4 { - sumMI = append( - sumMI, - summaryzedMI{ - AgencyID: mi.AgencyID, - Error: &miError{ - ErrorMessage: mi.ProcInfo.Stderr, - Status: mi.ProcInfo.Status, - Cmd: mi.ProcInfo.Cmd, - }, - Month: mi.Month, - Year: mi.Year, - Package: nil, - Summary: nil, - Metadata: nil}) - } - } - } - return c.JSON(http.StatusOK, sumMI) -} - // @ID GetMonthlyInfo // @Tags public_api // @Description Busca um dado mensal de um órgão diff --git a/uiapi/handlers.go b/uiapi/handlers.go index 9ffe5ae..b6a0526 100644 --- a/uiapi/handlers.go +++ b/uiapi/handlers.go @@ -49,37 +49,6 @@ func NewHandler(client *storage.Client, conn *gorm.DB, newrelic *newrelic.Applic }, nil } -// TODO: Remover quando o site tiver migrado para o novo endpoint -func (h handler) GetSummaryOfAgency(c echo.Context) error { - year, err := strconv.Atoi(c.Param("ano")) - if err != nil { - return c.JSON(http.StatusBadRequest, fmt.Sprintf("Parâmetro ano=%d inválido", year)) - } - month, err := strconv.Atoi(c.Param("mes")) - if err != nil { - return c.JSON(http.StatusBadRequest, fmt.Sprintf("Parâmetro mês=%d", month)) - } - agencyName := c.Param("orgao") - agencyMonthlyInfo, agency, err := h.client.GetOMA(month, year, agencyName) - if err != nil { - return c.JSON(http.StatusBadRequest, fmt.Sprintf("Parâmetro ano=%d, mês=%d ou nome do orgão=%s são inválidos", year, month, agencyName)) - } - agencySummary := agencySummary{ - FullName: agency.Name, - TotalWage: agencyMonthlyInfo.Summary.BaseRemuneration.Total, - MaxWage: agencyMonthlyInfo.Summary.BaseRemuneration.Max, - TotalPerks: agencyMonthlyInfo.Summary.OtherRemunerations.Total, - MaxPerk: agencyMonthlyInfo.Summary.OtherRemunerations.Max, - TotalRemuneration: agencyMonthlyInfo.Summary.BaseRemuneration.Total + - agencyMonthlyInfo.Summary.OtherRemunerations.Total, - TotalMembers: agencyMonthlyInfo.Summary.Count, - CrawlingTime: agencyMonthlyInfo.CrawlingTimestamp, - HasNext: time.Date(year, time.Month(month), 1, 0, 0, 0, 0, time.UTC).In(h.loc).Before(time.Now().AddDate(0, 1, 0)), - HasPrevious: time.Date(year, time.Month(month), 1, 0, 0, 0, 0, time.UTC).In(h.loc).After(time.Date(2018, 1, 1, 0, 0, 0, 0, time.UTC).In(h.loc)), - } - return c.JSON(http.StatusOK, agencySummary) -} - // @ID GetSummaryOfAgency // @Tags ui_api // @Description Resume os dados de remuneração mensal de um órgão. @@ -124,47 +93,6 @@ func (h handler) V2GetSummaryOfAgency(c echo.Context) error { return c.JSON(http.StatusOK, agencySummary) } -// TODO: Remover quando o site tiver migrado para o novo endpoint -func (h handler) GetSalaryOfAgencyMonthYear(c echo.Context) error { - month, err := strconv.Atoi(c.Param("mes")) - if err != nil { - return c.JSON(http.StatusBadRequest, fmt.Sprintf("Parâmetro mês=%d", month)) - } - year, err := strconv.Atoi(c.Param("ano")) - if err != nil { - return c.JSON(http.StatusBadRequest, fmt.Sprintf("Parâmetro ano=%d", year)) - } - agencyName := strings.ToLower(c.Param("orgao")) - agencyMonthlyInfo, _, err := h.client.GetOMA(month, year, agencyName) - if err != nil { - log.Printf("[salary agency month year] error getting data for second screen(mes:%d ano:%d, orgao:%s):%q", month, year, agencyName, err) - return c.JSON(http.StatusBadRequest, fmt.Sprintf("Parâmetro ano=%d, mês=%d ou nome do orgão=%s são inválidos", year, month, agencyName)) - } - if agencyMonthlyInfo.ProcInfo.String() != "" { - var newEnv = agencyMonthlyInfo.ProcInfo.Env - for _, omittedField := range h.envOmittedFields { - for i, field := range newEnv { - if strings.Contains(field, omittedField) { - newEnv[i] = omittedField + "= ##omitida##" - break - } - } - } - agencyMonthlyInfo.ProcInfo.Env = newEnv - return c.JSON(http.StatusPartialContent, procInfoResult{ - ProcInfo: agencyMonthlyInfo.ProcInfo, - CrawlingTimestamp: agencyMonthlyInfo.CrawlingTimestamp, - }) - } - return c.JSON(http.StatusOK, dataForChartAtAgencyScreen{ - Members: agencyMonthlyInfo.Summary.IncomeHistogram, - MaxSalary: agencyMonthlyInfo.Summary.BaseRemuneration.Max, - PackageURL: agencyMonthlyInfo.Package.URL, - PackageHash: agencyMonthlyInfo.Package.Hash, - PackageSize: agencyMonthlyInfo.Package.Size, - }) -} - // @ID GetSalaryOfAgencyMonthYear // @Tags ui_api // @Description Busca dados das remunerações mensais de um órgão. @@ -229,65 +157,6 @@ func (h handler) V2GetSalaryOfAgencyMonthYear(c echo.Context) error { }) } -// TODO: Remover quando o site tiver migrado para o novo endpoint -func (h handler) GetTotalsOfAgencyYear(c echo.Context) error { - year, err := strconv.Atoi(c.Param("ano")) - if err != nil { - return c.JSON(http.StatusBadRequest, fmt.Sprintf("Parâmetro ano=%d inválido", year)) - } - aID := c.Param("orgao") - agenciesMonthlyInfo, err := h.client.Db.GetMonthlyInfo([]strModels.Agency{{ID: aID}}, year) - if err != nil { - log.Printf("[totals of agency year] error getting data for first screen(ano:%d, estado:%s):%q", year, aID, err) - return c.JSON(http.StatusBadRequest, fmt.Sprintf("Parâmetro ano=%d ou orgao=%s inválidos", year, aID)) - } - var monthTotalsOfYear []monthTotals - agency, err := h.client.Db.GetAgency(aID) - if err != nil { - log.Printf("[totals of agency year] error getting data for first screen(estado:%s):%q", aID, err) - return c.JSON(http.StatusBadRequest, fmt.Sprintf("Parâmetro orgao=%s inválido", aID)) - } - host := c.Request().Host - agency.URL = fmt.Sprintf("%s/v1/orgao/%s", host, agency.ID) - for _, agencyMonthlyInfo := range agenciesMonthlyInfo[aID] { - if agencyMonthlyInfo.Summary != nil && agencyMonthlyInfo.Summary.BaseRemuneration.Total+agencyMonthlyInfo.Summary.OtherRemunerations.Total > 0 { - monthTotals := monthTotals{Month: agencyMonthlyInfo.Month, - BaseRemuneration: agencyMonthlyInfo.Summary.BaseRemuneration.Total, - OtherRemunerations: agencyMonthlyInfo.Summary.OtherRemunerations.Total, - CrawlingTimestamp: agencyMonthlyInfo.CrawlingTimestamp, - TotalMembers: agencyMonthlyInfo.Summary.Count, - } - monthTotalsOfYear = append(monthTotalsOfYear, monthTotals) - - // The status 4 is a report from crawlers that data is unavailable or malformed. By removing them from the API results, we make sure they are displayed as if there is no data. - } else if agencyMonthlyInfo.ProcInfo.String() != "" && agencyMonthlyInfo.ProcInfo.Status != 4 { - monthTotals := monthTotals{Month: agencyMonthlyInfo.Month, - BaseRemuneration: 0, - OtherRemunerations: 0, - CrawlingTimestamp: agencyMonthlyInfo.CrawlingTimestamp, - Error: &procError{Stdout: agencyMonthlyInfo.ProcInfo.Stdout, Stderr: agencyMonthlyInfo.ProcInfo.Stderr}, - } - monthTotalsOfYear = append(monthTotalsOfYear, monthTotals) - } - } - sort.Slice(monthTotalsOfYear, func(i, j int) bool { - return monthTotalsOfYear[i].Month < monthTotalsOfYear[j].Month - }) - destKey := fmt.Sprintf("%s/datapackage/%s-%d.zip", aID, aID, year) - bkp, _ := h.client.Cloud.GetFile(destKey) - var pkg *strModels.Package - if bkp != nil { - pkg = &strModels.Package{ - AgencyID: &aID, - Year: &year, - Package: *bkp, - } - } - - agencyTotalsYear := agencyTotalsYear{Year: year, Agency: agency, MonthTotals: monthTotalsOfYear, AgencyFullName: agency.Name, SummaryPackage: pkg} - return c.JSON(http.StatusOK, agencyTotalsYear) -} - // @ID GetTotalsOfAgencyYear // @Tags ui_api // @Description Busca os dados de remuneração de um órgão em um ano específico. @@ -388,79 +257,6 @@ func (h handler) V2GetTotalsOfAgencyYear(c echo.Context) error { return c.JSON(http.StatusOK, agencyTotalsYear) } -// TODO: Remover quando o site tiver migrado para o novo endpoint -func (h handler) GetBasicInfoOfType(c echo.Context) error { - yearOfConsult := time.Now().Year() - groupName := c.Param("grupo") - var agencies []strModels.Agency - var err error - var estadual bool - var exists bool - jurisdicao := map[string]string{ - "justica-eleitoral": "Eleitoral", - "ministerios-publicos": "Ministério", - "justica-estadual": "Estadual", - "justica-do-trabalho": "Trabalho", - "justica-federal": "Federal", - "justica-militar": "Militar", - "justica-superior": "Superior", - "conselhos-de-justica": "Conselho", - } - - // Adaptando as URLs do site com o banco de dados - // Primeiro consultamos entre as chaves do mapa. - if jurisdicao[groupName] != "" { - groupName = jurisdicao[groupName] - } else { - // Caso não encontremos entre as chaves, verificamos entre os valores do mapa. - // Isso pois, até a consolidação ser finalizada, o front consulta a api com /Eleitoral, /Trabalho, etc. - for _, value := range jurisdicao { - if groupName == value { - exists = true - break - } - } - // Se a jurisdição não existir no mapa, verificamos se trata-se de um estado - if !exists { - values := map[string]struct{}{"AC": {}, "AL": {}, "AP": {}, "AM": {}, "BA": {}, "CE": {}, "DF": {}, "ES": {}, "GO": {}, "MA": {}, "MT": {}, "MS": {}, "MG": {}, "PA": {}, "PB": {}, "PR": {}, "PE": {}, "PI": {}, "RJ": {}, "RN": {}, "RS": {}, "RO": {}, "RR": {}, "SC": {}, "SP": {}, "SE": {}, "TO": {}} - if _, estadual = values[groupName]; estadual { - exists = true - } - } - // Se o parâmetro dado não for encontrado de forma alguma, retornamos um NOT FOUND (404) - if !exists { - return c.JSON(http.StatusNotFound, fmt.Sprintf("Grupo não encontrado: %s.", groupName)) - } - } - - if estadual { - agencies, err = h.client.GetStateAgencies(groupName) - } else { - agencies, err = h.client.GetOPJ(groupName) - } - if err != nil { - // That happens when there is no information on that year. - log.Printf("[basic info type] first error getting data for first screen(ano:%d, grupo:%s). Going to try again with last year:%q", yearOfConsult, groupName, err) - yearOfConsult = yearOfConsult - 1 - - if estadual { - agencies, err = h.client.GetStateAgencies(groupName) - } else { - agencies, err = h.client.GetOPJ(groupName) - } - if err != nil { - log.Printf("[basic info type] error getting data for first screen(ano:%d, grupo:%s):%q", yearOfConsult, groupName, err) - return c.JSON(http.StatusBadRequest, fmt.Sprintf("Parâmetros ano=%d ou grupo=%s são inválidos", yearOfConsult, groupName)) - } - } - var agenciesBasic []agencyBasic - for k := range agencies { - agenciesBasic = append(agenciesBasic, agencyBasic{Name: agencies[k].ID, FullName: agencies[k].Name, AgencyCategory: agencies[k].Entity}) - } - state := state{Name: c.Param("grupo"), ShortName: "", FlagURL: "", Agency: agenciesBasic} - return c.JSON(http.StatusOK, state) -} - // @ID GetBasicInfoOfType // @Tags ui_api // @Description Busca os órgãos de um determinado grupo. @@ -540,20 +336,6 @@ func (h handler) V2GetBasicInfoOfType(c echo.Context) error { return c.JSON(http.StatusOK, group) } -// TODO: Remover quando o site tiver migrado para o novo endpoint -func (h handler) GetGeneralRemunerationFromYear(c echo.Context) error { - year, err := strconv.Atoi(c.Param("ano")) - if err != nil { - return c.JSON(http.StatusBadRequest, fmt.Sprintf("Parâmetro ano=%d inválido", year)) - } - data, err := h.client.Db.GetGeneralMonthlyInfosFromYear(year) - if err != nil { - fmt.Println("Error searching for monthly info from year: %w", err) - return c.JSON(http.StatusInternalServerError, fmt.Sprintf("Error buscando dados")) - } - return c.JSON(http.StatusOK, data) -} - // @ID GetGeneralRemunerationFromYear // @Tags ui_api // @Description Busca os dados, das remunerações de um ano inteiro, agrupados por mês. @@ -585,43 +367,6 @@ func (h handler) V2GetGeneralRemunerationFromYear(c echo.Context) error { return c.JSON(http.StatusOK, annualRemu) } -// TODO: Remover quando o site tiver migrado para o novo endpoint -func (h handler) GeneralSummaryHandler(c echo.Context) error { - agencies, err := h.client.GetAgenciesCount() - if err != nil { - return c.JSON(http.StatusInternalServerError, fmt.Sprintf("Erro ao contar orgãos: %q", err)) - } - collections, err := h.client.GetNumberOfMonthsCollected() - if err != nil { - return c.JSON(http.StatusInternalServerError, fmt.Sprintf("Erro ao contar registros: %q", err)) - } - fmonth, fyear, err := h.client.Db.GetFirstDateWithMonthlyInfo() - if err != nil { - log.Printf("Error buscando dados - GetFirstDateWithRemunerationRecords: %q", err) - return c.JSON(http.StatusInternalServerError, fmt.Sprintf("Erro buscando primeiro registro de remuneração: %q", err)) - } - fdate := time.Date(fyear, time.Month(fmonth), 2, 0, 0, 0, 0, time.UTC).In(h.loc) - lmonth, lyear, err := h.client.GetLastDateWithMonthlyInfo() - if err != nil { - log.Printf("Error buscando dados - GetLastDateWithRemunerationRecords: %q", err) - return c.JSON(http.StatusInternalServerError, fmt.Sprintf("Erro buscando último registro de remuneração: %q", err)) - } - ldate := time.Date(lyear, time.Month(lmonth), 2, 0, 0, 0, 0, time.UTC).In(h.loc) - remuValue, err := h.client.Db.GetGeneralMonthlyInfo() - if err != nil { - log.Printf("Error buscando dados - GetGeneralRemunerationValue: %q", err) - return c.JSON(http.StatusInternalServerError, fmt.Sprintf("Erro buscando valor total de remuneração: %q", err)) - } - return c.JSON(http.StatusOK, generalTotals{ - AgencyAmount: int(agencies), - MonthlyTotalsAmount: int(collections), - StartDate: fdate, - EndDate: ldate, - RemunerationRecordsCount: int(collections), - GeneralRemunerationValue: remuValue, - }) -} - // @ID GetGeneralSummary // @Tags ui_api // @Description Busca e resume os dados das remunerações de todos os anos @@ -766,7 +511,7 @@ func (h handler) DownloadByUrl(c echo.Context) error { // @Success 200 {object} []annualSummary "Requisição bem sucedida." // @Failure 400 {string} string "Parâmetro orgao inválido" // @Failure 500 {string} string "Algo deu errado ao tentar coletar os dados anuais do orgao" -// @Router /uiapi/v1/orgao/resumo/{orgao} [get] +// @Router /uiapi/v2/orgao/resumo/{orgao} [get] func (h handler) GetAnnualSummary(c echo.Context) error { agencyName := c.Param("orgao") strAgency, err := h.client.Db.GetAgency(agencyName) From 702ba373be944486fe5f14adfe02b66002709b85 Mon Sep 17 00:00:00 2001 From: Joellensilva Date: Fri, 12 May 2023 15:20:09 -0300 Subject: [PATCH 2/2] removendo /v1 --- README.md | 6 +++--- main.go | 2 +- uiapi/uiapi_test.go | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index cb622a4..708ab97 100644 --- a/README.md +++ b/README.md @@ -122,7 +122,7 @@ eb local run ## Testando servidor -Caso a execução tenha sido realizada com sucesso, você pode utilizar o seu cliente de api REST para acessar o servidor local, que está localizado em http://{HOST}:{PORT}/v1/orgaos +Caso a execução tenha sido realizada com sucesso, você pode utilizar o seu cliente de api REST para acessar o servidor local, que está localizado em http://{HOST}:{PORT}/v2/orgaos ## Documentando as rotas da API utilizando o swagger @@ -136,7 +136,7 @@ $ go install github.com/swaggo/swag/cmd/swag@latest Com o binário instalado, podemos iniciar a criação da documentação. -Como exemplo iremos documentar a rota da api `/v1/orgao/:orgao`. Os passos são: +Como exemplo iremos documentar a rota da api `/v2/orgao/:orgao`. Os passos são: ### 1 - Ir até o método chamado pela rota(nesse caso será o `GetAgencyById`) @@ -155,7 +155,7 @@ func (h handler) GetAgencyById(c echo.Context) error { // @Param orgao path string true "ID do órgão. Exemplos: tjal, tjba, mppb." // @Success 200 {object} agency "Requisição bem sucedida." // @Failure 404 {string} string "Órgão não encontrado." -// @Router /v1/orgao/{orgao} [get] +// @Router /v2/orgao/{orgao} [get] func (h handler) GetAgencyById(c echo.Context) error { ... } diff --git a/main.go b/main.go index 2d4adf9..882f5e3 100644 --- a/main.go +++ b/main.go @@ -169,7 +169,7 @@ func main() { } // Return a summary of an agency. This information will be used in the head of the agency page. uiAPIGroup.GET("/v2/orgao/resumo/:orgao/:ano/:mes", uiApiHandler.V2GetSummaryOfAgency) - // TODO: Apagar essa rota (v1) quando o site migrar para a nova rota. + // Return a annual summary of an agency. uiAPIGroup.GET("/v2/orgao/resumo/:orgao", uiApiHandler.GetAnnualSummary) // Return all the salary of a month and year. This will be used in the point chart at the entity page. uiAPIGroup.GET("/v2/orgao/salario/:orgao/:ano/:mes", uiApiHandler.V2GetSalaryOfAgencyMonthYear) diff --git a/uiapi/uiapi_test.go b/uiapi/uiapi_test.go index df74b0e..08d15f2 100644 --- a/uiapi/uiapi_test.go +++ b/uiapi/uiapi_test.go @@ -1438,7 +1438,7 @@ func (g getAnnualSummary) testWhenAgencyDoesNotHaveData(t *testing.T) { e := echo.New() request := httptest.NewRequest( http.MethodGet, - "/uiapi/v1/orgao/resumo/:orgao", + "/uiapi/v2/orgao/resumo/:orgao", nil, ) recorder := httptest.NewRecorder()