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();