From db7909f25d14147eaeab34ea566c3c05e9a249a4 Mon Sep 17 00:00:00 2001 From: aminecmi Date: Sun, 17 Jul 2022 21:46:43 +0200 Subject: [PATCH] All sorting issues should be fixed. --- src/main/kotlin/dao/DB.kt | 49 ++++++++++++++++++++++++++++----------- 1 file changed, 36 insertions(+), 13 deletions(-) diff --git a/src/main/kotlin/dao/DB.kt b/src/main/kotlin/dao/DB.kt index d832fce..86b4cce 100644 --- a/src/main/kotlin/dao/DB.kt +++ b/src/main/kotlin/dao/DB.kt @@ -81,15 +81,24 @@ class DB { fun createItem(listId: Int, c: ItemView, ctx: Context) { transaction { + val allITems = Item.find { Items.list eq listId }.sortedBy { it.position } + val firstChecked = allITems.firstOrNull { it.checked } + val p = if (firstChecked != null) { + firstChecked?.position + } else { + (allITems.lastOrNull()?.position ?: - 1) + 1 + } val listOpt = List.findById(listId) if (listOpt != null) { + reorderElements(listId, p) + var i = Item.new { list = listId content = c.content - position = Item.all().count().toInt() + position = p checked = false } - + ctx.json(i.toView()) } else { ctx.status(404) @@ -98,6 +107,21 @@ class DB { } + private fun reorderElements(listId: Int, position: Int, itemId: Int? = null) { + transaction { + var i = 0 + Item.find { Items.list eq listId and (Items.id neq itemId) } + .sortedBy { it.position } + .forEach { + if (i == position) { + i++ + } + it.position = i + i++ + } + } + } + fun deleteItem(listId: Int, itemId: Int, ctx: Context) { transaction { val listOpt = List.findById(listId) @@ -131,21 +155,20 @@ class DB { if (body.checked != null) { val allITems = Item.find { Items.list eq listId }.sortedBy { it.position } val firstChecked = allITems.firstOrNull { it.checked } - p = firstChecked?.position ?: allITems.lastOrNull()?.position + p = if (body.checked) { + if (firstChecked != null) { + firstChecked.position - 1 + } else { + allITems.lastOrNull()?.position + } + } else { + firstChecked?.position ?: allITems.lastOrNull()?.position + } item?.checked = body.checked } if (p != null) { - var i = 0 - Item.find { Items.list eq listId and (Items.id neq itemId) } - .sortedBy { it.position } - .forEach { - if (i == p) { - i++ - } - it.position = i - i++ - } + reorderElements(listId, p, itemId) item?.position = p } if (body.content != null) {