package nocodb import ( "encoding/json" "fmt" "io" "net/http" "net/url" "clintonambulance.com/calculate_negative_points/internal/config" ) type NocoDBRecord struct { ID int `json:"ID"` Name string `json:"Name"` } // NocoDBResponse represents the API response structure type NocoDBResponse struct { List []NocoDBRecord `json:"list"` PageInfo struct { TotalRows int `json:"totalRows"` Page int `json:"page"` PageSize int `json:"pageSize"` IsFirstPage bool `json:"isFirstPage"` IsLastPage bool `json:"isLastPage"` } `json:"pageInfo"` } type NocoDBRequest struct { EmployeeId int `json:"Employees_id"` ReportedBy int `json:"Employees_id1"` InfractionId int `json:"Infractions_id"` Date string `json:"Date"` } func NoPointsUrl(config *config.ApplicationConfig) string { combinedUrl, _ := url.JoinPath(config.NocoDBConfig.BaseUrl, "api/v2/tables", config.NocoDBConfig.EmployeesTableId, "records") return fmt.Sprintf("%s?viewId=%s", combinedUrl, config.NocoDBConfig.NoPointsViewId) } func AddInfractionsUrl(config *config.ApplicationConfig) string { combinedUrl, _ := url.JoinPath(config.NocoDBConfig.BaseUrl, "api/v2/tables", config.NocoDBConfig.InfractionsTableId, "records") return combinedUrl } func Fetch(config *config.ApplicationConfig) ([]NocoDBRecord, error) { records := []NocoDBRecord{} offset := 0 limit := 25 isLastPage := false baseURL := NoPointsUrl(config) for !isLastPage { // Create HTTP request with base URL req, err := http.NewRequest("GET", baseURL, nil) if err != nil { return nil, fmt.Errorf("failed to create request: %w", err) } // Set query params via the request's URL q := req.URL.Query() q.Set("offset", fmt.Sprintf("%d", offset)) q.Set("limit", fmt.Sprintf("%d", limit)) req.URL.RawQuery = q.Encode() // Add authorization header req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", config.NocoDBConfig.ApiToken.Value())) req.Header.Set("Content-Type", "application/json") // Make the request client := &http.Client{} resp, err := client.Do(req) if err != nil { return nil, fmt.Errorf("failed to fetch data from API: %w", err) } defer resp.Body.Close() // Check response status if resp.StatusCode != http.StatusOK { body, _ := io.ReadAll(resp.Body) return nil, fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, string(body)) } // Read and parse response body, err := io.ReadAll(resp.Body) if err != nil { return nil, fmt.Errorf("failed to read response body: %w", err) } var nocoDBResp NocoDBResponse if err := json.Unmarshal(body, &nocoDBResp); err != nil { return nil, fmt.Errorf("failed to parse JSON response: %w", err) } // Extract names from records records = append(records, nocoDBResp.List...) // Check if we've reached the last page isLastPage = nocoDBResp.PageInfo.IsLastPage // Update offset for next page offset += limit } return records, nil }