diff --git a/BACKLOG.md b/BACKLOG.md index 9f7bbfb..da74e1c 100644 --- a/BACKLOG.md +++ b/BACKLOG.md @@ -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 diff --git a/app/src/main/java/dev/scuttle/inventory/data/HierarchyStore.kt b/app/src/main/java/dev/scuttle/inventory/data/HierarchyStore.kt index bbcd310..b5728b1 100644 --- a/app/src/main/java/dev/scuttle/inventory/data/HierarchyStore.kt +++ b/app/src/main/java/dev/scuttle/inventory/data/HierarchyStore.kt @@ -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): Map = + 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 @@ -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)) @@ -196,6 +220,7 @@ class HierarchyStore @Inject constructor( mandatoryWarnings = mandatoryWarnings, locationStats = locationStats, allShelves = allShelves, + locationWarnings = warningsByLocation(missingItems), ) } diff --git a/app/src/main/java/dev/scuttle/inventory/data/auth/AuthRepositoryImpl.kt b/app/src/main/java/dev/scuttle/inventory/data/auth/AuthRepositoryImpl.kt index 3bf2f94..af4c866 100644 --- a/app/src/main/java/dev/scuttle/inventory/data/auth/AuthRepositoryImpl.kt +++ b/app/src/main/java/dev/scuttle/inventory/data/auth/AuthRepositoryImpl.kt @@ -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 @@ -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) = @@ -42,5 +55,6 @@ class AuthRepositoryImpl @Inject constructor( override suspend fun logout() { runCatching { api.logout() } tokenStore.clear() + sessionCleaner.clear() } } diff --git a/app/src/main/java/dev/scuttle/inventory/data/auth/SessionCleaner.kt b/app/src/main/java/dev/scuttle/inventory/data/auth/SessionCleaner.kt new file mode 100644 index 0000000..a0fd991 --- /dev/null +++ b/app/src/main/java/dev/scuttle/inventory/data/auth/SessionCleaner.kt @@ -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() + } +} diff --git a/app/src/main/java/dev/scuttle/inventory/data/household/HouseholdRepository.kt b/app/src/main/java/dev/scuttle/inventory/data/household/HouseholdRepository.kt index cf7ccad..4e9d048 100644 --- a/app/src/main/java/dev/scuttle/inventory/data/household/HouseholdRepository.kt +++ b/app/src/main/java/dev/scuttle/inventory/data/household/HouseholdRepository.kt @@ -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() {} } diff --git a/app/src/main/java/dev/scuttle/inventory/data/household/HouseholdRepositoryImpl.kt b/app/src/main/java/dev/scuttle/inventory/data/household/HouseholdRepositoryImpl.kt index 94ddcad..690629e 100644 --- a/app/src/main/java/dev/scuttle/inventory/data/household/HouseholdRepositoryImpl.kt +++ b/app/src/main/java/dev/scuttle/inventory/data/household/HouseholdRepositoryImpl.kt @@ -24,4 +24,8 @@ class HouseholdRepositoryImpl @Inject constructor( api.leave(householdId) cache = cache?.filter { it.id != householdId } } + + override fun clear() { + cache = null + } } diff --git a/app/src/main/java/dev/scuttle/inventory/data/location/LocationRepository.kt b/app/src/main/java/dev/scuttle/inventory/data/location/LocationRepository.kt index f89ee37..f2c4b64 100644 --- a/app/src/main/java/dev/scuttle/inventory/data/location/LocationRepository.kt +++ b/app/src/main/java/dev/scuttle/inventory/data/location/LocationRepository.kt @@ -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() {} } diff --git a/app/src/main/java/dev/scuttle/inventory/data/location/LocationRepositoryImpl.kt b/app/src/main/java/dev/scuttle/inventory/data/location/LocationRepositoryImpl.kt index 1427186..e8f615a 100644 --- a/app/src/main/java/dev/scuttle/inventory/data/location/LocationRepositoryImpl.kt +++ b/app/src/main/java/dev/scuttle/inventory/data/location/LocationRepositoryImpl.kt @@ -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() + } } diff --git a/app/src/main/java/dev/scuttle/inventory/data/product/ProductRepository.kt b/app/src/main/java/dev/scuttle/inventory/data/product/ProductRepository.kt index 002e83b..83d0451 100644 --- a/app/src/main/java/dev/scuttle/inventory/data/product/ProductRepository.kt +++ b/app/src/main/java/dev/scuttle/inventory/data/product/ProductRepository.kt @@ -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() {} } diff --git a/app/src/main/java/dev/scuttle/inventory/data/product/ProductRepositoryImpl.kt b/app/src/main/java/dev/scuttle/inventory/data/product/ProductRepositoryImpl.kt index 3a28a0d..1d9be27 100644 --- a/app/src/main/java/dev/scuttle/inventory/data/product/ProductRepositoryImpl.kt +++ b/app/src/main/java/dev/scuttle/inventory/data/product/ProductRepositoryImpl.kt @@ -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, List>.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) diff --git a/app/src/main/java/dev/scuttle/inventory/data/settings/FavoritesStore.kt b/app/src/main/java/dev/scuttle/inventory/data/settings/FavoritesStore.kt index 2eab0f1..dfeaa03 100644 --- a/app/src/main/java/dev/scuttle/inventory/data/settings/FavoritesStore.kt +++ b/app/src/main/java/dev/scuttle/inventory/data/settings/FavoritesStore.kt @@ -7,4 +7,7 @@ interface FavoritesStore { fun getFavoriteShelves(): Set 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() {} } diff --git a/app/src/main/java/dev/scuttle/inventory/data/settings/SharedPrefsFavoritesStore.kt b/app/src/main/java/dev/scuttle/inventory/data/settings/SharedPrefsFavoritesStore.kt index c126058..80cb8f5 100644 --- a/app/src/main/java/dev/scuttle/inventory/data/settings/SharedPrefsFavoritesStore.kt +++ b/app/src/main/java/dev/scuttle/inventory/data/settings/SharedPrefsFavoritesStore.kt @@ -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 = prefs.getStringSet(key, emptySet())?.mapNotNull { it.toLongOrNull() }?.toSet() ?: emptySet() diff --git a/app/src/main/java/dev/scuttle/inventory/data/shelf/ShelfRepository.kt b/app/src/main/java/dev/scuttle/inventory/data/shelf/ShelfRepository.kt index d546681..61b8da1 100644 --- a/app/src/main/java/dev/scuttle/inventory/data/shelf/ShelfRepository.kt +++ b/app/src/main/java/dev/scuttle/inventory/data/shelf/ShelfRepository.kt @@ -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() {} } diff --git a/app/src/main/java/dev/scuttle/inventory/data/shelf/ShelfRepositoryImpl.kt b/app/src/main/java/dev/scuttle/inventory/data/shelf/ShelfRepositoryImpl.kt index 25f589e..71ea932 100644 --- a/app/src/main/java/dev/scuttle/inventory/data/shelf/ShelfRepositoryImpl.kt +++ b/app/src/main/java/dev/scuttle/inventory/data/shelf/ShelfRepositoryImpl.kt @@ -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() + } } diff --git a/app/src/main/java/dev/scuttle/inventory/ui/households/HouseholdsViewModel.kt b/app/src/main/java/dev/scuttle/inventory/ui/households/HouseholdsViewModel.kt index e0c6839..7bc2811 100644 --- a/app/src/main/java/dev/scuttle/inventory/ui/households/HouseholdsViewModel.kt +++ b/app/src/main/java/dev/scuttle/inventory/ui/households/HouseholdsViewModel.kt @@ -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 @@ -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()) @@ -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) { diff --git a/app/src/main/java/dev/scuttle/inventory/ui/settings/JoinHouseholdViewModel.kt b/app/src/main/java/dev/scuttle/inventory/ui/settings/JoinHouseholdViewModel.kt index f2d2c76..db0bae8 100644 --- a/app/src/main/java/dev/scuttle/inventory/ui/settings/JoinHouseholdViewModel.kt +++ b/app/src/main/java/dev/scuttle/inventory/ui/settings/JoinHouseholdViewModel.kt @@ -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 @@ -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()) @@ -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) }, diff --git a/app/src/test/java/dev/scuttle/inventory/HierarchyStoreTest.kt b/app/src/test/java/dev/scuttle/inventory/HierarchyStoreTest.kt index 9de6e58..283d6c3 100644 --- a/app/src/test/java/dev/scuttle/inventory/HierarchyStoreTest.kt +++ b/app/src/test/java/dev/scuttle/inventory/HierarchyStoreTest.kt @@ -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 @@ -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) + } } diff --git a/app/src/test/java/dev/scuttle/inventory/HouseholdsViewModelTest.kt b/app/src/test/java/dev/scuttle/inventory/HouseholdsViewModelTest.kt index d5757df..284a4a6 100644 --- a/app/src/test/java/dev/scuttle/inventory/HouseholdsViewModelTest.kt +++ b/app/src/test/java/dev/scuttle/inventory/HouseholdsViewModelTest.kt @@ -3,6 +3,7 @@ package dev.scuttle.inventory import dev.scuttle.inventory.data.dto.HouseholdDto import dev.scuttle.inventory.data.household.HouseholdRepository import dev.scuttle.inventory.ui.households.HouseholdsViewModel +import kotlinx.coroutines.flow.first import kotlinx.coroutines.test.runTest import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse @@ -39,7 +40,7 @@ class HouseholdsViewModelTest { @Test fun loads_households_on_init() = runTest { - val viewModel = HouseholdsViewModel(FakeHouseholdRepository()) + val viewModel = HouseholdsViewModel(FakeHouseholdRepository(), TestHierarchy.store(FakeHouseholdRepository())) val state = viewModel.state.value assertEquals(1, state.households.size) @@ -49,7 +50,7 @@ class HouseholdsViewModelTest { @Test fun create_adds_a_household_and_clears_the_field() = runTest { - val viewModel = HouseholdsViewModel(FakeHouseholdRepository()) + val viewModel = HouseholdsViewModel(FakeHouseholdRepository(), TestHierarchy.store(FakeHouseholdRepository())) viewModel.onNewNameChange("Pantry") viewModel.create() @@ -60,10 +61,25 @@ class HouseholdsViewModelTest { assertEquals("", state.newName) } + @Test + fun create_refreshes_the_hierarchy_store() = runTest { + // X4: a newly-created household must reach the drawer/home hierarchy without + // a manual pull-to-refresh. + val repo = FakeHouseholdRepository() + val store = TestHierarchy.store(repo) + val viewModel = HouseholdsViewModel(repo, store) + viewModel.onNewNameChange("Pantry") + + viewModel.create() + + val loaded = store.state.first { s -> s.entries.any { it.name == "Pantry" } } + assertTrue(loaded.entries.any { it.name == "Pantry" }) + } + @Test fun list_failure_surfaces_an_error() = runTest { val repo = FakeHouseholdRepository().apply { failList = true } - val viewModel = HouseholdsViewModel(repo) + val viewModel = HouseholdsViewModel(repo, TestHierarchy.store(repo)) assertEquals("offline", viewModel.state.value.error) } @@ -73,7 +89,7 @@ class HouseholdsViewModelTest { val repo = FakeHouseholdRepository().apply { items.add(HouseholdDto(id = 2, name = "Office", join_code = "BBBB-2222")) } - val viewModel = HouseholdsViewModel(repo) + val viewModel = HouseholdsViewModel(repo, TestHierarchy.store(repo)) assertEquals(2, viewModel.state.value.households.size) viewModel.leave(householdId = 1) diff --git a/app/src/test/java/dev/scuttle/inventory/JoinHouseholdViewModelTest.kt b/app/src/test/java/dev/scuttle/inventory/JoinHouseholdViewModelTest.kt index c64cc0b..7faf4c2 100644 --- a/app/src/test/java/dev/scuttle/inventory/JoinHouseholdViewModelTest.kt +++ b/app/src/test/java/dev/scuttle/inventory/JoinHouseholdViewModelTest.kt @@ -3,6 +3,7 @@ package dev.scuttle.inventory import dev.scuttle.inventory.data.dto.HouseholdDto import dev.scuttle.inventory.data.household.HouseholdRepository import dev.scuttle.inventory.ui.settings.JoinHouseholdViewModel +import kotlinx.coroutines.flow.first import kotlinx.coroutines.test.runTest import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse @@ -33,7 +34,7 @@ class JoinHouseholdViewModelTest { @Test fun code_change_updates_state() { - val vm = JoinHouseholdViewModel(FakeHouseholdRepository()) + val vm = JoinHouseholdViewModel(FakeHouseholdRepository(), TestHierarchy.store(FakeHouseholdRepository())) vm.onCodeChange("ABC") assertEquals("ABC", vm.state.value.code) assertNull(vm.state.value.error) @@ -42,7 +43,7 @@ class JoinHouseholdViewModelTest { @Test fun join_with_empty_code_does_nothing() = runTest { - val vm = JoinHouseholdViewModel(FakeHouseholdRepository()) + val vm = JoinHouseholdViewModel(FakeHouseholdRepository(), TestHierarchy.store(FakeHouseholdRepository())) vm.join() assertFalse(vm.state.value.success) assertFalse(vm.state.value.loading) @@ -50,7 +51,7 @@ class JoinHouseholdViewModelTest { @Test fun join_success_sets_success_and_clears_code() = runTest { - val vm = JoinHouseholdViewModel(FakeHouseholdRepository()) + val vm = JoinHouseholdViewModel(FakeHouseholdRepository(), TestHierarchy.store(FakeHouseholdRepository())) vm.onCodeChange("VALIDCODE") vm.join() assertTrue(vm.state.value.success) @@ -61,7 +62,7 @@ class JoinHouseholdViewModelTest { @Test fun join_failure_surfaces_error_and_preserves_code() = runTest { - val vm = JoinHouseholdViewModel(FakeHouseholdRepository(failJoin = true)) + val vm = JoinHouseholdViewModel(FakeHouseholdRepository(failJoin = true), TestHierarchy.store(FakeHouseholdRepository())) vm.onCodeChange("BADCODE") vm.join() assertFalse(vm.state.value.success) @@ -71,11 +72,32 @@ class JoinHouseholdViewModelTest { @Test fun code_change_after_error_clears_error() = runTest { - val vm = JoinHouseholdViewModel(FakeHouseholdRepository(failJoin = true)) + val vm = JoinHouseholdViewModel(FakeHouseholdRepository(failJoin = true), TestHierarchy.store(FakeHouseholdRepository())) vm.onCodeChange("BAD") vm.join() assertNotNull(vm.state.value.error) vm.onCodeChange("NEW") assertNull(vm.state.value.error) } + + @Test + fun successful_join_refreshes_the_hierarchy_store() = runTest { + // X4: joining from Settings must reach the drawer/home hierarchy without a + // manual pull-to-refresh. This repo's list() returns the joined household. + val repo = object : HouseholdRepository { + override fun getCached(): List? = null + override suspend fun list() = listOf(HouseholdDto(2, "Friends", "BBBB")) + override suspend fun create(name: String) = HouseholdDto(2, "Friends", "BBBB") + override suspend fun join(code: String) = HouseholdDto(2, "Friends", "BBBB") + override suspend fun leave(householdId: Long) {} + } + val store = TestHierarchy.store(repo) + val vm = JoinHouseholdViewModel(repo, store) + vm.onCodeChange("BBBB") + + vm.join() + + val loaded = store.state.first { it.entries.isNotEmpty() } + assertTrue(loaded.entries.any { it.name == "Friends" }) + } } diff --git a/app/src/test/java/dev/scuttle/inventory/SessionCleanerTest.kt b/app/src/test/java/dev/scuttle/inventory/SessionCleanerTest.kt new file mode 100644 index 0000000..999c10d --- /dev/null +++ b/app/src/test/java/dev/scuttle/inventory/SessionCleanerTest.kt @@ -0,0 +1,102 @@ +package dev.scuttle.inventory + +import android.net.Uri +import dev.scuttle.inventory.data.HierarchyStore +import dev.scuttle.inventory.data.auth.SessionCleaner +import dev.scuttle.inventory.data.dto.HouseholdDto +import dev.scuttle.inventory.data.dto.LocationDto +import dev.scuttle.inventory.data.dto.ProductDto +import dev.scuttle.inventory.data.dto.ShelfDto +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 org.junit.Assert.assertTrue +import org.junit.Test + +class SessionCleanerTest { + + private class RecordingHouseholdRepo : HouseholdRepository { + var cleared = false + override fun getCached(): List? = null + override suspend fun list() = emptyList() + override suspend fun create(name: String) = throw NotImplementedError() + override suspend fun join(code: String) = throw NotImplementedError() + override suspend fun leave(householdId: Long) {} + override fun clear() { cleared = true } + } + + private class RecordingLocationRepo : LocationRepository { + var cleared = false + override fun getCached(householdId: Long): List? = null + override suspend fun list(householdId: Long) = emptyList() + override suspend fun create(householdId: Long, name: String, type: String) = throw NotImplementedError() + override suspend fun delete(householdId: Long, locationId: Long) {} + override fun clear() { cleared = true } + } + + private class RecordingShelfRepo : ShelfRepository { + var cleared = false + override fun getCached(householdId: Long, locationId: Long): List? = null + override suspend fun list(householdId: Long, locationId: Long) = emptyList() + override suspend fun create(householdId: Long, locationId: Long, name: String) = throw NotImplementedError() + override suspend fun delete(householdId: Long, locationId: Long, shelfId: Long) {} + override fun clear() { cleared = true } + } + + private class RecordingProductRepo : ProductRepository { + var cleared = false + override fun getCached(householdId: Long, shelfId: Long): List? = null + override suspend fun list(householdId: Long, shelfId: Long) = emptyList() + override suspend fun create(householdId: Long, shelfId: Long, name: String, quantity: Int) = throw NotImplementedError() + override suspend fun update(householdId: Long, shelfId: Long, productId: Long, name: String, description: String?, code: String?, isMandatory: Boolean) = throw NotImplementedError() + override suspend fun add(householdId: Long, shelfId: Long, productId: Long, amount: Int) = throw NotImplementedError() + override suspend fun remove(householdId: Long, shelfId: Long, productId: Long, amount: Int) = throw NotImplementedError() + override suspend fun move(householdId: Long, shelfId: Long, productId: Long, targetShelfId: Long) = throw NotImplementedError() + override suspend fun uploadImage(householdId: Long, shelfId: Long, productId: Long, imageUri: Uri, mimeType: String) = throw NotImplementedError() + override suspend fun delete(householdId: Long, shelfId: Long, productId: Long) {} + override fun clear() { cleared = true } + } + + private class RecordingFavoritesStore : FavoritesStore { + var cleared = false + override fun getFavoriteLocations() = emptySet() + override fun toggleFavoriteLocation(id: Long) {} + override fun isFavoriteLocation(id: Long) = false + override fun getFavoriteShelves() = emptySet() + override fun toggleFavoriteShelf(id: Long) {} + override fun isFavoriteShelf(id: Long) = false + override fun clear() { cleared = true } + } + + private class RecordingDefaultHouseholdStore : DefaultHouseholdStore { + var cleared = false + override fun get(): Long? = null + override fun set(householdId: Long) {} + override fun clear() { cleared = true } + } + + @Test + fun clear_fans_out_to_every_cache_and_store() { + // X1: session end must wipe ALL per-account singleton state — miss one and + // that slice of the previous user's data survives into the next login. + val household = RecordingHouseholdRepo() + val location = RecordingLocationRepo() + val shelf = RecordingShelfRepo() + val product = RecordingProductRepo() + val favorites = RecordingFavoritesStore() + val defaultHousehold = RecordingDefaultHouseholdStore() + val store = HierarchyStore(household, location, shelf, product) + + SessionCleaner(household, location, shelf, product, store, favorites, defaultHousehold).clear() + + assertTrue(household.cleared) + assertTrue(location.cleared) + assertTrue(shelf.cleared) + assertTrue(product.cleared) + assertTrue(favorites.cleared) + assertTrue(defaultHousehold.cleared) + } +} diff --git a/app/src/test/java/dev/scuttle/inventory/TestHierarchy.kt b/app/src/test/java/dev/scuttle/inventory/TestHierarchy.kt new file mode 100644 index 0000000..f3e1122 --- /dev/null +++ b/app/src/test/java/dev/scuttle/inventory/TestHierarchy.kt @@ -0,0 +1,47 @@ +package dev.scuttle.inventory + +import android.net.Uri +import dev.scuttle.inventory.data.HierarchyStore +import dev.scuttle.inventory.data.dto.LocationDto +import dev.scuttle.inventory.data.dto.ProductDto +import dev.scuttle.inventory.data.dto.ShelfDto +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.shelf.ShelfRepository + +/** + * Builds a real [HierarchyStore] over empty location/shelf/product repos for VM + * tests that only need to verify a store refresh was triggered (X4) — the store's + * entries then reflect whatever the supplied [HouseholdRepository] returns. + */ +object TestHierarchy { + private object EmptyLocations : LocationRepository { + override fun getCached(householdId: Long): List? = null + override suspend fun list(householdId: Long) = emptyList() + override suspend fun create(householdId: Long, name: String, type: String) = throw NotImplementedError() + override suspend fun delete(householdId: Long, locationId: Long) {} + } + + private object EmptyShelves : ShelfRepository { + override fun getCached(householdId: Long, locationId: Long): List? = null + override suspend fun list(householdId: Long, locationId: Long) = emptyList() + override suspend fun create(householdId: Long, locationId: Long, name: String) = throw NotImplementedError() + override suspend fun delete(householdId: Long, locationId: Long, shelfId: Long) {} + } + + private object EmptyProducts : ProductRepository { + override fun getCached(householdId: Long, shelfId: Long): List? = null + override suspend fun list(householdId: Long, shelfId: Long) = emptyList() + override suspend fun create(householdId: Long, shelfId: Long, name: String, quantity: Int) = throw NotImplementedError() + override suspend fun update(householdId: Long, shelfId: Long, productId: Long, name: String, description: String?, code: String?, isMandatory: Boolean) = throw NotImplementedError() + override suspend fun add(householdId: Long, shelfId: Long, productId: Long, amount: Int) = throw NotImplementedError() + override suspend fun remove(householdId: Long, shelfId: Long, productId: Long, amount: Int) = throw NotImplementedError() + override suspend fun move(householdId: Long, shelfId: Long, productId: Long, targetShelfId: Long) = throw NotImplementedError() + override suspend fun uploadImage(householdId: Long, shelfId: Long, productId: Long, imageUri: Uri, mimeType: String) = throw NotImplementedError() + override suspend fun delete(householdId: Long, shelfId: Long, productId: Long) {} + } + + fun store(householdRepository: HouseholdRepository): HierarchyStore = + HierarchyStore(householdRepository, EmptyLocations, EmptyShelves, EmptyProducts) +}