Skip to content

Commit f6548fa

Browse files
committed
Sync local only tasks & subtask in proper order to preserve hierarchy & sorting
1 parent 50c25a5 commit f6548fa

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
@@ -310,20 +310,41 @@ class TaskRepository(
310310
taskDao.upsert(remoteTask.asTaskEntity(localListId, existingEntity?.id, parentTaskEntity?.id))
311311
}
312312
taskDao.deleteStaleTasks(localListId, remoteTasks.map(Task::id))
313-
taskDao.getLocalOnlyTasks(localListId).onEach { localTask ->
314-
val remoteTask = withContext(Dispatchers.IO) {
315-
try {
316-
tasksApi.insert(remoteListId, localTask.asTask())
317-
} catch (_: Exception) {
318-
null
319-
}
320-
}
321-
if (remoteTask != null) {
322-
val parentTaskEntity = remoteTask.parent?.let { taskDao.getByRemoteId(it) }
323-
taskDao.upsert(remoteTask.asTaskEntity(localListId, localTask.id, parentTaskEntity?.id))
313+
val localOnlyTasks = taskDao.getLocalOnlyTasks(localListId)
314+
val sortedRootTasks = computeTaskPositions(localOnlyTasks.filter { it.parentTaskLocalId == null })
315+
var previousTaskId: String? = null
316+
sortedRootTasks.onEach { localRootTask ->
317+
val remoteTask = syncLocalTask(localListId, remoteListId, localRootTask, null, previousTaskId)
318+
val sortedSubTasks = computeTaskPositions(localOnlyTasks.filter { it.parentTaskLocalId == localRootTask.id })
319+
var previousSubTaskId: String? = null
320+
sortedSubTasks.onEach { localSubTask ->
321+
val remoteSubTask = syncLocalTask(localListId, remoteListId, localSubTask, remoteTask?.id, previousSubTaskId)
322+
previousSubTaskId = remoteSubTask?.id
324323
}
324+
previousTaskId = remoteTask?.id
325+
}
326+
}
327+
}
328+
329+
private suspend fun syncLocalTask(
330+
localTaskListId: Long,
331+
remoteTaskListId: String,
332+
localTask: TaskEntity,
333+
parentTaskId: String?,
334+
previousTaskId: String?
335+
): Task? {
336+
val remoteTask = withContext(Dispatchers.IO) {
337+
try {
338+
tasksApi.insert(remoteTaskListId, localTask.asTask(), parentTaskId, previousTaskId)
339+
} catch (_: Exception) {
340+
null
325341
}
326342
}
343+
if (remoteTask != null) {
344+
val parentTaskEntity = remoteTask.parent?.let { taskDao.getByRemoteId(it) }
345+
taskDao.upsert(remoteTask.asTaskEntity(localTaskListId, localTask.id, parentTaskEntity?.id))
346+
}
347+
return remoteTask
327348
}
328349

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

0 commit comments

Comments
 (0)