Skip to content

Commit 7d0ad42

Browse files
committed
Sync local only tasks & subtask in proper order to preserve hierarchy & sorting
1 parent 051f3d5 commit 7d0ad42

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
@@ -325,20 +325,41 @@ class TaskRepository(
325325
taskDao.upsert(remoteTask.asTaskEntity(localListId, existingEntity?.id, parentTaskEntity?.id))
326326
}
327327
taskDao.deleteStaleTasks(localListId, remoteTasks.map(Task::id))
328-
taskDao.getLocalOnlyTasks(localListId).onEach { localTask ->
329-
val remoteTask = withContext(Dispatchers.IO) {
330-
try {
331-
tasksApi.insert(remoteListId, localTask.asTask())
332-
} catch (_: Exception) {
333-
null
334-
}
335-
}
336-
if (remoteTask != null) {
337-
val parentTaskEntity = remoteTask.parent?.let { taskDao.getByRemoteId(it) }
338-
taskDao.upsert(remoteTask.asTaskEntity(localListId, localTask.id, parentTaskEntity?.id))
328+
val localOnlyTasks = taskDao.getLocalOnlyTasks(localListId)
329+
val sortedRootTasks = computeTaskPositions(localOnlyTasks.filter { it.parentTaskLocalId == null })
330+
var previousTaskId: String? = null
331+
sortedRootTasks.onEach { localRootTask ->
332+
val remoteTask = syncLocalTask(localListId, remoteListId, localRootTask, null, previousTaskId)
333+
val sortedSubTasks = computeTaskPositions(localOnlyTasks.filter { it.parentTaskLocalId == localRootTask.id })
334+
var previousSubTaskId: String? = null
335+
sortedSubTasks.onEach { localSubTask ->
336+
val remoteSubTask = syncLocalTask(localListId, remoteListId, localSubTask, remoteTask?.id, previousSubTaskId)
337+
previousSubTaskId = remoteSubTask?.id
339338
}
339+
previousTaskId = remoteTask?.id
340+
}
341+
}
342+
}
343+
344+
private suspend fun syncLocalTask(
345+
localTaskListId: Long,
346+
remoteTaskListId: String,
347+
localTask: TaskEntity,
348+
parentTaskId: String?,
349+
previousTaskId: String?
350+
): Task? {
351+
val remoteTask = withContext(Dispatchers.IO) {
352+
try {
353+
tasksApi.insert(remoteTaskListId, localTask.asTask(), parentTaskId, previousTaskId)
354+
} catch (_: Exception) {
355+
null
340356
}
341357
}
358+
if (remoteTask != null) {
359+
val parentTaskEntity = remoteTask.parent?.let { taskDao.getByRemoteId(it) }
360+
taskDao.upsert(remoteTask.asTaskEntity(localTaskListId, localTask.id, parentTaskEntity?.id))
361+
}
362+
return remoteTask
342363
}
343364

344365
suspend fun createTaskList(title: String): Long {

0 commit comments

Comments
 (0)