Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions BACKLOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,31 @@ fast enough in real use, don't build it.
---

## Done
- ✅ `2026-07-04` — **Household create/join/leave now refreshes the shared hierarchy** (wave-3 X4). `HouseholdsViewModel.create()/leave()`
and `JoinHouseholdViewModel.join()` updated only the `HouseholdRepository` cache + their own UI state, so
the drawer/home/dashboard (driven by the `@Singleton HierarchyStore`) stayed stale until a manual
pull-to-refresh or relaunch — product create/delete already refreshed, but household-level mutations were
missed. Inject `HierarchyStore` into both VMs and call `refresh()` after a successful create/join/leave.
Tests assert the store reflects the mutation (shared `TestHierarchy` helper).
- ✅ `2026-07-04` — **Per-location "⚠ needs attention" indicator now lights up on load** (wave-3 X2, HIGH/MED).
Home (`AllStoragesScreen`) and the drawer rendered the warning purely from `state.locationWarnings`, which
was populated *only* by a composed `ProductsPane` via `reportLocationWarning` — so a location whose
out-of-stock mandatory item sat on a non-visible shelf showed no ⚠ until the user opened it and swiped to
that shelf, making the at-a-glance rollup silently show "all good". `HierarchyStore` now computes
`locationWarnings` authoritatively in both `loadFromCache` and `buildFromNetwork` by grouping the
`missingItems` it already builds by `locationId`, and `refresh` onSuccess takes the server-computed map as
truth (dropping the old partial-map preservation — the API is server-authoritative and mutations refresh
after the server confirms). Tests cover the warning appearing from a non-visible shelf and clearing when stocked.
- ✅ `2026-07-04` — **Logout/login no longer leaks the previous user's data** (wave-3 X1, HIGH). `logout()`
cleared only the bearer token, but every repository + `HierarchyStore` + the favorites/default-household
prefs are `@Singleton`, so an account switch on the same process rendered User A's households/locations/
products/missing-items/favorites to User B — `HierarchyStore.refresh()` → `loadFromCache()` repopulates
synchronously from the stale caches before the network returns. Added `clear()` to each repo cache
(default no-op on the interface so test fakes are unaffected), `HierarchyStore` (reset state + cancel the
in-flight job), and `FavoritesStore`; centralized in a `SessionCleaner` called on `logout()` **and** at
the start of every new sign-in (register/login/google) — the latter also covers the reactive-401 path,
where the interceptor clears the token but can't reach the singletons. In-memory/prefs only (no local DB).
Tests: `HierarchyStore.clear()` resets, `SessionCleaner.clear()` fans out to every cache/store.
- ✅ `2026-07-04` — **Drawer search reaches every household, not just the first** (wave-2 W23). `AppDrawer`
wired the single global "Search" entry to `entries.firstOrNull()?.id`, so a multi-household user could
only ever search their first household — silently. Search is legitimately household-scoped, so: keep the
Expand Down
31 changes: 28 additions & 3 deletions app/src/main/java/dev/scuttle/inventory/data/HierarchyStore.kt
Original file line number Diff line number Diff line change
Expand Up @@ -109,11 +109,21 @@ class HierarchyStore @Inject constructor(
entries = entries, missingItems = missingItems, missingItemCount = mandatoryWarnings,
totalShelves = totalShelves, totalProducts = totalProducts,
mandatoryWarnings = mandatoryWarnings, locationStats = locationStats,
allShelves = allShelves,
allShelves = allShelves, locationWarnings = warningsByLocation(missingItems),
)
}
}

/**
* Which locations have at least one missing mandatory item, derived from the
* full product set (X2). The home/drawer "⚠ needs attention" indicator reads
* this — before, it was only ever populated by a composed ProductsPane, so a
* missing item on a non-visible shelf showed no warning until the user opened
* that location and swiped to the shelf.
*/
private fun warningsByLocation(missingItems: List<MissingItem>): Map<Long, Boolean> =
missingItems.map { it.locationId }.associateWith { true }

