From 3bd02f839e3936192a55d8b066b4d525b1c0def5 Mon Sep 17 00:00:00 2001 From: Neil Brommer Date: Thu, 12 May 2022 14:44:26 -0700 Subject: [PATCH] Update SortOrder on bookmarks in the group when a bookmark is moved --- Start/Server/Data/Services/BookmarkService.cs | 42 ++++++++++++++++++- 1 file changed, 40 insertions(+), 2 deletions(-) diff --git a/Start/Server/Data/Services/BookmarkService.cs b/Start/Server/Data/Services/BookmarkService.cs index e2e9b19..e6a716c 100644 --- a/Start/Server/Data/Services/BookmarkService.cs +++ b/Start/Server/Data/Services/BookmarkService.cs @@ -44,8 +44,11 @@ namespace Start.Server.Data.Services { } public async Task UpdateBookmark(string userId, Bookmark bookmark) { - Bookmark? existingBookmark = db.Bookmarks - .SingleOrDefault(b => b.BookmarkId == bookmark.BookmarkId); + Bookmark? existingBookmark = await db.Bookmarks + .SingleOrDefaultAsync(b => b.BookmarkId == bookmark.BookmarkId); + + if (existingBookmark == null) + return null; if (!BookmarkOwnershipTools.IsBookmarkOwner(this.db, userId, bookmark.BookmarkId)) return null; @@ -55,6 +58,41 @@ namespace Start.Server.Data.Services { .IsBookmarkGroupOwner(this.db, userId, bookmark.BookmarkGroupId)) return null; + if (bookmark.BookmarkGroupId != existingBookmark.BookmarkGroupId) { + // The bookmark was moved to a different group - shuffle sort order around + List? oldGroupBookmarks = await db.Bookmarks + .Where(b => b.BookmarkGroupId == existingBookmark.BookmarkGroupId) + .Where(b => b.SortOrder > existingBookmark.SortOrder) + .ToListAsync(); + + oldGroupBookmarks.ForEach(b => b.SortOrder -= 1); + + List? newGroupBookmarks = await db.Bookmarks + .Where(b => b.BookmarkGroupId == bookmark.BookmarkGroupId) + .Where(b => b.SortOrder >= bookmark.SortOrder) + .ToListAsync(); + + newGroupBookmarks.ForEach(b => b.SortOrder += 1); + } + else if (bookmark.SortOrder != existingBookmark.SortOrder) { + // The bookmark has been moved within the same group + + List? groupBookmarks = await db.Bookmarks + .Where(b => b.BookmarkGroupId == bookmark.BookmarkGroupId) + .Where(b => b.BookmarkId != bookmark.BookmarkId) + .ToListAsync(); + + groupBookmarks + .Where(b => b.SortOrder > existingBookmark.SortOrder) + .ToList() + .ForEach(b => b.SortOrder -=1); + + groupBookmarks + .Where(b => b.SortOrder > bookmark.SortOrder) + .ToList() + .ForEach(b => b.SortOrder += 1); + } + db.Entry(bookmark).State = EntityState.Modified; await db.SaveChangesAsync();