Update SortOrder on bookmarks in the group when a bookmark is moved

This commit is contained in:
Neil Brommer 2022-05-12 14:44:26 -07:00
parent 196a592c47
commit 3bd02f839e

View file

@ -44,8 +44,11 @@ namespace Start.Server.Data.Services {
}
public async Task<Bookmark?> 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<Bookmark>? oldGroupBookmarks = await db.Bookmarks
.Where(b => b.BookmarkGroupId == existingBookmark.BookmarkGroupId)
.Where(b => b.SortOrder > existingBookmark.SortOrder)
.ToListAsync();
oldGroupBookmarks.ForEach(b => b.SortOrder -= 1);
List<Bookmark>? 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<Bookmark>? 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();