/**
* @param userInitiated true when the user pulled to refresh or tapped refresh —
* flips `refreshing` so the pull indicator spins. A post-mutation reload passes
Expand All @@ -129,13 +139,27 @@ class HierarchyStore @Inject constructor(
buildFromNetwork(households)
}.fold(
// buildFromNetwork returns a fresh state with loading/refreshing at their
// false defaults, so both indicators clear on success.
onSuccess = { update -> _state.update { s -> update.copy(locationWarnings = s.locationWarnings) } },
// false defaults, so both indicators clear on success. Its locationWarnings
// are now computed authoritatively from the full server product set (X2),
// so we take them as-is rather than preserving the old partial map that only
// the visible ProductsPane could populate — the API is server-authoritative,
// and a mutation refreshes after the server confirms, so this is the truth.
onSuccess = { update -> _state.value = update },
onFailure = { e -> _state.update { it.copy(loading = false, refreshing = false, error = e.toUserMessage("Failed to load.")) } },
)
}
}

/**
* Reset to the empty state and drop any in-flight load. Called on session end
* (logout / new login) so one account's hierarchy never renders to the next —
* loadFromCache() would otherwise repopulate it from the singleton repo caches.
*/
fun clear() {
activeJob?.cancel()
_state.value = HierarchyState()
}

