diff --git a/main.go b/main.go index 6d6c58f..3a4fbd0 100644 --- a/main.go +++ b/main.go @@ -135,10 +135,9 @@ func fetchAndConvertXMLToJSON(apiURL string, outputDir string, fileName string, } // Function to read JSON data from a file -// Function to read JSON data from a file -func readJSONFromFile(folderName, kpiName string) ([]map[string]interface{}, error) { +func readJSONFromFile(folderName, fileName string) ([]map[string]interface{}, error) { // Construct the file path dynamically using the folder name - filePath := fmt.Sprintf("%s/%s.json", folderName, kpiName) + filePath := fmt.Sprintf("%s/%s.json", folderName, fileName) // Read and return the JSON content from the file fileContent, err := ioutil.ReadFile(filePath) @@ -264,6 +263,74 @@ func fetchfilterJSON(dataset string) ([]FilterGroup, error) { return filters, nil } +// LanguageSource represents the source language data structure +type LanguageSource struct { + Dataset string `json:"dataset"` + Key string `json:"key"` + Value string `json:"value"` + ValueEn string `json:"value_en"` + ValueAr string `json:"value_ar"` +} + +func TranslateFilters(app *pocketbase.PocketBase, dataset string, filterGroups []FilterGroup, langKey string) ([]FilterGroup, error) { + // Fetch source data from the PocketBase collection + param := dbx.NewExp("dataset = {:dataset}", dbx.Params{"dataset": dataset}) + records, err := app.Dao().FindRecordsByExpr("charts_variables", param) + if err != nil { + return nil, fmt.Errorf("failed to fetch source data: %w", err) + } + + // Parse the source data into a slice of LanguageSource + var sourceData []LanguageSource + for _, record := range records { + source := LanguageSource{ + Dataset: record.GetString("dataset"), + Key: record.GetString("key"), + Value: record.GetString("value"), + ValueEn: record.GetString("value_en"), + ValueAr: record.GetString("value_ar"), + } + sourceData = append(sourceData, source) + } + + // Create a map for quick lookup of translations + translationMap := make(map[string]string) + for _, source := range sourceData { + var value string + switch langKey { + case "value_en": + value = source.ValueEn + case "value_ar": + value = source.ValueAr + default: + continue + } + translationMap[source.Value] = value + } + + // Translate the filter data + for i, filter := range filterGroups { + if filter.FilterKey == "TIME_PERIOD" { + // Skip translation for TIME_PERIOD + continue + } + for j, v := range filter.FilterData { + // Type assertion for interface{} to string + value, ok := v.(string) + if !ok { + return nil, fmt.Errorf("unexpected type for filter data: %v", v) + } + + // Translate the value if it exists in the map + if translatedValue, exists := translationMap[value]; exists { + filterGroups[i].FilterData[j] = translatedValue + } + } + } + + return filterGroups, nil +} + var app *pocketbase.PocketBase func main() { @@ -827,21 +894,15 @@ func main() { // Define the struct for the expected result type Chart struct { - ID string `json:"id"` - ChartType string `json:"chart_type"` - Dataset string `json:"dataset"` - Filter string `json:"filter"` - KPI string `json:"kpi"` - MainID string `json:"main_id"` - SubID string `json:"sub_id"` - URL string `json:"url"` - IsChart bool `json:"is_chart"` - Created string `json:"created"` - Updated string `json:"updated"` + Dataset string `json:"dataset"` + Key string `json:"key"` + Value string `json:"value"` + ValueEn string `json:"value_en"` + ValueAr string `json:"value_ar"` } // Query to fetch the data - sqlQuery := "SELECT * FROM charts" + sqlQuery := "SELECT * FROM charts_variables" var results []Chart // Execute the query @@ -869,22 +930,32 @@ func main() { } // Fetch all matching records manually - // Construct the dbx.Expression filter := dbx.NewExp("dataset = {:dataset}", dbx.Params{"dataset": dataset}) records, err := app.Dao().FindRecordsByExpr("charts", filter) if err != nil { log.Printf("Failed to fetch records for dataset '%s': %v", dataset, err) return c.JSON(http.StatusInternalServerError, map[string]string{"error": "Failed to fetch records"}) } - if len(records) == 0 { return c.JSON(http.StatusNotFound, map[string]string{"error": "No records found for the given dataset"}) } var aggregatedResponse []map[string]interface{} + // param := dbx.NewExp("dataset = {:dataset}", dbx.Params{"dataset": dataset}) + // languageSourceRaw, err := app.Dao().FindRecordsByExpr("charts_variables", param) + // if err != nil { + // log.Printf("Failed to fetch language source: %v", err) + // } + filterData, err := fetchfilterJSON(dataset) + // Translate filter data using the desired dataset and language key + // fRes, err := TranslateFilters(app, dataset, filterData, "value_en") + // if err != nil { + // log.Fatalf("Error translating filters: %v", err) + // } + for _, record := range records { // Extract the URL for each record apiURL := record.GetString("url") @@ -909,7 +980,6 @@ func main() { response, err := readJSONFromFile("kpi_files", kpi) if err != nil { log.Printf("Failed to read JSON for KPI '%s': %v", kpi, err) - continue // Skip this record and proceed with others } // Prepare the structure with URL and its response @@ -974,6 +1044,73 @@ func main() { // Final result structure result := []map[string]interface{}{} + // Loop through main topics and fetch sub-topic data for each + for _, mainTopic := range mainTopics { + + dataSets := []struct { + DataSet string `db:"data_set" json:"data_set"` + DataSetTileHeading string `db:"data_set_tile_heading" json:"data_set_tile_heading"` + ValueSource string `db:"value_source" json:"value_source"` + Value string `db:"value" json:"value"` + DataSetListOrder string `db:"data_set_list_order" json:"data_set_list_order"` + }{} + + // Query to get data-set for the current sub topic + err := app.DB(). + Select("data_set", "data_set_tile_heading", "value_source", "value", "data_set_list_order"). + From("home_screen"). + Where(dbx.HashExp{"show_in_home_page": 1}). + OrderBy("data_set_list_order ASC"). + All(&dataSets) + + if err != nil { + continue + } + + // Add the main topic and its sub-topics to the result + result = append(result, map[string]interface{}{ + "main_topic": mainTopic.MainTopic, + "main_topic_list_order": mainTopic.MainTopicListOrder, + "color_pattern": mainTopic.ColorPattern, + "tile_data": dataSets, + }) + } + + // Send the combined result as JSON + return c.JSON(http.StatusOK, result) + + }) + + e.Router.GET("/api/getUAENumbersData", func(c echo.Context) error { + + // Define the struct for holding the query results + mainTopics := []struct { + MainTopic string `db:"main_topic" json:"main_topic"` + MainTopicListOrder string `db:"main_topic_list_order" json:"main_topic_list_order"` + ColorPattern string `db:"color_pattern" json:"color_pattern"` + }{} + + // Execute the query + err := app.DB(). + Select("main_topic", "main_topic_list_order", "color_pattern"). + From("home_screen"). + GroupBy("main_topic", "color_pattern"). + OrderBy("main_topic_list_order ASC"). + All(&mainTopics) + + if err != nil { + log.Printf("Failed to fetch home_screen data: %v", err) + return c.JSON(http.StatusInternalServerError, map[string]string{"error": "Failed to fetch records"}) + } + + // If no records are found + if len(mainTopics) == 0 { + return c.JSON(http.StatusNotFound, map[string]string{"error": "No records found for home screen"}) + } + + // Final result structure + result := []map[string]interface{}{} + // Loop through main topics and fetch sub-topic data for each for _, mainTopic := range mainTopics { subTopics := []struct {