From 83c57ed9e6a0fc544ee516003750d55ed5b1fef9 Mon Sep 17 00:00:00 2001 From: zebrapurring <103900164+zebrapurring@users.noreply.github.com> Date: Fri, 13 Dec 2024 02:47:40 +0100 Subject: [PATCH] fix: sorting for completed and scheduled maintenance entries (#384) * fix: sorting for completed and scheduled maintenance entries * Completed entries are sorted by descending completion date * Scheduled entries are sorted by ascending scheduling date * Selecting both entries shall sort them by scheduling and then completion date in descending order * refactor: rewrite if-else as switch-case --------- Co-authored-by: zebrapurring <> --- .../data/repo/repo_maintenance_entry.go | 22 ++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/backend/internal/data/repo/repo_maintenance_entry.go b/backend/internal/data/repo/repo_maintenance_entry.go index b3e98349e..ed3a06c4f 100644 --- a/backend/internal/data/repo/repo_maintenance_entry.go +++ b/backend/internal/data/repo/repo_maintenance_entry.go @@ -5,6 +5,7 @@ import ( "errors" "time" + "entgo.io/ent/dialect/sql" "github.com/google/uuid" "github.com/sysadminsmedia/homebox/backend/internal/data/ent" "github.com/sysadminsmedia/homebox/backend/internal/data/ent/group" @@ -130,21 +131,36 @@ func (r *MaintenanceEntryRepository) GetMaintenanceByItemID(ctx context.Context, item.HasGroupWith(group.IDEQ(groupID)), ), ) - if filters.Status == MaintenanceFilterStatusScheduled { + switch filters.Status { + case MaintenanceFilterStatusScheduled: query = query.Where(maintenanceentry.Or( maintenanceentry.DateIsNil(), maintenanceentry.DateEQ(time.Time{}), maintenanceentry.DateGT(time.Now()), )) - } else if filters.Status == MaintenanceFilterStatusCompleted { + // Sort scheduled entries by ascending scheduled date + query = query.Order( + maintenanceentry.ByScheduledDate(sql.OrderAsc()), + ) + case MaintenanceFilterStatusCompleted: query = query.Where( maintenanceentry.Not(maintenanceentry.Or( maintenanceentry.DateIsNil(), maintenanceentry.DateEQ(time.Time{}), maintenanceentry.DateGT(time.Now()), ))) + // Sort completed entries by descending completion date + query = query.Order( + maintenanceentry.ByDate(sql.OrderDesc()), + ) + default: + // Sort entries by default by scheduled and maintenance date in descending order + query = query.Order( + maintenanceentry.ByScheduledDate(sql.OrderDesc()), + maintenanceentry.ByDate(sql.OrderDesc()), + ) } - entries, err := query.WithItem().Order(maintenanceentry.ByScheduledDate()).All(ctx) + entries, err := query.WithItem().All(ctx) if err != nil { return []MaintenanceEntryWithDetails{}, err