fun reportLocationWarning(locationId: Long, hasWarning: Boolean) {
_state.update { state ->
state.copy(locationWarnings = state.locationWarnings + (locationId to hasWarning))
Expand Down Expand Up @@ -196,6 +220,7 @@ class HierarchyStore @Inject constructor(
mandatoryWarnings = mandatoryWarnings,
locationStats = locationStats,
allShelves = allShelves,
locationWarnings = warningsByLocation(missingItems),
)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import javax.inject.Inject
class AuthRepositoryImpl @Inject constructor(
private val api: AuthApi,
private val tokenStore: TokenStore,
private val sessionCleaner: SessionCleaner,
) : AuthRepository {

override fun isAuthenticated(): Boolean = tokenStore.get() != null
Expand All @@ -19,17 +20,29 @@ class AuthRepositoryImpl @Inject constructor(

override suspend fun register(name: String, email: String, password: String) {
val response = api.register(RegisterRequest(name = name, email = email, password = password))
tokenStore.set(response.token)
onNewSession(response.token)
}

override suspend fun login(email: String, password: String) {
val response = api.login(LoginRequest(email = email, password = password))
tokenStore.set(response.token)
onNewSession(response.token)
}

override suspend fun loginWithGoogle(idToken: String) {
val response = api.google(GoogleRequest(id_token = idToken))
tokenStore.set(response.token)
onNewSession(response.token)
}

/**
* Start every new session from a clean slate. Clearing here (not only in
* logout) also covers the reactive-401 logout path, where the interceptor
* clears the token but can't reach the singleton caches — so the stale data
* is wiped at the next successful sign-in regardless of how the prior session
* ended.
*/
private fun onNewSession(token: String) {
sessionCleaner.clear()
tokenStore.set(token)
}

override suspend fun loginWithGoogleCode(code: String, codeVerifier: String, redirectUri: String) =
Expand All @@ -42,5 +55,6 @@ class AuthRepositoryImpl @Inject constructor(
override suspend fun logout() {
runCatching { api.logout() }
tokenStore.clear()
sessionCleaner.clear()
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package dev.scuttle.inventory.data.auth

import dev.scuttle.inventory.data.HierarchyStore
import dev.scuttle.inventory.data.household.HouseholdRepository
import dev.scuttle.inventory.data.location.LocationRepository
import dev.scuttle.inventory.data.product.ProductRepository
import dev.scuttle.inventory.data.settings.DefaultHouseholdStore
import dev.scuttle.inventory.data.settings.FavoritesStore
import dev.scuttle.inventory.data.shelf.ShelfRepository
import javax.inject.Inject
import javax.inject.Singleton

/**
* Wipes every per-account in-memory cache + local pref so one user's data never
* bleeds into the next session. The repositories, [HierarchyStore], and the pref
* stores are all `@Singleton`, so without this an account switch on the same
* process would render the previous user's households/locations/products/
* missing-items (and favorites) to the new user — `HierarchyStore.refresh()`
* calls `loadFromCache()`, which repopulates synchronously from the stale caches
* before the network returns. In-memory/prefs only, so it respects the
* always-online, no-local-DB rule.
*/
@Singleton
class SessionCleaner @Inject constructor(
private val householdRepository: HouseholdRepository,
private val locationRepository: LocationRepository,
private val shelfRepository: ShelfRepository,
private val productRepository: ProductRepository,
private val hierarchyStore: HierarchyStore,
private val favoritesStore: FavoritesStore,
private val defaultHouseholdStore: DefaultHouseholdStore,
) {
fun clear() {
householdRepository.clear()
locationRepository.clear()
shelfRepository.clear()
productRepository.clear()
hierarchyStore.clear()
favoritesStore.clear()
defaultHouseholdStore.clear()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,7 @@ interface HouseholdRepository {
suspend fun join(code: String): HouseholdDto

suspend fun leave(householdId: Long)

/** Drop the in-memory cache so one account's data never bleeds into the next session. */
fun clear() {}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,8 @@ class HouseholdRepositoryImpl @Inject constructor(
api.leave(householdId)
cache = cache?.filter { it.id != householdId }
}

override fun clear() {
cache = null
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,7 @@ interface LocationRepository {
suspend fun create(householdId: Long, name: String, type: String): LocationDto

suspend fun delete(householdId: Long, locationId: Long)

/** Drop the in-memory cache so one account's data never bleeds into the next session. */
fun clear() {}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,8 @@ class LocationRepositoryImpl @Inject constructor(
api.delete(householdId, locationId)
cache[householdId] = cache[householdId]?.filter { it.id != locationId } ?: emptyList()
}

override fun clear() {
cache.clear()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,7 @@ interface ProductRepository {
suspend fun move(householdId: Long, shelfId: Long, productId: Long, targetShelfId: Long): ProductDto
suspend fun uploadImage(householdId: Long, shelfId: Long, productId: Long, imageUri: Uri, mimeType: String): ProductDto
suspend fun delete(householdId: Long, shelfId: Long, productId: Long)

/** Drop the in-memory cache so one account's data never bleeds into the next session. */
fun clear() {}
}
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,10 @@ class ProductRepositoryImpl @Inject constructor(
cache[householdId to shelfId] = cache[householdId to shelfId]?.filter { it.id != productId } ?: emptyList()
}

override fun clear() {
cache.clear()
}

private fun MutableMap<Pair<Long, Long>, List<ProductDto>>.replaceProduct(householdId: Long, shelfId: Long, updated: ProductDto) {
val key = householdId to shelfId
this[key] = this[key]?.map { if (it.id == updated.id) updated else it } ?: listOf(updated)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,7 @@ interface FavoritesStore {
fun getFavoriteShelves(): Set<Long>
fun toggleFavoriteShelf(id: Long)
fun isFavoriteShelf(id: Long): Boolean

/** Forget all favorites so one account's picks never carry into the next session. */
fun clear() {}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ class SharedPrefsFavoritesStore(context: Context) : FavoritesStore {
override fun isFavoriteShelf(id: Long): Boolean = id in getFavoriteShelves()
override fun toggleFavoriteShelf(id: Long) = toggleInSet("shelves", id)

override fun clear() {
prefs.edit().clear().apply()
}

private fun getLongSet(key: String): Set<Long> =
prefs.getStringSet(key, emptySet())?.mapNotNull { it.toLongOrNull() }?.toSet() ?: emptySet()

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,7 @@ interface ShelfRepository {
suspend fun create(householdId: Long, locationId: Long, name: String): ShelfDto

suspend fun delete(householdId: Long, locationId: Long, shelfId: Long)

/** Drop the in-memory cache so one account's data never bleeds into the next session. */
fun clear() {}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,8 @@ class ShelfRepositoryImpl @Inject constructor(
val key = householdId to locationId
cache[key] = cache[key]?.filter { it.id != shelfId } ?: emptyList()
}

override fun clear() {
cache.clear()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package dev.scuttle.inventory.ui.households

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dev.scuttle.inventory.data.HierarchyStore
import dev.scuttle.inventory.data.dto.HouseholdDto
import dev.scuttle.inventory.data.household.HouseholdRepository
import dagger.hilt.android.lifecycle.HiltViewModel
Expand All @@ -27,6 +28,7 @@ data class HouseholdsUiState(
@HiltViewModel
class HouseholdsViewModel @Inject constructor(
private val repository: HouseholdRepository,
private val hierarchyStore: HierarchyStore,
) : ViewModel() {

private val _state = MutableStateFlow(HouseholdsUiState())
Expand Down Expand Up @@ -62,12 +64,17 @@ class HouseholdsViewModel @Inject constructor(
repository.create(name)
_state.update { it.copy(newName = "") }
_state.update { it.copy(households = repository.list()) }
// Keep the drawer/home/dashboard (driven by HierarchyStore) in sync — a
// new household would otherwise stay invisible there until a manual
// pull-to-refresh or relaunch (X4).
hierarchyStore.refresh()
}
}

fun leave(householdId: Long) = launchLoading {
repository.leave(householdId)
_state.update { it.copy(households = repository.list()) }
hierarchyStore.refresh()
}

private fun launchLoading(refreshing: Boolean = false, block: suspend () -> Unit) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package dev.scuttle.inventory.ui.settings

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dev.scuttle.inventory.data.HierarchyStore
import dev.scuttle.inventory.data.household.HouseholdRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
Expand All @@ -22,6 +23,7 @@ data class JoinUiState(
@HiltViewModel
class JoinHouseholdViewModel @Inject constructor(
private val repository: HouseholdRepository,
private val hierarchyStore: HierarchyStore,
) : ViewModel() {

private val _state = MutableStateFlow(JoinUiState())
Expand All @@ -35,6 +37,9 @@ class JoinHouseholdViewModel @Inject constructor(
viewModelScope.launch {
_state.update { it.copy(loading = true, error = null, success = false) }
val result = runCatching { repository.join(code) }
// Refresh the drawer/home/dashboard so the joined household appears there
// immediately, not just on the next manual pull-to-refresh (X4).
if (result.isSuccess) hierarchyStore.refresh()
_state.update { state ->
result.fold(
onSuccess = { state.copy(loading = false, code = "", success = true) },
Expand Down
55 changes: 55 additions & 0 deletions app/src/test/java/dev/scuttle/inventory/HierarchyStoreTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import java.io.IOException
Expand Down Expand Up @@ -101,4 +102,58 @@ class HierarchyStoreTest {
assertFalse(failed.loading)
assertFalse(failed.refreshing)
}

@Test
fun refresh_computes_location_warnings_without_any_pane_report() = runTest {
// X2: the "⚠ needs attention" indicator must light up from server data on
// load — a missing mandatory item on any shelf, not only the visible one.
val store = HierarchyStore(
FakeHouseholdRepository(listOf(HouseholdDto(1, "Home", "AAAA"))),
FakeLocationRepository(mapOf(1L to listOf(LocationDto(10, "Fridge", "fridge")))),
FakeShelfRepository(mapOf(10L to listOf(ShelfDto(100, "Top", 0, 10), ShelfDto(101, "Bottom", 1, 10)))),
// The missing mandatory item sits on the SECOND (non-visible) shelf.
FakeProductRepository(mapOf(101L to listOf(ProductDto(1, "Milk", 0, 101, is_mandatory = true)))),
)

store.refresh(userInitiated = true)

val loaded = store.state.first { !it.loading }
assertEquals(true, loaded.locationWarnings[10])
}

@Test
fun refresh_leaves_no_warning_when_all_mandatory_items_are_stocked() = runTest {
val store = HierarchyStore(
FakeHouseholdRepository(listOf(HouseholdDto(1, "Home", "AAAA"))),
FakeLocationRepository(mapOf(1L to listOf(LocationDto(10, "Fridge", "fridge")))),
FakeShelfRepository(mapOf(10L to listOf(ShelfDto(100, "Top", 0, 10)))),
FakeProductRepository(mapOf(100L to listOf(ProductDto(1, "Milk", 3, 100, is_mandatory = true)))),
)

store.refresh(userInitiated = true)

val loaded = store.state.first { !it.loading }
assertNull(loaded.locationWarnings[10])
}

@Test
fun clear_resets_to_the_empty_state() = runTest {
// X1: on session end the store must reset so one account's hierarchy never
// renders to the next (loadFromCache would otherwise repopulate it).
val store = HierarchyStore(
FakeHouseholdRepository(listOf(HouseholdDto(1, "Home", "AAAA"))),
FakeLocationRepository(mapOf(1L to listOf(LocationDto(10, "Fridge", "fridge")))),
FakeShelfRepository(mapOf(10L to listOf(ShelfDto(100, "Top", 0, 10)))),
FakeProductRepository(mapOf(100L to listOf(ProductDto(1, "Milk", 0, 100, is_mandatory = true)))),
)
store.refresh(userInitiated = true)
assertEquals(1, store.state.first { !it.loading }.entries.size)

store.clear()

val cleared = store.state.value
assertTrue(cleared.entries.isEmpty())
assertEquals(0, cleared.missingItemCount)
assertNull(cleared.error)
}
}
Loading
Loading