@@ -98,6 +98,16 @@ data class InboundStats(
9898 val updated : Int = 0
9999) {
100100 val total: Int get() = imported + updated
101+
102+ operator fun plus (o : InboundStats ) = InboundStats (imported + o.imported, updated + o.updated)
103+ }
104+
105+ /* * What a manual sync did in both directions: [exported] to the backend, [imported] from it. */
106+ data class FullSyncStats (
107+ val exported : ReconcileStats = ReconcileStats (),
108+ val imported : InboundStats = InboundStats ()
109+ ) {
110+ operator fun plus (o : FullSyncStats ) = FullSyncStats (exported + o.exported, imported + o.imported)
101111}
102112
103113/* *
@@ -171,6 +181,16 @@ abstract class ServiceInterface (
171181 /* * Whether this backend can pull data INTO openScale (bidirectional). HealthConnect/Wger = true. */
172182 open val supportsInbound: Boolean get() = false
173183
184+ /* *
185+ * Whether measurements imported from this backend are still exported back to it. True wherever
186+ * writing back is harmless: Wger patches the entry the measurement came from, and MQTT reads
187+ * `<base>/inbound/…` but publishes openScale's complete state, which consumers expect to include
188+ * imported values — so an edit made in openScale reaches the source too. False where it is not:
189+ * Health Connect lets no app change another app's record, so writing back only adds a copy of
190+ * ours next to the original.
191+ */
192+ open val exportsImported: Boolean get() = true
193+
174194 /* * Outbound active unless the user set this backend to import-only. */
175195 fun exportEnabled (): Boolean = viewModel().syncDirection.value != SyncDirection .IMPORT
176196
@@ -185,13 +205,29 @@ abstract class ServiceInterface (
185205 exportEnabled() && (isMultiUser || userId == viewModel().selectedUserId.value)
186206
187207 /* *
188- * Full manual sync of all measurements of the selected user to this backend.
189- * Returns what was actually pushed on success, or null on failure (the error is surfaced via the
190- * error banner). Only call from the UI context where openScaleService/openScaleDataService are
191- * wired.
208+ * Full manual sync with this backend, in the direction the user set for it: import first, then
209+ * export — the order every sync uses, so whatever comes from this backend is known as the
210+ * source's before anything is exported to it (see [isImported]). Returns what was actually
211+ * imported and pushed on success, or null on failure (the error is surfaced via the error
212+ * banner). Only call from the UI context where openScaleService/openScaleDataService are wired.
192213 */
193- suspend fun runFullSync () : ReconcileStats ? {
194- // Multi-user backends sync all users; single-user backends only their selected user.
214+ suspend fun runFullSync () : FullSyncStats ? {
215+ var imported = InboundStats ()
216+ if (importEnabled()) {
217+ when (val r = runInbound(if (isMultiUser) - 1 else viewModel().selectedUserId.value)) {
218+ is SyncResult .Success -> imported = r.data
219+ is SyncResult .Failure -> {
220+ setErrorMessage(r)
221+ return null
222+ }
223+ }
224+ }
225+ if (! exportEnabled()) {
226+ viewModel().setLastSync(Instant .now())
227+ return FullSyncStats (imported = imported)
228+ }
229+ // Read after the import, so what it just added goes out to this backend as well. Multi-user
230+ // backends sync all users; single-user backends only their selected user.
195231 val measurements = try {
196232 val allUsers = openScaleDataService.getUsers()
197233 val users = if (isMultiUser) allUsers else allUsers.filter { it.id == viewModel().selectedUserId.value }
@@ -215,7 +251,7 @@ abstract class ServiceInterface (
215251 return when (result) {
216252 is SyncResult .Success -> {
217253 viewModel().setLastSync(Instant .now())
218- result.data
254+ FullSyncStats ( result.data, imported)
219255 }
220256 is SyncResult .Failure -> {
221257 setErrorMessage(result)
@@ -317,6 +353,12 @@ abstract class ServiceInterface (
317353 skippedNoWeight++
318354 continue
319355 }
356+ // Imported from this very backend: nothing of ours to send. Also stays in currentIds,
357+ // so an earlier echo of it is neither re-pushed nor deleted.
358+ if (isImported(m)) {
359+ unchanged++
360+ continue
361+ }
320362 val prev = ledger[m.id]
321363 when {
322364 prev == null -> inserts + = m
@@ -395,7 +437,7 @@ abstract class ServiceInterface (
395437 // so the periodic worker doesn't rewrite unchanged snapshots every run. Best-effort.
396438 val snapshotUsers = if (force) current.mapTo(HashSet ()) { it.userId } else changedUsers
397439 if (snapshotUsers.isNotEmpty()) {
398- runCatching { onReconciled(current, snapshotUsers) }
440+ runCatching { onReconciled(current.filterNot { isImported(it) } , snapshotUsers) }
399441 .onFailure { Timber .w(it, " onReconciled hook failed" ) }
400442 }
401443
@@ -414,6 +456,31 @@ abstract class ServiceInterface (
414456 */
415457 protected open suspend fun onReconciled (current : List <OpenScaleMeasurement >, changedUserIds : Set <Int >) {}
416458
459+ // --- Inbound origin (no write-back to the source, issue #51) -------------------------
460+ // Per-backend set of the measurements runInbound took FROM this backend, as "userId:timeMs",
461+ // kept only where [exportsImported] is false. Such a measurement is never exported back to that
462+ // backend, not even after an edit in openScale: on Health Connect it would sit as a record of
463+ // ours next to the original app's (Google's write guidance forbids writing back what was read).
464+ // The source keeps its own record; a correction belongs there and comes back with the next
465+ // import. Other backends still get everything. Per measurement, not per value: an inbound
466+ // reading always carries the weight, which every backend anchors its payload on, so no part of
467+ // such a measurement is ours to send.
468+ private val originPrefs by lazy {
469+ context.getSharedPreferences(" inbound_origin_${viewModel().getName()} " , Context .MODE_PRIVATE )
470+ }
471+
472+ private fun originKey (userId : Int , timeMs : Long ) = " $userId :$timeMs "
473+
474+ private fun originRecord (keys : Set <String >) {
475+ if (keys.isEmpty()) return
476+ synchronized(ledgerLock) {
477+ originPrefs.edit { putStringSet(" origin" , originPrefs.getStringSet(" origin" , emptySet()).orEmpty() + keys) }
478+ }
479+ }
480+
481+ private fun isImported (m : OpenScaleMeasurement ): Boolean =
482+ ! exportsImported && originKey(m.userId, m.date.time) in originPrefs.getStringSet(" origin" , emptySet()).orEmpty()
483+
417484 // --- Inbound (Phase 4: external source → openScale) ---------------------------------
418485 /* *
419486 * Inbound-capable backends ([supportsInbound]) override this to pull measurements from their
@@ -460,6 +527,10 @@ abstract class ServiceInterface (
460527 .mapTo(HashSet ()) { it.date.time }
461528 }
462529
530+ // Recorded BEFORE writing, so no export running meanwhile (the periodic worker, a manual
531+ // sync) can see one of these measurements without knowing it is the source's.
532+ if (! exportsImported) originRecord(items.mapTo(HashSet ()) { originKey(it.userId ? : userId, it.timeMs) })
533+
463534 var updated = 0
464535 val attempted = HashMap <Int , MutableList <Long >>()
465536 for (m in items) {
@@ -585,7 +656,17 @@ abstract class ServiceInterface (
585656 * the ledger is a MOVE — backends key records by (user, time), so we drop the stale record at the
586657 * old time and recreate at the new one. No retry-enqueue here; submit()/drainQueue() own that.
587658 */
588- private suspend fun dispatchOp (op : PendingOp ): SyncResult <Unit > = when (op.type) {
659+ private suspend fun dispatchOp (op : PendingOp ): SyncResult <Unit > {
660+ // A measurement imported from this backend is the source's: nothing to send, and no ledger
661+ // entry either, since nothing was exported. Deletes still go out unchanged — suppressing one
662+ // would only let the next import bring the measurement straight back.
663+ if ((op.type == " insert" || op.type == " update" ) && isImported(op.toMeasurement())) {
664+ return SyncResult .Success (Unit )
665+ }
666+ return dispatchWire(op)
667+ }
668+
669+ private suspend fun dispatchWire (op : PendingOp ): SyncResult <Unit > = when (op.type) {
589670 " insert" -> op.toMeasurement().let { m ->
590671 insert(m).also { if (it is SyncResult .Success ) ledgerRecord(op.id, m) }
591672 }
@@ -770,6 +851,7 @@ abstract class ServiceInterface (
770851 fun resetSyncState () {
771852 ledgerStore(emptyMap())
772853 dirtyStore(emptyMap())
854+ synchronized(ledgerLock) { originPrefs.edit { clear() } } // keyed by that install's user ids
773855 viewModel().setSelectedUserId(- 1 ) // user ids belong to that install too
774856 }
775857
0 commit comments