Skip to content

Commit 5ed62c1

Browse files
committed
Sync local only tasks & subtask in proper order to preserve hierarchy & sorting
1 parent 7d9937f commit 5ed62c1

1 file changed

Lines changed: 32 additions & 11 deletions

File tree

tasks-core/src/commonMain/kotlin/net/opatry/tasks/data/TaskRepository.kt

Lines changed: 32 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -226,8 +226,8 @@ class TaskRepository(
226226
entries.map { (list, tasks) ->
227227
// FIXME Where should happen the sorting, on SQL side or here or in UI layer?
228228
list.asTaskListDataModel(tasks)
229+
}
229230
}
230-
}
231231

232232
suspend fun sync() {
233233
val taskListIds = mutableMapOf<Long, String>()
@@ -281,19 +281,40 @@ class TaskRepository(
281281
taskDao.upsert(remoteTask.asTaskEntity(localListId, existingEntity?.id))
282282
}
283283
taskDao.deleteStaleTasks(localListId, remoteTasks.map(Task::id))
284-
taskDao.getLocalOnlyTasks(localListId).onEach { localTask ->
285-
val remoteTask = withContext(Dispatchers.IO) {
286-
try {
287-
tasksApi.insert(remoteListId, localTask.asTask())
288-
} catch (e: Exception) {
289-
null
290-
}
291-
}
292-
if (remoteTask != null) {
293-
taskDao.upsert(remoteTask.asTaskEntity(localListId, localTask.id))
284+
val localOnlyTasks = taskDao.getLocalOnlyTasks(localListId)
285+
val sortedRootTasks = computeTaskPositions(localOnlyTasks.filter { it.parentTaskLocalId == null })
286+
var previousTaskId: String? = null
287+
sortedRootTasks.onEach { localRootTask ->
288+
val remoteTask = syncLocalTask(localListId, remoteListId, localRootTask, null, previousTaskId)
289+
val sortedSubTasks = computeTaskPositions(localOnlyTasks.filter { it.parentTaskLocalId == localRootTask.id })
290+
var previousSubTaskId: String? = null
291+
sortedSubTasks.onEach { localSubTask ->
292+
val remoteSubTask = syncLocalTask(localListId, remoteListId, localSubTask, remoteTask?.id, previousSubTaskId)
293+
previousSubTaskId = remoteSubTask?.id
294294
}
295+
previousTaskId = remoteTask?.id
296+
}
297+
}
298+
}
299+
300+
private suspend fun syncLocalTask(
301+
localTaskListId: Long,
302+
remoteTaskListId: String,
303+
localTask: TaskEntity,
304+
parentTaskId: String?,
305+
previousTaskId: String?
306+
): Task? {
307+
val remoteTask = withContext(Dispatchers.IO) {
308+
try {
309+
tasksApi.insert(remoteTaskListId, localTask.asTask(), parentTaskId, previousTaskId)
310+
} catch (e: Exception) {
311+
null
295312
}
296313
}
314+
if (remoteTask != null) {
315+
taskDao.upsert(remoteTask.asTaskEntity(localTaskListId, localTask.id))
316+
}
317+
return remoteTask
297318
}
298319

299320
suspend fun createTaskList(title: String) {

0 commit comments

Comments
 (0)