Skip to content

Commit 63239fd

Browse files
Deleting when document is synced
1 parent 7bc0f54 commit 63239fd

2 files changed

Lines changed: 19 additions & 6 deletions

File tree

application/core/documents/src/commonMain/kotlin/io/writeopia/core/folders/sync/DocumentConflictHandler.kt

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -26,13 +26,26 @@ class DocumentConflictHandler(
2626
externalDocuments: List<Document>
2727
): List<Document> {
2828
val now = Clock.System.now()
29-
// Todo: Implement!! Save external documents and remove localDocuments. A more complex
30-
// handling of conflicts can be implemented in the future.
31-
externalDocuments.forEach { document ->
32-
documentRepository.saveDocument(document.copy(lastSyncedAt = now))
29+
30+
val allDocumentsById = (localDocuments + externalDocuments).groupBy { it.id }
31+
32+
// Resolve conflicts for each document ID.
33+
val resolvedDocuments = allDocumentsById.map { (_, documents) ->
34+
// Select the document with the newest lastUpdatedAt
35+
val winner = documents.maxByOrNull { it.lastUpdatedAt }
36+
?: throw IllegalStateException("Document list for ID cannot be empty.")
37+
38+
// Mark the winner as synced (or keep existing lastSyncedAt if it's external and already set)
39+
winner.copy(lastSyncedAt = now)
40+
}
41+
42+
// Save the resolved (winning and synced) documents to the repository.
43+
resolvedDocuments.forEach { document ->
44+
documentRepository.saveDocument(document)
3345
}
3446

35-
return (localDocuments.toSet() - externalDocuments.toSet()).toList()
47+
// Determine which documents to return.
48+
return resolvedDocuments
3649
}
3750

3851
suspend fun handleConflictForFolders(

backend/core/database/src/main/sqldelight/io/writeopia/sql/DocumentEntity.sq

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ selectWithContentByWorkspaceIdAfterTime:
8989
SELECT *
9090
FROM document_entity
9191
LEFT JOIN story_step_entity ON document_entity.id=story_step_entity.document_id
92-
WHERE last_synced > ? AND workspace_id = ? AND deleted = FALSE
92+
WHERE last_synced > ? AND workspace_id = ?
9393
ORDER BY position;
9494

9595
selectWithContentById:

0 commit comments

Comments
 (0)