diff --git a/backend-go/internal/controller/lost.go b/backend-go/internal/controller/lost.go index 542625c8..fead37d9 100644 --- a/backend-go/internal/controller/lost.go +++ b/backend-go/internal/controller/lost.go @@ -5,7 +5,9 @@ import ( "fmt" "net/http" "os" + "sort" "strconv" + "time" "github.com/LambdaIITH/Dashboard/backend/config" lost "github.com/LambdaIITH/Dashboard/backend/internal/db" @@ -133,6 +135,83 @@ func GetAllItemsHandler(c *gin.Context) { c.JSON(http.StatusOK, response) } +/* +GetCombinedAllItemsHandler fetches all the lost and found items and returns them as a JSON response ordered by creation time. +*/ +func GetCombinedAllItemsHandler(c *gin.Context) { + + maxLimit := 100 + if limitStr := c.Query("max_limit"); limitStr != "" { + if limit, err := strconv.Atoi(limitStr); err == nil { + maxLimit = limit + } + } + + //Step 1: Fetching lost items AND found items + lostItems, err := lost.GetAllLostItems(c) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to fetch items"}) + + return + } + + + foundItems, err := lost.GetAllFoundItems(c) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to fetch items"}) + return + } + + + + //Step 2: Initialize response slice + response := make([]map[string]any, 0, len(lostItems)+len(foundItems)) + + for _, item := range lostItems { + images := item.Images + if images == nil { + images = []string{} + } + + itemData := map[string]any{ + "id": item.ID, + "name": item.ItemName, + "images": images, + "created_at": item.CreatedAt, + "type": "lost", + } + response = append(response, itemData) + } + for _, item := range foundItems { + images := item.Images + if images == nil { + images = []string{} + } + + itemData := map[string]any{ + "id": item.ID, + "name": item.ItemName, + "images": images, + "created_at": item.CreatedAt, + "type": "found", + } + response = append(response, itemData) + } + + sort.Slice(response, func(i, j int) bool { + t1 := response[i]["created_at"].(time.Time) + t2 := response[j]["created_at"].(time.Time) + return t1.After(t2) // newest first + }) + + if len(response) > maxLimit { + response = response[:maxLimit] + } + + // Step 4: Return the response + c.JSON(http.StatusOK, response) +} + /* GetItemByIdHandler fetches a particular lost item by its ID and returns it as a JSON response. */ diff --git a/backend-go/internal/router/routes.go b/backend-go/internal/router/routes.go index a15335c2..7d6dedc7 100644 --- a/backend-go/internal/router/routes.go +++ b/backend-go/internal/router/routes.go @@ -77,6 +77,12 @@ func SetupRoutes(router *gin.Engine) { foundGroup.GET("/search", controller.SearchFoundItemHandler) } + //Group routes for lost-found items + lostFoundGroup := router.Group("/lost_found") + { + lostFoundGroup.GET("/", controller.GetCombinedAllItemsHandler) //optional parameter max_limit + } + //Group routes for timetable/calendar timetableGroup := router.Group("/schedule") {