From eca904ad865f3146cd40fc759aaabc1c6eb7f324 Mon Sep 17 00:00:00 2001 From: thanna23 <148076306+thanna23@users.noreply.github.com> Date: Tue, 17 Nov 2026 16:58:56 +0100 Subject: [PATCH 01/14] feat(listing): name a location after the campus it is on A point within 600 m of the EPFL or UNIL centre is named \"EPFL campus\" or \"UNIL campus\", the nearer one winning. --- .../listing/model/ListingLocation.kt | 43 +++++++++++++ .../listing/model/ListingLocationsTest.kt | 60 +++++++++++++++++++ 2 files changed, 103 insertions(+) create mode 100644 app/src/test/java/com/android/polybazaar/listing/model/ListingLocationsTest.kt diff --git a/app/src/main/java/com/android/polybazaar/listing/model/ListingLocation.kt b/app/src/main/java/com/android/polybazaar/listing/model/ListingLocation.kt index 9ed7bf4f..1c9f1f60 100644 --- a/app/src/main/java/com/android/polybazaar/listing/model/ListingLocation.kt +++ b/app/src/main/java/com/android/polybazaar/listing/model/ListingLocation.kt @@ -1,6 +1,11 @@ // Co-authored-by: Claude Code (Claude Opus 5.5) package com.android.polybazaar.listing.model +import com.android.polybazaar.map.model.Campus +import com.android.polybazaar.map.model.Coordinates +import kotlin.math.cos +import kotlin.math.sqrt + /** * Where a listing is offered: a point on the map and the name shown for it. * @@ -10,3 +15,41 @@ package com.android.polybazaar.listing.model * [ListingRules.MAX_LOCATION_NAME_LENGTH] characters once trimmed. */ data class ListingLocation(val latitude: Double, val longitude: Double, val name: String) + +/** Names for the points the lender picks on the map for a listing's location. */ +object ListingLocations { + + /** How far from a campus centre a point still counts as on that campus. */ + private const val CAMPUS_RADIUS_METERS = 600.0 + + private const val EARTH_RADIUS_METERS = 6_371_000.0 + + /** The name stored for [campus]: listing data, not a string resource. */ + private fun nameOf(campus: Campus): String = + when (campus) { + Campus.EPFL -> "EPFL campus" + Campus.UNIL -> "UNIL campus" + } + + /** + * The name of the campus [point] is on, the nearest one if it is close to both, or null when it + * is on neither. + */ + fun campusNameFor(point: Coordinates): String? = + Campus.entries + .map { it to distanceMeters(point, it.centre) } + .filter { (_, distance) -> distance <= CAMPUS_RADIUS_METERS } + .minByOrNull { (_, distance) -> distance } + ?.let { (campus, _) -> nameOf(campus) } + + /** Whether [name] is one [campusNameFor] gives, rather than one the lender typed. */ + fun isCampusName(name: String): Boolean = Campus.entries.any { nameOf(it) == name } + + /** Equirectangular distance: accurate enough over the few hundred meters of a campus. */ + private fun distanceMeters(a: Coordinates, b: Coordinates): Double { + val meanLatitude = Math.toRadians((a.latitude + b.latitude) / 2) + val x = Math.toRadians(b.longitude - a.longitude) * cos(meanLatitude) + val y = Math.toRadians(b.latitude - a.latitude) + return EARTH_RADIUS_METERS * sqrt(x * x + y * y) + } +} diff --git a/app/src/test/java/com/android/polybazaar/listing/model/ListingLocationsTest.kt b/app/src/test/java/com/android/polybazaar/listing/model/ListingLocationsTest.kt new file mode 100644 index 00000000..49891be9 --- /dev/null +++ b/app/src/test/java/com/android/polybazaar/listing/model/ListingLocationsTest.kt @@ -0,0 +1,60 @@ +// Co-authored-by: Claude Code (Claude Opus 5.5) +package com.android.polybazaar.listing.model + +import com.android.polybazaar.map.model.Campus +import com.android.polybazaar.map.model.Coordinates +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class ListingLocationsTest { + + /** About 111 195 m per degree of latitude. */ + private fun Coordinates.northBy(meters: Double) = + Coordinates(latitude + meters / 111_195.0, longitude) + + /** The point [fraction] of the way from EPFL to UNIL, about 1 040 m apart. */ + private fun betweenCampuses(fraction: Double): Coordinates { + val epfl = Campus.EPFL.centre + val unil = Campus.UNIL.centre + return Coordinates( + epfl.latitude + (unil.latitude - epfl.latitude) * fraction, + epfl.longitude + (unil.longitude - epfl.longitude) * fraction, + ) + } + + @Test + fun campusNameFor_pointsWithin600Meters_areOnThatCampus() { + mapOf(Campus.EPFL to "EPFL campus", Campus.UNIL to "UNIL campus").forEach { (campus, name) -> + assertEquals(name, ListingLocations.campusNameFor(campus.centre)) + assertEquals(name, ListingLocations.campusNameFor(campus.centre.northBy(590.0))) + } + } + + @Test + fun campusNameFor_pointsBeyond600Meters_areOnNoCampus() { + // North of both campuses, more than 600 m from each. + assertNull(ListingLocations.campusNameFor(Campus.EPFL.centre.northBy(610.0))) + assertNull(ListingLocations.campusNameFor(Campus.UNIL.centre.northBy(610.0))) + // Lausanne station, a few kilometers away. + assertNull(ListingLocations.campusNameFor(Coordinates(46.5167, 6.6291))) + } + + @Test + fun campusNameFor_pointCloseToBothCampuses_isOnTheNearest() { + // Both points are within 600 m of each campus. + assertEquals("EPFL campus", ListingLocations.campusNameFor(betweenCampuses(0.45))) + assertEquals("UNIL campus", ListingLocations.campusNameFor(betweenCampuses(0.55))) + } + + @Test + fun isCampusName_onlyForTheNamesGivenToCampuses() { + assertTrue(ListingLocations.isCampusName("EPFL campus")) + assertTrue(ListingLocations.isCampusName("UNIL campus")) + listOf("", "Flat", "epfl campus", "EPFL campus ").forEach { + assertFalse(it, ListingLocations.isCampusName(it)) + } + } +} From 98ad5727e078c418df006ae8733ed6e4a43bd7f9 Mon Sep 17 00:00:00 2001 From: thanna23 <148076306+thanna23@users.noreply.github.com> Date: Tue, 17 Nov 2026 16:59:21 +0100 Subject: [PATCH 02/14] feat(listing): refuse a location with a blank name and trim it --- .../polybazaar/listing/model/ListingRules.kt | 9 ++++++--- .../listing/model/ListingRulesTest.kt | 18 ++++++++++++++++++ 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/com/android/polybazaar/listing/model/ListingRules.kt b/app/src/main/java/com/android/polybazaar/listing/model/ListingRules.kt index 156e8008..94ecd9bf 100644 --- a/app/src/main/java/com/android/polybazaar/listing/model/ListingRules.kt +++ b/app/src/main/java/com/android/polybazaar/listing/model/ListingRules.kt @@ -146,7 +146,8 @@ object ListingRules { * @param maxRentalDays kept from the edited item, since the form has no input for it. Ignored for * services. * @param availableDates the days the owner offers the listing on. - * @param location kept from the edited listing, since the form has no input for it. + * @param location where the listing is offered, set in the form. A location with a blank name + * leaves the form incomplete; its name is stored trimmed. */ fun buildListing( type: ListingType, @@ -164,6 +165,8 @@ object ListingRules { ): Listing? { val parsedPrice = parsePrice(price) ?: return null if (title.isBlank() || description.isBlank() || category?.type != type) return null + if (location != null && location.name.isBlank()) return null + val trimmedLocation = location?.copy(name = location.name.trim()) return when (type) { ListingType.ITEM -> ItemListing( @@ -180,7 +183,7 @@ object ListingRules { imagePaths = imagePaths, listingId = listingId, availableDates = availableDates, - location = location, + location = trimmedLocation, ) ListingType.SERVICE -> ServiceListing( @@ -192,7 +195,7 @@ object ListingRules { imagePaths = imagePaths, listingId = listingId, availableDates = availableDates, - location = location, + location = trimmedLocation, ) } } diff --git a/app/src/test/java/com/android/polybazaar/listing/model/ListingRulesTest.kt b/app/src/test/java/com/android/polybazaar/listing/model/ListingRulesTest.kt index d743e6eb..7fc3a364 100644 --- a/app/src/test/java/com/android/polybazaar/listing/model/ListingRulesTest.kt +++ b/app/src/test/java/com/android/polybazaar/listing/model/ListingRulesTest.kt @@ -487,4 +487,22 @@ class ListingRulesTest { assertEquals(location, service?.location) assertNull(withoutLocation?.location) } + + @Test + fun buildListing_refusesABlankLocationName_andTrimsTheOthers() { + fun build(name: String) = + buildListing( + ListingType.SERVICE, + "Tutoring", + "One hour", + "25", + ListingCategory.SERVICE_TUTORING, + emptyList(), + location = ListingLocation(46.52, 6.57, name), + ) + + assertNull(build("")) + assertNull(build(" ")) + assertEquals(ListingLocation(46.52, 6.57, "Flat"), build(" Flat ")?.location) + } } From bc89ebdc0e5c6ccc6269ab6be145eca848ccf7d1 Mon Sep 17 00:00:00 2001 From: thanna23 <148076306+thanna23@users.noreply.github.com> Date: Tue, 17 Nov 2026 17:00:12 +0100 Subject: [PATCH 03/14] feat(listing): set, rename and clear the location in the listing form The picker opens on the chosen or saved location, else the lender's approximate location, else EPFL. A campus name is dropped when the pin moves off campus, and a blank name blocks saving. Wire FusedLocationRepository into both listing forms. --- .../android/polybazaar/PolyBazaarTestCase.kt | 2 + .../com/android/polybazaar/MainActivity.kt | 8 + .../listing/viewmodel/ListingFormViewModel.kt | 76 +++- .../polybazaar/ui/navigation/AppNavHost.kt | 5 + .../map/model/FakeLocationRepository.kt | 19 + .../listing/ui/CreateListingScreenTest.kt | 11 +- .../listing/ui/EditListingScreenTest.kt | 5 +- .../viewmodel/ListingFormViewModelTest.kt | 380 ++++++++++++++++-- .../ui/navigation/AppNavHostTest.kt | 6 + .../ui/navigation/EndToEndFlowTest.kt | 2 + 10 files changed, 486 insertions(+), 28 deletions(-) create mode 100644 app/src/sharedTest/java/com/android/polybazaar/map/model/FakeLocationRepository.kt diff --git a/app/src/androidTest/java/com/android/polybazaar/PolyBazaarTestCase.kt b/app/src/androidTest/java/com/android/polybazaar/PolyBazaarTestCase.kt index 333bea7a..5f6301dd 100644 --- a/app/src/androidTest/java/com/android/polybazaar/PolyBazaarTestCase.kt +++ b/app/src/androidTest/java/com/android/polybazaar/PolyBazaarTestCase.kt @@ -9,6 +9,7 @@ import com.android.polybazaar.auth.viewmodel.AuthViewModel import com.android.polybazaar.chat.model.FakeChatRepository import com.android.polybazaar.listing.model.FakeListingRepository import com.android.polybazaar.listing.model.FilePhotoStorage +import com.android.polybazaar.map.model.FakeLocationRepository import com.android.polybazaar.testing.InMemoryBackend import com.android.polybazaar.ui.navigation.AppNavHost import com.kaspersky.components.composesupport.config.withComposeSupport @@ -54,6 +55,7 @@ abstract class PolyBazaarTestCase : FilePhotoStorage.EDIT_FORM, ), chatRepository = FakeChatRepository(), + locationRepository = FakeLocationRepository(), navController = rememberNavController(), ) } diff --git a/app/src/main/java/com/android/polybazaar/MainActivity.kt b/app/src/main/java/com/android/polybazaar/MainActivity.kt index 43e9ed76..04ca193b 100644 --- a/app/src/main/java/com/android/polybazaar/MainActivity.kt +++ b/app/src/main/java/com/android/polybazaar/MainActivity.kt @@ -19,10 +19,12 @@ import com.android.polybazaar.auth.viewmodel.AuthViewModel import com.android.polybazaar.chat.model.FirebaseChatRepository import com.android.polybazaar.listing.model.FilePhotoStorage import com.android.polybazaar.listing.model.FirebaseListingRepository +import com.android.polybazaar.map.model.FusedLocationRepository import com.android.polybazaar.photo.JpegPhotoCompressor import com.android.polybazaar.profile.model.FirebaseProfileRepository import com.android.polybazaar.ui.navigation.AppNavHost import com.android.polybazaar.ui.theme.PolyBazaarTheme +import com.google.android.gms.location.LocationServices class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { @@ -56,6 +58,12 @@ class MainActivity : ComponentActivity() { editPhotoStorage = remember { FilePhotoStorage(applicationContext, FilePhotoStorage.EDIT_FORM) }, chatRepository = remember { FirebaseChatRepository() }, + locationRepository = + remember { + FusedLocationRepository( + LocationServices.getFusedLocationProviderClient(applicationContext) + ) + }, ) } } diff --git a/app/src/main/java/com/android/polybazaar/listing/viewmodel/ListingFormViewModel.kt b/app/src/main/java/com/android/polybazaar/listing/viewmodel/ListingFormViewModel.kt index 918c0fdf..814888c2 100644 --- a/app/src/main/java/com/android/polybazaar/listing/viewmodel/ListingFormViewModel.kt +++ b/app/src/main/java/com/android/polybazaar/listing/viewmodel/ListingFormViewModel.kt @@ -14,8 +14,10 @@ import com.android.polybazaar.listing.model.ItemListing import com.android.polybazaar.listing.model.Listing import com.android.polybazaar.listing.model.ListingCategory import com.android.polybazaar.listing.model.ListingLocation +import com.android.polybazaar.listing.model.ListingLocations import com.android.polybazaar.listing.model.ListingRepository import com.android.polybazaar.listing.model.ListingRules.MAX_DESCRIPTION_LENGTH +import com.android.polybazaar.listing.model.ListingRules.MAX_LOCATION_NAME_LENGTH import com.android.polybazaar.listing.model.ListingRules.MAX_PHOTOS import com.android.polybazaar.listing.model.ListingRules.MAX_PRICE import com.android.polybazaar.listing.model.ListingRules.MAX_REFUND_VALUE @@ -28,8 +30,12 @@ import com.android.polybazaar.listing.model.ListingRules.isValidRefundInput import com.android.polybazaar.listing.model.ListingRules.parsePrice import com.android.polybazaar.listing.model.ListingType import com.android.polybazaar.listing.model.PhotoStorage +import com.android.polybazaar.map.model.Campus +import com.android.polybazaar.map.model.Coordinates +import com.android.polybazaar.map.model.LocationRepository import java.time.LocalDate import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.Job import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow @@ -47,8 +53,9 @@ import kotlinx.coroutines.launch * @property photos photos on this device, to upload when the form is saved. * @property maxRentalDays kept from the edited listing, so that saving does not erase it. The form * has no input for it yet. - * @property location kept from the edited listing, so that saving does not erase it. The form has - * no input for it yet, so a new listing has none. + * @property location where the listing is offered, picked on the map, or null for none. + * @property suggestedPoint where the map picker opens: the chosen location, else the lender's + * position once found, else EPFL. * @property availableDates the days the owner offers the listing on, chosen in the calendar. * @property today the day earlier days cannot be offered from, for the calendar to use as well. * Always given, so that building a state never reads the clock. @@ -73,6 +80,7 @@ data class ListingFormUiState( val photos: List = emptyList(), val maxRentalDays: Int? = null, val location: ListingLocation? = null, + val suggestedPoint: Coordinates = Campus.EPFL.centre, val availableDates: Set = emptySet(), val isLoading: Boolean = false, val loadError: AppError? = null, @@ -129,6 +137,10 @@ data class ListingFormUiState( val showRefundError: Boolean get() = type == ListingType.ITEM && showAmountError(refundTouched, refundValue, MAX_REFUND_VALUE) + + /** A chosen location needs a name: until it has one, the form cannot be saved. */ + val showLocationNameError: Boolean + get() = location != null && location.name.isBlank() } /** Whether to flag [input] as an invalid amount: only once the user has left a non-empty field. */ @@ -151,6 +163,8 @@ private fun formFor(listing: Listing, today: LocalDate) = storedPhotos = listing.imagePaths, maxRentalDays = (listing as? ItemListing)?.maxRentalDays, location = listing.location, + suggestedPoint = + listing.location?.let { Coordinates(it.latitude, it.longitude) } ?: Campus.EPFL.centre, availableDates = upcomingDays(listing.availableDates, today), today = today, ) @@ -166,6 +180,7 @@ private fun formFor(listing: Listing, today: LocalDate) = * @param savedStateHandle keeps the form when Android kills the app, which can happen while the * camera app is in front. Pass `createSavedStateHandle()` from the factory: a handle made by hand * is not saved by Android. + * @param locationRepository finds the lender, to open the map picker where they are. * @param today the current day, to leave past available days out of an edited listing. */ class ListingFormViewModel( @@ -173,6 +188,7 @@ class ListingFormViewModel( private val listingRepository: ListingRepository, private val photoStorage: PhotoStorage, private val savedStateHandle: SavedStateHandle, + private val locationRepository: LocationRepository, private val today: () -> LocalDate = LocalDate::now, ) : ViewModel() { @@ -189,6 +205,9 @@ class ListingFormViewModel( /** The saved photos being downloaded, so that each is downloaded once at a time. */ private val photosDownloading = mutableSetOf() + /** The running request for the lender's position, see [locateLender]. */ + private var locateJob: Job? = null + /** The photo the camera app is taking, until it closes. */ private var pendingPhoto: Uri? get() = savedStateHandle[PENDING_PHOTO] @@ -282,6 +301,47 @@ class ListingFormViewModel( /** Replaces the days the listing is offered on with those chosen in the calendar. */ fun updateAvailableDates(days: Set) = changeForm { it.copy(availableDates = days) } + /** + * Opens the map picker where the lender is, when the form has no location yet. If their position + * cannot be read, the picker stays on its suggested point and no error is shown. + */ + fun locateLender() { + val state = _uiState.value + // While the edited listing loads, its location would overwrite the result anyway; and one + // request at a time, so repeated calls don't stack Play Services requests. + if (state.location != null || !state.canEdit || locateJob?.isActive == true) return + locateJob = viewModelScope.launch { + locationRepository.currentLocation().onSuccess { point -> + // A location chosen meanwhile is where the picker should open instead. + updateState { if (it.location == null) it.copy(suggestedPoint = point) else it } + } + } + } + + /** + * Sets the location to [point] picked on the map. A point on a campus is named after it; + * otherwise the name typed for the previous point is kept, or left blank for the lender to fill. + * A campus name is not kept: it would mislabel a point off that campus. + */ + fun setLocationPoint(point: Coordinates) = changeForm { + val previous = it.location?.name?.takeUnless(ListingLocations::isCampusName) ?: "" + val name = ListingLocations.campusNameFor(point) ?: previous + it.copy( + location = ListingLocation(point.latitude, point.longitude, name), + suggestedPoint = point, + ) + } + + /** Ignored while no location is set: the name belongs to a point on the map. */ + fun updateLocationName(name: String) = changeForm { + it.copy( + location = it.location?.copy(name = AuthRules.limitInput(name, MAX_LOCATION_NAME_LENGTH)) + ) + } + + /** Removes the location, so the listing is saved without one. */ + fun clearLocation() = changeForm { it.copy(location = null) } + /** * Adds photos picked in the gallery, skipping duplicates and those beyond [MAX_PHOTOS], kept * stored photos included. @@ -437,6 +497,8 @@ class ListingFormViewModel( const val LOCATION_LATITUDE = "locationLatitude" const val LOCATION_LONGITUDE = "locationLongitude" const val LOCATION_NAME = "locationName" + const val SUGGESTED_LATITUDE = "suggestedLatitude" + const val SUGGESTED_LONGITUDE = "suggestedLongitude" const val PENDING_PHOTO = "pendingPhoto" const val RETAKE_INDEX = "retakeIndex" @@ -461,6 +523,8 @@ class ListingFormViewModel( set(LOCATION_LATITUDE, state.location?.latitude) set(LOCATION_LONGITUDE, state.location?.longitude) set(LOCATION_NAME, state.location?.name) + set(SUGGESTED_LATITUDE, state.suggestedPoint.latitude) + set(SUGGESTED_LONGITUDE, state.suggestedPoint.longitude) // As days since 1970: a LongArray survives the app being killed, a set of dates might not. set(AVAILABLE_DATES, state.availableDates.map { it.toEpochDay() }.toLongArray()) } @@ -473,6 +537,13 @@ class ListingFormViewModel( return ListingLocation(latitude, longitude, name) } + /** The saved suggested point, or EPFL when the form had none. */ + fun SavedStateHandle.restoreSuggestedPoint(): Coordinates { + val latitude = get(SUGGESTED_LATITUDE) ?: return Campus.EPFL.centre + val longitude = get(SUGGESTED_LONGITUDE) ?: return Campus.EPFL.centre + return Coordinates(latitude, longitude) + } + /** * The form as it was saved. Its available days before [today] are left out: a form restored on * a later day could otherwise save a day that is already over. @@ -492,6 +563,7 @@ class ListingFormViewModel( photos = get>(PHOTOS).orEmpty(), maxRentalDays = get(MAX_RENTAL_DAYS), location = restoreLocation(), + suggestedPoint = restoreSuggestedPoint(), availableDates = upcomingDays( get(AVAILABLE_DATES)?.map(LocalDate::ofEpochDay)?.toSet().orEmpty(), diff --git a/app/src/main/java/com/android/polybazaar/ui/navigation/AppNavHost.kt b/app/src/main/java/com/android/polybazaar/ui/navigation/AppNavHost.kt index 52561a63..ede6e230 100644 --- a/app/src/main/java/com/android/polybazaar/ui/navigation/AppNavHost.kt +++ b/app/src/main/java/com/android/polybazaar/ui/navigation/AppNavHost.kt @@ -71,6 +71,7 @@ import com.android.polybazaar.listing.ui.ListingDetailActions import com.android.polybazaar.listing.ui.ListingDetailScreen import com.android.polybazaar.listing.viewmodel.ListingDetailViewModel import com.android.polybazaar.listing.viewmodel.ListingFormViewModel +import com.android.polybazaar.map.model.LocationRepository import com.android.polybazaar.profile.model.ProfileRepository import com.android.polybazaar.profile.ui.EditProfileActions import com.android.polybazaar.profile.ui.EditProfileContent @@ -106,6 +107,7 @@ object AppNavHostTags { * @param photoStorage keeps the photos of the listing being created. * @param editPhotoStorage keeps the photos added to the listing being edited. It must use another * folder than [photoStorage]: opening a form deletes the photos its folder holds for other forms. + * @param locationRepository finds the lender, to open the listing form's map picker where they are. */ @Composable fun AppNavHost( @@ -116,6 +118,7 @@ fun AppNavHost( photoStorage: PhotoStorage, editPhotoStorage: PhotoStorage, chatRepository: ChatRepository, + locationRepository: LocationRepository, navController: NavHostController = rememberNavController(), ) { val uiState by authViewModel.uiState.collectAsState() @@ -286,6 +289,7 @@ fun AppNavHost( listingRepository = listingRepository, photoStorage = photoStorage, savedStateHandle = createSavedStateHandle(), + locationRepository = locationRepository, ) } } @@ -312,6 +316,7 @@ fun AppNavHost( listingRepository = listingRepository, photoStorage = editPhotoStorage, savedStateHandle = createSavedStateHandle(), + locationRepository = locationRepository, ) } } diff --git a/app/src/sharedTest/java/com/android/polybazaar/map/model/FakeLocationRepository.kt b/app/src/sharedTest/java/com/android/polybazaar/map/model/FakeLocationRepository.kt new file mode 100644 index 00000000..e47448ce --- /dev/null +++ b/app/src/sharedTest/java/com/android/polybazaar/map/model/FakeLocationRepository.kt @@ -0,0 +1,19 @@ +// Co-authored-by: Claude Code (Claude Opus 5.5) +package com.android.polybazaar.map.model + +/** + * A [LocationRepository] for tests: [currentLocation] returns [result], a failure by default as + * when the permission is refused, and counts its calls in [calls]. + */ +class FakeLocationRepository( + var result: Result = Result.failure(IllegalStateException("No location")) +) : LocationRepository { + + var calls = 0 + private set + + override suspend fun currentLocation(): Result { + calls++ + return result + } +} diff --git a/app/src/test/java/com/android/polybazaar/listing/ui/CreateListingScreenTest.kt b/app/src/test/java/com/android/polybazaar/listing/ui/CreateListingScreenTest.kt index 60f17c92..1943ad24 100644 --- a/app/src/test/java/com/android/polybazaar/listing/ui/CreateListingScreenTest.kt +++ b/app/src/test/java/com/android/polybazaar/listing/ui/CreateListingScreenTest.kt @@ -55,6 +55,7 @@ import com.android.polybazaar.listing.model.ObservedListing import com.android.polybazaar.listing.model.ServiceListing import com.android.polybazaar.listing.viewmodel.ListingFormUiState import com.android.polybazaar.listing.viewmodel.ListingFormViewModel +import com.android.polybazaar.map.model.FakeLocationRepository import java.io.File import java.net.UnknownHostException import java.time.LocalDate @@ -92,7 +93,14 @@ class CreateListingScreenTest { today: () -> LocalDate = LocalDate::now, ): ListingFormViewModel { val viewModel = - ListingFormViewModel(null, repository, createStorage(), SavedStateHandle(), today) + ListingFormViewModel( + null, + repository, + createStorage(), + SavedStateHandle(), + FakeLocationRepository(), + today, + ) setContentWithRegistry(registry) { CreateListingScreen(listingViewModel = viewModel, onListingCreated = onListingCreated) } @@ -878,6 +886,7 @@ class CreateListingScreenTest { RecordingListingRepository(), createStorage(), SavedStateHandle(), + FakeLocationRepository(), ) var createdCount = 0 val owner = diff --git a/app/src/test/java/com/android/polybazaar/listing/ui/EditListingScreenTest.kt b/app/src/test/java/com/android/polybazaar/listing/ui/EditListingScreenTest.kt index d868ecb5..69638d6c 100644 --- a/app/src/test/java/com/android/polybazaar/listing/ui/EditListingScreenTest.kt +++ b/app/src/test/java/com/android/polybazaar/listing/ui/EditListingScreenTest.kt @@ -1,4 +1,4 @@ -// Co-authored-by: Claude Code (Claude Fable 5.2) +// Co-authored-by: Claude Code (Claude Fable 5.2, Claude Opus 5.5) package com.android.polybazaar.listing.ui import android.content.Context @@ -36,6 +36,7 @@ import com.android.polybazaar.listing.model.ListingRules.MAX_PHOTOS import com.android.polybazaar.listing.model.ServiceListing import com.android.polybazaar.listing.viewmodel.ListingFormUiState import com.android.polybazaar.listing.viewmodel.ListingFormViewModel +import com.android.polybazaar.map.model.FakeLocationRepository import java.io.ByteArrayOutputStream import java.net.UnknownHostException import java.time.LocalDate @@ -97,6 +98,7 @@ class EditListingScreenTest { repository, FilePhotoStorage(context, FilePhotoStorage.EDIT_FORM), SavedStateHandle(), + FakeLocationRepository(), ) composeTestRule.setContent { EditListingScreen( @@ -340,6 +342,7 @@ class EditListingScreenTest { repository, FilePhotoStorage(context, FilePhotoStorage.EDIT_FORM), SavedStateHandle(), + FakeLocationRepository(), ) composeTestRule.setContent { dispatcher = LocalOnBackPressedDispatcherOwner.current!!.onBackPressedDispatcher diff --git a/app/src/test/java/com/android/polybazaar/listing/viewmodel/ListingFormViewModelTest.kt b/app/src/test/java/com/android/polybazaar/listing/viewmodel/ListingFormViewModelTest.kt index f58e38e6..6d18463a 100644 --- a/app/src/test/java/com/android/polybazaar/listing/viewmodel/ListingFormViewModelTest.kt +++ b/app/src/test/java/com/android/polybazaar/listing/viewmodel/ListingFormViewModelTest.kt @@ -14,6 +14,7 @@ import com.android.polybazaar.listing.model.ListingCategory import com.android.polybazaar.listing.model.ListingLocation import com.android.polybazaar.listing.model.ListingRepository import com.android.polybazaar.listing.model.ListingRules.MAX_DESCRIPTION_LENGTH +import com.android.polybazaar.listing.model.ListingRules.MAX_LOCATION_NAME_LENGTH import com.android.polybazaar.listing.model.ListingRules.MAX_PHOTOS import com.android.polybazaar.listing.model.ListingRules.MAX_TITLE_LENGTH import com.android.polybazaar.listing.model.ListingType @@ -21,6 +22,9 @@ import com.android.polybazaar.listing.model.ObservedListing import com.android.polybazaar.listing.model.PhotoStorage import com.android.polybazaar.listing.model.ServiceListing import com.android.polybazaar.listing.model.TakenPhoto +import com.android.polybazaar.map.model.Campus +import com.android.polybazaar.map.model.Coordinates +import com.android.polybazaar.map.model.FakeLocationRepository import com.google.firebase.firestore.FirebaseFirestoreException import java.io.IOException import java.net.UnknownHostException @@ -52,6 +56,7 @@ class ListingFormViewModelTest { private lateinit var repository: FakeListingRepository private lateinit var photoStorage: FakePhotoStorage private lateinit var savedStateHandle: SavedStateHandle + private val locationRepository = FakeLocationRepository() private lateinit var viewModel: ListingFormViewModel private val listing = @@ -68,7 +73,10 @@ class ListingFormViewModelTest { repository = FakeListingRepository() photoStorage = FakePhotoStorage() savedStateHandle = SavedStateHandle() - viewModel = ListingFormViewModel(null, repository, photoStorage, savedStateHandle) { today } + viewModel = + ListingFormViewModel(null, repository, photoStorage, savedStateHandle, locationRepository) { + today + } } @After @@ -286,7 +294,13 @@ class ListingFormViewModelTest { viewModel.startTakingPhoto(retakeIndex = null) val restored = - ListingFormViewModel(null, repository, photoStorage, afterAppKilled(savedStateHandle)) + ListingFormViewModel( + null, + repository, + photoStorage, + afterAppKilled(savedStateHandle), + locationRepository, + ) restored.finishTakingPhoto(saved = true) assertEquals( @@ -302,7 +316,7 @@ class ListingFormViewModelTest { viewModel.addPhotos(uris(1)) viewModel.startTakingPhoto(retakeIndex = null) - ListingFormViewModel(null, repository, photoStorage, savedStateHandle) + ListingFormViewModel(null, repository, photoStorage, savedStateHandle, locationRepository) assertEquals(uris(1) + photoStorage.taken[0].uri, photoStorage.keptOnCleanup.last()) } @@ -485,7 +499,13 @@ class ListingFormViewModelTest { assertEquals(AppError.NETWORK, viewModel.uiState.value.saveError) val restored = - ListingFormViewModel(null, repository, photoStorage, afterAppKilled(savedStateHandle)) + ListingFormViewModel( + null, + repository, + photoStorage, + afterAppKilled(savedStateHandle), + locationRepository, + ) // The form comes back, the error of a save that no longer runs does not. assertEquals("Math tutoring", restored.uiState.value.title) @@ -621,7 +641,8 @@ class ListingFormViewModelTest { repository.storedListing = storedItem // The same fixed day as the other forms: with the real date, available days chosen in these // tests end up in the past and are dropped. - val editViewModel = ListingFormViewModel("l1", repository, photoStorage, handle) { today } + val editViewModel = + ListingFormViewModel("l1", repository, photoStorage, handle, locationRepository) { today } testDispatcher.scheduler.advanceUntilIdle() return editViewModel } @@ -640,7 +661,8 @@ class ListingFormViewModelTest { fun edit_showsLoadingUntilTheListingArrives() = runTest { repository.storedListing = storedItem repository.pendingLoad = CompletableDeferred() - val editViewModel = ListingFormViewModel("l1", repository, photoStorage, savedStateHandle) + val editViewModel = + ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) testDispatcher.scheduler.runCurrent() assertTrue(editViewModel.uiState.value.isLoading) @@ -658,7 +680,8 @@ class ListingFormViewModelTest { fun edit_formCannotBeChangedWhileLoading() = runTest { repository.storedListing = storedItem repository.pendingLoad = CompletableDeferred() - val editViewModel = ListingFormViewModel("l1", repository, photoStorage, savedStateHandle) + val editViewModel = + ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) testDispatcher.scheduler.runCurrent() assertFalse(editViewModel.uiState.value.canEdit) @@ -685,7 +708,8 @@ class ListingFormViewModelTest { fun edit_formCannotBeChangedAfterALoadFailure() = runTest { repository.storedListing = storedItem repository.loadFailure = UnknownHostException("offline") - val editViewModel = ListingFormViewModel("l1", repository, photoStorage, savedStateHandle) + val editViewModel = + ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) testDispatcher.scheduler.advanceUntilIdle() assertFalse(editViewModel.uiState.value.canEdit) @@ -709,7 +733,8 @@ class ListingFormViewModelTest { savedStateHandle["pendingPhoto"] = photo repository.storedListing = storedItem repository.pendingLoad = CompletableDeferred() - val editViewModel = ListingFormViewModel("l1", repository, photoStorage, savedStateHandle) + val editViewModel = + ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) testDispatcher.scheduler.runCurrent() editViewModel.finishTakingPhoto(saved = true) @@ -738,7 +763,8 @@ class ListingFormViewModelTest { repository.storedListing = storedItem repository.loadFailure = FirebaseFirestoreException("missing", FirebaseFirestoreException.Code.NOT_FOUND) - val editViewModel = ListingFormViewModel("l1", repository, photoStorage, savedStateHandle) + val editViewModel = + ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) testDispatcher.scheduler.advanceUntilIdle() assertEquals(AppError.NOT_FOUND, editViewModel.uiState.value.loadError) @@ -875,7 +901,8 @@ class ListingFormViewModelTest { fun edit_loadFailureSetsLoadErrorNotSaveError() = runTest { repository.storedListing = storedItem repository.loadFailure = UnknownHostException("offline") - val editViewModel = ListingFormViewModel("l1", repository, photoStorage, savedStateHandle) + val editViewModel = + ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) testDispatcher.scheduler.advanceUntilIdle() assertEquals(AppError.NETWORK, editViewModel.uiState.value.loadError) @@ -887,7 +914,8 @@ class ListingFormViewModelTest { fun edit_listingAboveThePhotoLimitAcceptsNoNewPhotos() = runTest { val paths = (0..MAX_PHOTOS).map { "listings/u/l1/old/$it" } repository.storedListing = storedItem.copy(imagePaths = paths) - val editViewModel = ListingFormViewModel("l1", repository, photoStorage, savedStateHandle) + val editViewModel = + ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) testDispatcher.scheduler.advanceUntilIdle() editViewModel.addPhotos(uris(1)) @@ -902,7 +930,8 @@ class ListingFormViewModelTest { fun edit_cancelledLoadShowsNoErrorAndCanBeRetried() = runTest { repository.storedListing = storedItem repository.loadFailure = CancellationException() - val editViewModel = ListingFormViewModel("l1", repository, photoStorage, savedStateHandle) + val editViewModel = + ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) testDispatcher.scheduler.advanceUntilIdle() // Cancellation means the screen closed, so it is not an error, and the load is not stuck. @@ -920,7 +949,8 @@ class ListingFormViewModelTest { fun edit_loadIsIgnoredWhileOneIsRunning() = runTest { repository.storedListing = storedItem repository.pendingLoad = CompletableDeferred() - val editViewModel = ListingFormViewModel("l1", repository, photoStorage, savedStateHandle) + val editViewModel = + ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) testDispatcher.scheduler.runCurrent() editViewModel.loadListing() @@ -935,7 +965,8 @@ class ListingFormViewModelTest { fun edit_serviceListingLoadsWithoutARefundValue() = runTest { val service = listing.copy(imagePaths = storedPaths, listingId = "l1", ownerUid = "owner") repository.storedListing = service - val editViewModel = ListingFormViewModel("l1", repository, photoStorage, savedStateHandle) + val editViewModel = + ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) testDispatcher.scheduler.advanceUntilIdle() assertEquals("", editViewModel.uiState.value.refundValue) @@ -1104,7 +1135,13 @@ class ListingFormViewModelTest { viewModel.updateAvailableDates(chosenDays) val restored = - ListingFormViewModel(null, repository, photoStorage, afterAppKilled(savedStateHandle)) { + ListingFormViewModel( + null, + repository, + photoStorage, + afterAppKilled(savedStateHandle), + locationRepository, + ) { today } @@ -1114,7 +1151,16 @@ class ListingFormViewModelTest { @Test fun save_afterTheDayChanged_leavesOutTheDaysNowPast() = runTest { var now = today - val form = ListingFormViewModel(null, repository, photoStorage, SavedStateHandle()) { now } + val form = + ListingFormViewModel( + null, + repository, + photoStorage, + SavedStateHandle(), + locationRepository, + ) { + now + } viewModel = form fillForm() form.updateAvailableDates(chosenDays) @@ -1132,7 +1178,13 @@ class ListingFormViewModelTest { val laterDay = LocalDate.of(2026, 11, 20) val restored = - ListingFormViewModel(null, repository, photoStorage, afterAppKilled(savedStateHandle)) { + ListingFormViewModel( + null, + repository, + photoStorage, + afterAppKilled(savedStateHandle), + locationRepository, + ) { laterDay } @@ -1145,7 +1197,9 @@ class ListingFormViewModelTest { repository.storedListing = storedItem.copy(availableDates = chosenDays + LocalDate.of(2026, 11, 9) + today) val editViewModel = - ListingFormViewModel("l1", repository, photoStorage, savedStateHandle) { today } + ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) { + today + } testDispatcher.scheduler.advanceUntilIdle() assertEquals(chosenDays + today, editViewModel.uiState.value.availableDates) @@ -1180,19 +1234,23 @@ class ListingFormViewModelTest { fun edit_loadsTheStoredLocationIntoTheForm() = runTest { repository.storedListing = storedItem.copy(location = storedLocation) val editViewModel = - ListingFormViewModel("l1", repository, photoStorage, savedStateHandle) { today } + ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) { + today + } testDispatcher.scheduler.advanceUntilIdle() assertEquals(storedLocation, editViewModel.uiState.value.location) assertEquals(storedLocation, editViewModel.uiState.value.listing?.location) } - // The form has no input for the location, so saving an edit must send the stored one back. + // Unless the lender changes it, saving an edit must send the stored location back. @Test fun edit_saveKeepsTheStoredLocation() = runTest { repository.storedListing = storedItem.copy(location = storedLocation) val editViewModel = - ListingFormViewModel("l1", repository, photoStorage, savedStateHandle) { today } + ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) { + today + } testDispatcher.scheduler.advanceUntilIdle() repository.result = storedItem.copy(price = 15.0, location = storedLocation) @@ -1217,7 +1275,9 @@ class ListingFormViewModelTest { @Test fun location_survivesTheAppBeingKilled() = runTest { repository.storedListing = storedItem.copy(location = storedLocation) - ListingFormViewModel("l1", repository, photoStorage, savedStateHandle) { today } + ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) { + today + } testDispatcher.scheduler.advanceUntilIdle() assertEquals(storedLocation.latitude, savedStateHandle.get("locationLatitude")) @@ -1249,8 +1309,280 @@ class ListingFormViewModelTest { ) handles.forEach { handle -> - val restored = ListingFormViewModel(null, repository, photoStorage, handle) { today } + val restored = + ListingFormViewModel(null, repository, photoStorage, handle, locationRepository) { today } assertNull(restored.uiState.value.location) } } + + // Location picked on the map + + private val epfl = Campus.EPFL.centre + private val lausanne = Coordinates(46.5167, 6.6291) + private val ouchy = Coordinates(46.5065, 6.6265) + + private fun uiLocation() = viewModel.uiState.value.location + + @Test + fun locateLender_opensThePickerWhereTheLenderIs() = runTest { + locationRepository.result = Result.success(lausanne) + + viewModel.locateLender() + testDispatcher.scheduler.advanceUntilIdle() + + assertEquals(1, locationRepository.calls) + assertEquals(lausanne, viewModel.uiState.value.suggestedPoint) + assertNull(uiLocation()) + } + + @Test + fun locateLender_failureLeavesTheFormUnchangedWithoutError() = runTest { + val before = viewModel.uiState.value + + viewModel.locateLender() + testDispatcher.scheduler.advanceUntilIdle() + + assertEquals(1, locationRepository.calls) + assertEquals(before, viewModel.uiState.value) + assertEquals(epfl, viewModel.uiState.value.suggestedPoint) + } + + @Test + fun locateLender_isSkippedWhenALocationIsSet() = runTest { + locationRepository.result = Result.success(lausanne) + viewModel.setLocationPoint(ouchy) + + viewModel.locateLender() + testDispatcher.scheduler.advanceUntilIdle() + + assertEquals(0, locationRepository.calls) + assertEquals(ouchy, viewModel.uiState.value.suggestedPoint) + } + + @Test + fun locateLender_answeringAfterALocationWasChosen_keepsTheChosenPoint() = runTest { + locationRepository.result = Result.success(lausanne) + + viewModel.locateLender() + viewModel.setLocationPoint(ouchy) + testDispatcher.scheduler.advanceUntilIdle() + + assertEquals(1, locationRepository.calls) + assertEquals(ouchy, viewModel.uiState.value.suggestedPoint) + } + + @Test + fun setLocationPoint_onACampus_isNamedAfterIt() { + val unil = Campus.UNIL.centre + + viewModel.setLocationPoint(unil) + + assertEquals(ListingLocation(unil.latitude, unil.longitude, "UNIL campus"), uiLocation()) + assertEquals(unil, viewModel.uiState.value.suggestedPoint) + assertFalse(viewModel.uiState.value.showLocationNameError) + } + + @Test + fun setLocationPoint_offCampus_isLeftUnnamedAndBlocksSaving() { + fillForm() + + viewModel.setLocationPoint(lausanne) + + assertEquals(ListingLocation(lausanne.latitude, lausanne.longitude, ""), uiLocation()) + assertTrue(viewModel.uiState.value.showLocationNameError) + assertNull(viewModel.uiState.value.listing) + assertFalse(viewModel.uiState.value.canSave) + } + + @Test + fun setLocationPoint_offCampus_keepsTheNameTypedForThePreviousPoint() { + viewModel.setLocationPoint(lausanne) + viewModel.updateLocationName("Flat") + + viewModel.setLocationPoint(ouchy) + assertEquals(ListingLocation(ouchy.latitude, ouchy.longitude, "Flat"), uiLocation()) + + // A campus point names itself, replacing the typed name. + viewModel.setLocationPoint(epfl) + assertEquals("EPFL campus", uiLocation()?.name) + } + + @Test + fun setLocationPoint_movedOffACampus_dropsTheCampusName() { + fillForm() + viewModel.setLocationPoint(epfl) + + viewModel.setLocationPoint(lausanne) + + assertEquals(ListingLocation(lausanne.latitude, lausanne.longitude, ""), uiLocation()) + assertTrue(viewModel.uiState.value.showLocationNameError) + assertFalse(viewModel.uiState.value.canSave) + } + + @Test + fun locateLender_asksOnceAtATime() = runTest { + locationRepository.result = Result.success(lausanne) + + viewModel.locateLender() + viewModel.locateLender() + testDispatcher.scheduler.advanceUntilIdle() + assertEquals(1, locationRepository.calls) + + // Once the first request is over, the lender can be located again. + viewModel.locateLender() + testDispatcher.scheduler.advanceUntilIdle() + assertEquals(2, locationRepository.calls) + } + + @Test + fun locateLender_whileTheEditedListingLoads_asksNothing() = runTest { + locationRepository.result = Result.success(lausanne) + repository.storedListing = storedItem.copy(location = storedLocation) + repository.pendingLoad = CompletableDeferred() + val editViewModel = + ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) + testDispatcher.scheduler.runCurrent() + + editViewModel.locateLender() + repository.pendingLoad!!.complete(Unit) + testDispatcher.scheduler.advanceUntilIdle() + + assertEquals(0, locationRepository.calls) + assertEquals( + Coordinates(storedLocation.latitude, storedLocation.longitude), + editViewModel.uiState.value.suggestedPoint, + ) + } + + @Test + fun updateLocationName_dropsLeadingSpacesAndCapsTheLength() { + viewModel.setLocationPoint(lausanne) + + viewModel.updateLocationName(" Flat ") + assertEquals("Flat ", uiLocation()?.name) + + viewModel.updateLocationName("a".repeat(MAX_LOCATION_NAME_LENGTH + 5)) + assertEquals("a".repeat(MAX_LOCATION_NAME_LENGTH), uiLocation()?.name) + } + + @Test + fun updateLocationName_withoutALocation_changesNothing() { + viewModel.updateLocationName("Flat") + + assertEquals(ListingFormUiState(today = today), viewModel.uiState.value) + } + + @Test + fun clearLocation_removesItAndTheNameError() { + fillForm() + viewModel.setLocationPoint(lausanne) + + viewModel.clearLocation() + + assertNull(uiLocation()) + assertFalse(viewModel.uiState.value.showLocationNameError) + assertTrue(viewModel.uiState.value.canSave) + } + + @Test + fun create_savesTheLocationWithItsNameTrimmed() = runTest { + repository.result = listing + fillForm() + viewModel.setLocationPoint(lausanne) + viewModel.updateLocationName("Flat ") + + viewModel.save() + testDispatcher.scheduler.advanceUntilIdle() + + assertEquals( + ListingLocation(lausanne.latitude, lausanne.longitude, "Flat"), + repository.createdListing?.location, + ) + } + + @Test + fun locationChanges_areIgnoredWhileTheEditedListingLoads() = runTest { + repository.storedListing = storedItem.copy(location = storedLocation) + repository.pendingLoad = CompletableDeferred() + val editViewModel = + ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) + testDispatcher.scheduler.runCurrent() + + editViewModel.setLocationPoint(lausanne) + editViewModel.updateLocationName("Flat") + editViewModel.clearLocation() + assertNull(editViewModel.uiState.value.location) + assertEquals(epfl, editViewModel.uiState.value.suggestedPoint) + + repository.pendingLoad!!.complete(Unit) + testDispatcher.scheduler.advanceUntilIdle() + assertEquals(storedLocation, editViewModel.uiState.value.location) + } + + @Test + fun edit_opensThePickerOnTheStoredLocation_orEpflWithoutOne() = runTest { + repository.storedListing = storedItem.copy(location = ListingLocation(46.5, 6.6, "Flat")) + val withLocation = + ListingFormViewModel("l1", repository, photoStorage, SavedStateHandle(), locationRepository) + testDispatcher.scheduler.advanceUntilIdle() + + assertEquals(Coordinates(46.5, 6.6), withLocation.uiState.value.suggestedPoint) + assertEquals(epfl, editForm().uiState.value.suggestedPoint) + } + + @Test + fun edit_savesTheChangedLocation() = runTest { + repository.storedListing = storedItem.copy(location = storedLocation) + val editViewModel = + ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) { + today + } + testDispatcher.scheduler.advanceUntilIdle() + repository.result = storedItem + + editViewModel.setLocationPoint(Campus.UNIL.centre) + editViewModel.save() + testDispatcher.scheduler.advanceUntilIdle() + + assertEquals("UNIL campus", repository.updatedListings.single().location?.name) + } + + @Test + fun suggestedPointAndUnnamedLocation_surviveTheAppBeingKilled() = runTest { + fun restored() = + ListingFormViewModel( + null, + repository, + photoStorage, + afterAppKilled(savedStateHandle), + locationRepository, + ) { + today + } + .uiState + .value + locationRepository.result = Result.success(lausanne) + viewModel.locateLender() + testDispatcher.scheduler.advanceUntilIdle() + + assertEquals(lausanne, restored().suggestedPoint) + + // A name still being typed, even blank, comes back as it was. + viewModel.setLocationPoint(ouchy) + viewModel.updateLocationName(" ") + val form = restored() + assertEquals(ouchy, form.suggestedPoint) + assertEquals(ListingLocation(ouchy.latitude, ouchy.longitude, ""), form.location) + assertTrue(form.showLocationNameError) + } + + @Test + fun suggestedPoint_partlySavedIsRestoredAsEpfl() { + listOf("suggestedLatitude", "suggestedLongitude").forEach { key -> + val handle = SavedStateHandle(mapOf(key to 46.5)) + val restored = + ListingFormViewModel(null, repository, photoStorage, handle, locationRepository) { today } + assertEquals(epfl, restored.uiState.value.suggestedPoint) + } + } } diff --git a/app/src/test/java/com/android/polybazaar/ui/navigation/AppNavHostTest.kt b/app/src/test/java/com/android/polybazaar/ui/navigation/AppNavHostTest.kt index 560360a9..b14f292d 100644 --- a/app/src/test/java/com/android/polybazaar/ui/navigation/AppNavHostTest.kt +++ b/app/src/test/java/com/android/polybazaar/ui/navigation/AppNavHostTest.kt @@ -75,6 +75,7 @@ import com.android.polybazaar.listing.model.ServiceListing import com.android.polybazaar.listing.ui.CreateListingScreenTags import com.android.polybazaar.listing.ui.EditListingScreenTags import com.android.polybazaar.listing.ui.ListingDetailScreenTags +import com.android.polybazaar.map.model.FakeLocationRepository import com.android.polybazaar.profile.model.ProfileRepository import com.android.polybazaar.profile.ui.EditProfileScreenTags import com.android.polybazaar.profile.ui.LenderProfileScreenTags @@ -153,6 +154,7 @@ class AppNavHostTest { photoStorage = photoStorage, editPhotoStorage = editPhotoStorage, chatRepository = chatRepository, + locationRepository = FakeLocationRepository(), navController = navController, ) } @@ -194,6 +196,7 @@ class AppNavHostTest { photoStorage = photoStorage, editPhotoStorage = editPhotoStorage, chatRepository = chatRepository, + locationRepository = FakeLocationRepository(), navController = navController, ) } @@ -662,6 +665,7 @@ class AppNavHostTest { photoStorage = photoStorage, editPhotoStorage = editPhotoStorage, chatRepository = chatRepository, + locationRepository = FakeLocationRepository(), navController = navController, ) } @@ -1253,6 +1257,7 @@ class AppNavHostTest { photoStorage = photoStorage, editPhotoStorage = editPhotoStorage, chatRepository = chatRepository, + locationRepository = FakeLocationRepository(), navController = navController, ) } @@ -1328,6 +1333,7 @@ class AppNavHostTest { photoStorage = photoStorage, editPhotoStorage = editPhotoStorage, chatRepository = chatRepository, + locationRepository = FakeLocationRepository(), navController = navController, ) } diff --git a/app/src/test/java/com/android/polybazaar/ui/navigation/EndToEndFlowTest.kt b/app/src/test/java/com/android/polybazaar/ui/navigation/EndToEndFlowTest.kt index c05676dd..1ac52ca8 100644 --- a/app/src/test/java/com/android/polybazaar/ui/navigation/EndToEndFlowTest.kt +++ b/app/src/test/java/com/android/polybazaar/ui/navigation/EndToEndFlowTest.kt @@ -34,6 +34,7 @@ import com.android.polybazaar.listing.model.FilePhotoStorage import com.android.polybazaar.listing.model.ItemListing import com.android.polybazaar.listing.model.ListingCategory import com.android.polybazaar.listing.ui.CreateListingScreenTags +import com.android.polybazaar.map.model.FakeLocationRepository import com.android.polybazaar.profile.ui.EditProfileScreenTags import com.android.polybazaar.profile.ui.ProfileScreenTags import com.android.polybazaar.settings.ui.SettingsScreenTags @@ -83,6 +84,7 @@ class EndToEndFlowTest { photoStorage = photoStorage, editPhotoStorage = editPhotoStorage, chatRepository = FakeChatRepository(), + locationRepository = FakeLocationRepository(), navController = navController, ) } From 8dcfa8d4a6c924433430211014ab05d5851f807f Mon Sep 17 00:00:00 2001 From: thanna23 <148076306+thanna23@users.noreply.github.com> Date: Tue, 17 Nov 2026 17:02:04 +0100 Subject: [PATCH 04/14] docs(listing): update why an invalid stored location reads as none --- .../polybazaar/listing/model/FirebaseListingRepository.kt | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/com/android/polybazaar/listing/model/FirebaseListingRepository.kt b/app/src/main/java/com/android/polybazaar/listing/model/FirebaseListingRepository.kt index 3fe4d61c..5f4ca202 100644 --- a/app/src/main/java/com/android/polybazaar/listing/model/FirebaseListingRepository.kt +++ b/app/src/main/java/com/android/polybazaar/listing/model/FirebaseListingRepository.kt @@ -340,9 +340,9 @@ class FirebaseListingRepository( * existed. A malformed one also reads as null rather than hiding the listing, like the available * days: the listing is still worth showing without it. An out-of-range or otherwise invalid * location (as [ListingRules.isValidLocation] checks, the name once trimmed) also reads as null: - * the edit form has no location input and would keep it, so every save would fail; reading it as - * none lets the next edit delete it and keeps the listing editable. The name is trimmed, as the - * app writes it, since the rules accept one with spaces around it. + * an edit form that kept it would fail every save, while reading it as none keeps the listing + * editable. The name is trimmed, as the app writes it, since the rules accept one with spaces + * around it. */ private fun DocumentSnapshot.location(): ListingLocation? { val data = get(LOCATION) as? Map<*, *> ?: return null From 62728ebb1026b0aceb78b2859f243355b6b6c650 Mon Sep 17 00:00:00 2001 From: thanna23 <148076306+thanna23@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:47:43 +0100 Subject: [PATCH 05/14] feat(connectivity): know whether the device can reach the internet Add ConnectivityRepository and its Android version, which follows the default network and counts it as online only once validated. Part of #364. Co-Authored-By: Claude Opus 5.5 --- app/src/main/AndroidManifest.xml | 2 + .../model/ConnectivityRepository.kt | 57 +++++++++++++++++ .../model/FakeConnectivityRepository.kt | 9 +++ .../AndroidConnectivityRepositoryTest.kt | 63 +++++++++++++++++++ 4 files changed, 131 insertions(+) create mode 100644 app/src/main/java/com/android/polybazaar/connectivity/model/ConnectivityRepository.kt create mode 100644 app/src/sharedTest/java/com/android/polybazaar/connectivity/model/FakeConnectivityRepository.kt create mode 100644 app/src/test/java/com/android/polybazaar/connectivity/model/AndroidConnectivityRepositoryTest.kt diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 6b2a57d6..595b6737 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -15,6 +15,8 @@ + + +} + +/** + * A [ConnectivityRepository] that follows Android's default network. + * + * Its callback is never unregistered: create one per process, with the application context, and + * share it, so it lives as long as the app does. + */ +class AndroidConnectivityRepository(context: Context) : ConnectivityRepository { + + private val connectivityManager = + context.applicationContext.getSystemService(ConnectivityManager::class.java) + + private val _isOnline = + MutableStateFlow( + reachesInternet( + connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork) + ) + ) + override val isOnline: StateFlow = _isOnline.asStateFlow() + + init { + connectivityManager.registerDefaultNetworkCallback( + object : ConnectivityManager.NetworkCallback() { + // Also called right after a new default network becomes available. + override fun onCapabilitiesChanged(network: Network, capabilities: NetworkCapabilities) { + _isOnline.value = reachesInternet(capabilities) + } + + override fun onLost(network: Network) { + _isOnline.value = false + } + } + ) + } + + /** Whether [capabilities] reach the internet: validated, so not stuck behind a login page. */ + private fun reachesInternet(capabilities: NetworkCapabilities?): Boolean = + capabilities != null && + capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) && + capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED) +} diff --git a/app/src/sharedTest/java/com/android/polybazaar/connectivity/model/FakeConnectivityRepository.kt b/app/src/sharedTest/java/com/android/polybazaar/connectivity/model/FakeConnectivityRepository.kt new file mode 100644 index 00000000..5cdcef7b --- /dev/null +++ b/app/src/sharedTest/java/com/android/polybazaar/connectivity/model/FakeConnectivityRepository.kt @@ -0,0 +1,9 @@ +// Co-authored-by: Claude Code (Claude Opus 5.5) +package com.android.polybazaar.connectivity.model + +import kotlinx.coroutines.flow.MutableStateFlow + +/** A [ConnectivityRepository] for tests: set [isOnline] to go offline or back online. */ +class FakeConnectivityRepository(online: Boolean = true) : ConnectivityRepository { + override val isOnline = MutableStateFlow(online) +} diff --git a/app/src/test/java/com/android/polybazaar/connectivity/model/AndroidConnectivityRepositoryTest.kt b/app/src/test/java/com/android/polybazaar/connectivity/model/AndroidConnectivityRepositoryTest.kt new file mode 100644 index 00000000..ae2309c0 --- /dev/null +++ b/app/src/test/java/com/android/polybazaar/connectivity/model/AndroidConnectivityRepositoryTest.kt @@ -0,0 +1,63 @@ +// Co-authored-by: Claude Code (Claude Opus 5.5) +package com.android.polybazaar.connectivity.model + +import android.content.Context +import android.net.ConnectivityManager +import android.net.NetworkCapabilities +import androidx.test.core.app.ApplicationProvider +import androidx.test.ext.junit.runners.AndroidJUnit4 +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.Shadows.shadowOf +import org.robolectric.shadows.ShadowNetworkCapabilities + +/** [AndroidConnectivityRepository] on Robolectric's [ConnectivityManager]. */ +@RunWith(AndroidJUnit4::class) +class AndroidConnectivityRepositoryTest { + + private val context: Context = ApplicationProvider.getApplicationContext() + private val connectivityManager = context.getSystemService(ConnectivityManager::class.java) + + private fun capabilities(vararg capabilities: Int): NetworkCapabilities = + ShadowNetworkCapabilities.newInstance().also { network -> + capabilities.forEach { shadowOf(network).addCapability(it) } + } + + private val validated = + capabilities( + NetworkCapabilities.NET_CAPABILITY_INTERNET, + NetworkCapabilities.NET_CAPABILITY_VALIDATED, + ) + + /** Gives the active network [capabilities], then creates the repository. */ + private fun repositoryOn(capabilities: NetworkCapabilities?): AndroidConnectivityRepository { + shadowOf(connectivityManager) + .setNetworkCapabilities(connectivityManager.activeNetwork, capabilities) + return AndroidConnectivityRepository(context) + } + + @Test + fun startsOffline_withoutAValidatedInternetNetwork() { + // Behind a login page, the network has the internet capability but is not validated. + assertFalse( + repositoryOn(capabilities(NetworkCapabilities.NET_CAPABILITY_INTERNET)).isOnline.value + ) + assertFalse(repositoryOn(null).isOnline.value) + } + + @Test + fun followsTheDefaultNetwork() { + val repository = repositoryOn(validated) + val callback = shadowOf(connectivityManager).networkCallbacks.single() + val network = connectivityManager.activeNetwork!! + assertTrue(repository.isOnline.value) + + callback.onLost(network) + assertFalse(repository.isOnline.value) + + callback.onCapabilitiesChanged(network, validated) + assertTrue(repository.isOnline.value) + } +} From 69be9ba1c74af0e2931d1060d8a7263ae3d5f96c Mon Sep 17 00:00:00 2001 From: thanna23 <148076306+thanna23@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:47:44 +0100 Subject: [PATCH 06/14] feat(listing): follow whether the device is online in the listing form The form state exposes isOnline, followed live and never saved, so the location picker can be disabled offline. One ConnectivityRepository per process is passed through AppNavHost to both forms. Part of #364. Co-Authored-By: Claude Opus 5.5 --- .../android/polybazaar/PolyBazaarTestCase.kt | 2 + .../com/android/polybazaar/MainActivity.kt | 15 ++ .../listing/viewmodel/ListingFormViewModel.kt | 25 ++- .../polybazaar/ui/navigation/AppNavHost.kt | 5 + .../listing/ui/CreateListingScreenTest.kt | 3 + .../listing/ui/EditListingScreenTest.kt | 3 + .../viewmodel/ListingFormViewModelTest.kt | 205 ++++++++---------- .../ui/navigation/AppNavHostTest.kt | 6 + .../ui/navigation/EndToEndFlowTest.kt | 2 + 9 files changed, 148 insertions(+), 118 deletions(-) diff --git a/app/src/androidTest/java/com/android/polybazaar/PolyBazaarTestCase.kt b/app/src/androidTest/java/com/android/polybazaar/PolyBazaarTestCase.kt index 5f6301dd..f591b3d3 100644 --- a/app/src/androidTest/java/com/android/polybazaar/PolyBazaarTestCase.kt +++ b/app/src/androidTest/java/com/android/polybazaar/PolyBazaarTestCase.kt @@ -7,6 +7,7 @@ import androidx.navigation.compose.rememberNavController import androidx.test.core.app.ApplicationProvider import com.android.polybazaar.auth.viewmodel.AuthViewModel import com.android.polybazaar.chat.model.FakeChatRepository +import com.android.polybazaar.connectivity.model.FakeConnectivityRepository import com.android.polybazaar.listing.model.FakeListingRepository import com.android.polybazaar.listing.model.FilePhotoStorage import com.android.polybazaar.map.model.FakeLocationRepository @@ -56,6 +57,7 @@ abstract class PolyBazaarTestCase : ), chatRepository = FakeChatRepository(), locationRepository = FakeLocationRepository(), + connectivityRepository = FakeConnectivityRepository(), navController = rememberNavController(), ) } diff --git a/app/src/main/java/com/android/polybazaar/MainActivity.kt b/app/src/main/java/com/android/polybazaar/MainActivity.kt index 04ca193b..4a50f6bc 100644 --- a/app/src/main/java/com/android/polybazaar/MainActivity.kt +++ b/app/src/main/java/com/android/polybazaar/MainActivity.kt @@ -17,6 +17,8 @@ import androidx.lifecycle.viewmodel.viewModelFactory import com.android.polybazaar.auth.model.FirebaseAuthRepository import com.android.polybazaar.auth.viewmodel.AuthViewModel import com.android.polybazaar.chat.model.FirebaseChatRepository +import com.android.polybazaar.connectivity.model.AndroidConnectivityRepository +import com.android.polybazaar.connectivity.model.ConnectivityRepository import com.android.polybazaar.listing.model.FilePhotoStorage import com.android.polybazaar.listing.model.FirebaseListingRepository import com.android.polybazaar.map.model.FusedLocationRepository @@ -64,9 +66,22 @@ class MainActivity : ComponentActivity() { LocationServices.getFusedLocationProviderClient(applicationContext) ) }, + connectivityRepository = connectivityRepository(), ) } } } } + + /** The app's [ConnectivityRepository], created on first use. */ + private fun connectivityRepository(): ConnectivityRepository = + connectivity ?: AndroidConnectivityRepository(applicationContext).also { connectivity = it } + + private companion object { + /** + * One for the whole process, never released: the listing forms' ViewModels outlive a rotated + * activity and keep using it, and its network callback is registered only once. + */ + var connectivity: ConnectivityRepository? = null + } } diff --git a/app/src/main/java/com/android/polybazaar/listing/viewmodel/ListingFormViewModel.kt b/app/src/main/java/com/android/polybazaar/listing/viewmodel/ListingFormViewModel.kt index 814888c2..727461f6 100644 --- a/app/src/main/java/com/android/polybazaar/listing/viewmodel/ListingFormViewModel.kt +++ b/app/src/main/java/com/android/polybazaar/listing/viewmodel/ListingFormViewModel.kt @@ -8,6 +8,7 @@ import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.android.polybazaar.auth.model.AuthRules import com.android.polybazaar.booking.model.upcomingDays +import com.android.polybazaar.connectivity.model.ConnectivityRepository import com.android.polybazaar.error.model.AppError import com.android.polybazaar.error.model.toAppError import com.android.polybazaar.listing.model.ItemListing @@ -64,6 +65,8 @@ import kotlinx.coroutines.launch * until a Retry succeeds. * @property savedListing the saved listing, until the screen has handled it. * @property saveError why the last save failed, or null. + * @property isOnline whether the device is online, which choosing a location on the map needs. + * Followed live, never saved with the form. */ data class ListingFormUiState( val today: LocalDate, @@ -87,6 +90,7 @@ data class ListingFormUiState( val savedListing: Listing? = null, val isSaving: Boolean = false, val saveError: AppError? = null, + val isOnline: Boolean = true, ) { /** Whether this form edits a saved listing rather than creating one. */ val isEditing: Boolean @@ -181,6 +185,8 @@ private fun formFor(listing: Listing, today: LocalDate) = * camera app is in front. Pass `createSavedStateHandle()` from the factory: a handle made by hand * is not saved by Android. * @param locationRepository finds the lender, to open the map picker where they are. + * @param connectivityRepository tells whether the device is online, see + * [ListingFormUiState.isOnline]. * @param today the current day, to leave past available days out of an edited listing. */ class ListingFormViewModel( @@ -189,10 +195,16 @@ class ListingFormViewModel( private val photoStorage: PhotoStorage, private val savedStateHandle: SavedStateHandle, private val locationRepository: LocationRepository, + connectivityRepository: ConnectivityRepository, private val today: () -> LocalDate = LocalDate::now, ) : ViewModel() { - private val _uiState = MutableStateFlow(savedStateHandle.restoreForm(listingId, today())) + private val _uiState = + MutableStateFlow( + savedStateHandle + .restoreForm(listingId, today()) + .copy(isOnline = connectivityRepository.isOnline.value) + ) val uiState: StateFlow = _uiState.asStateFlow() /** @@ -230,6 +242,11 @@ class ListingFormViewModel( photoStorage.deleteAllExcept(_uiState.value.photos + listOfNotNull(pendingPhoto)) // A restored edit form holds the user's changes, which loading the listing would overwrite. if (listingId != null && savedStateHandle.get(LOADED) != true) loadListing() + viewModelScope.launch { + connectivityRepository.isOnline.collect { online -> + _uiState.update { it.copy(isOnline = online) } + } + } } /** @@ -247,7 +264,9 @@ class ListingFormViewModel( .getListing(id) .onSuccess { listing -> savedStateHandle[LOADED] = true - updateState { formFor(listing, today()).copy(isLoading = true) } + updateState { + formFor(listing, today()).copy(isLoading = true, isOnline = it.isOnline) + } } .onFailure { exception -> // Cancellation means the screen was closed: it is not an error to show. @@ -436,7 +455,7 @@ class ListingFormViewModel( val form = if (state.isEditing) formFor(savedListing, today()) else ListingFormUiState(today = today()) - form.copy(savedListing = savedListing) + form.copy(savedListing = savedListing, isOnline = it.isOnline) } } catch (exception: Exception) { if (exception is CancellationException) { diff --git a/app/src/main/java/com/android/polybazaar/ui/navigation/AppNavHost.kt b/app/src/main/java/com/android/polybazaar/ui/navigation/AppNavHost.kt index ede6e230..984788a7 100644 --- a/app/src/main/java/com/android/polybazaar/ui/navigation/AppNavHost.kt +++ b/app/src/main/java/com/android/polybazaar/ui/navigation/AppNavHost.kt @@ -61,6 +61,7 @@ import com.android.polybazaar.chat.ui.ConversationScreen import com.android.polybazaar.chat.ui.InboxScreen import com.android.polybazaar.chat.viewmodel.ConversationViewModel import com.android.polybazaar.chat.viewmodel.InboxViewModel +import com.android.polybazaar.connectivity.model.ConnectivityRepository import com.android.polybazaar.error.model.AppError import com.android.polybazaar.error.ui.message import com.android.polybazaar.listing.model.ListingRepository @@ -108,6 +109,7 @@ object AppNavHostTags { * @param editPhotoStorage keeps the photos added to the listing being edited. It must use another * folder than [photoStorage]: opening a form deletes the photos its folder holds for other forms. * @param locationRepository finds the lender, to open the listing form's map picker where they are. + * @param connectivityRepository tells the listing forms whether the device is online. */ @Composable fun AppNavHost( @@ -119,6 +121,7 @@ fun AppNavHost( editPhotoStorage: PhotoStorage, chatRepository: ChatRepository, locationRepository: LocationRepository, + connectivityRepository: ConnectivityRepository, navController: NavHostController = rememberNavController(), ) { val uiState by authViewModel.uiState.collectAsState() @@ -290,6 +293,7 @@ fun AppNavHost( photoStorage = photoStorage, savedStateHandle = createSavedStateHandle(), locationRepository = locationRepository, + connectivityRepository = connectivityRepository, ) } } @@ -317,6 +321,7 @@ fun AppNavHost( photoStorage = editPhotoStorage, savedStateHandle = createSavedStateHandle(), locationRepository = locationRepository, + connectivityRepository = connectivityRepository, ) } } diff --git a/app/src/test/java/com/android/polybazaar/listing/ui/CreateListingScreenTest.kt b/app/src/test/java/com/android/polybazaar/listing/ui/CreateListingScreenTest.kt index 1943ad24..aa88c48e 100644 --- a/app/src/test/java/com/android/polybazaar/listing/ui/CreateListingScreenTest.kt +++ b/app/src/test/java/com/android/polybazaar/listing/ui/CreateListingScreenTest.kt @@ -45,6 +45,7 @@ import androidx.test.ext.junit.runners.AndroidJUnit4 import com.android.polybazaar.R import com.android.polybazaar.booking.ui.AvailabilityCalendarSheetTags import com.android.polybazaar.booking.ui.AvailabilityCalendarTags +import com.android.polybazaar.connectivity.model.FakeConnectivityRepository import com.android.polybazaar.listing.model.FilePhotoStorage import com.android.polybazaar.listing.model.ItemListing import com.android.polybazaar.listing.model.Listing @@ -99,6 +100,7 @@ class CreateListingScreenTest { createStorage(), SavedStateHandle(), FakeLocationRepository(), + FakeConnectivityRepository(), today, ) setContentWithRegistry(registry) { @@ -887,6 +889,7 @@ class CreateListingScreenTest { createStorage(), SavedStateHandle(), FakeLocationRepository(), + FakeConnectivityRepository(), ) var createdCount = 0 val owner = diff --git a/app/src/test/java/com/android/polybazaar/listing/ui/EditListingScreenTest.kt b/app/src/test/java/com/android/polybazaar/listing/ui/EditListingScreenTest.kt index 69638d6c..464500b8 100644 --- a/app/src/test/java/com/android/polybazaar/listing/ui/EditListingScreenTest.kt +++ b/app/src/test/java/com/android/polybazaar/listing/ui/EditListingScreenTest.kt @@ -27,6 +27,7 @@ import androidx.test.ext.junit.runners.AndroidJUnit4 import com.android.polybazaar.R import com.android.polybazaar.booking.model.formatRuns import com.android.polybazaar.booking.model.groupIntoRuns +import com.android.polybazaar.connectivity.model.FakeConnectivityRepository import com.android.polybazaar.listing.model.FakeListingRepository import com.android.polybazaar.listing.model.FilePhotoStorage import com.android.polybazaar.listing.model.ItemListing @@ -99,6 +100,7 @@ class EditListingScreenTest { FilePhotoStorage(context, FilePhotoStorage.EDIT_FORM), SavedStateHandle(), FakeLocationRepository(), + FakeConnectivityRepository(), ) composeTestRule.setContent { EditListingScreen( @@ -343,6 +345,7 @@ class EditListingScreenTest { FilePhotoStorage(context, FilePhotoStorage.EDIT_FORM), SavedStateHandle(), FakeLocationRepository(), + FakeConnectivityRepository(), ) composeTestRule.setContent { dispatcher = LocalOnBackPressedDispatcherOwner.current!!.onBackPressedDispatcher diff --git a/app/src/test/java/com/android/polybazaar/listing/viewmodel/ListingFormViewModelTest.kt b/app/src/test/java/com/android/polybazaar/listing/viewmodel/ListingFormViewModelTest.kt index 6d18463a..d437b4f3 100644 --- a/app/src/test/java/com/android/polybazaar/listing/viewmodel/ListingFormViewModelTest.kt +++ b/app/src/test/java/com/android/polybazaar/listing/viewmodel/ListingFormViewModelTest.kt @@ -7,6 +7,7 @@ import android.os.Parcel import androidx.core.os.bundleOf import androidx.lifecycle.SavedStateHandle import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.android.polybazaar.connectivity.model.FakeConnectivityRepository import com.android.polybazaar.error.model.AppError import com.android.polybazaar.listing.model.ItemListing import com.android.polybazaar.listing.model.Listing @@ -57,6 +58,7 @@ class ListingFormViewModelTest { private lateinit var photoStorage: FakePhotoStorage private lateinit var savedStateHandle: SavedStateHandle private val locationRepository = FakeLocationRepository() + private val connectivity = FakeConnectivityRepository() private lateinit var viewModel: ListingFormViewModel private val listing = @@ -73,11 +75,24 @@ class ListingFormViewModelTest { repository = FakeListingRepository() photoStorage = FakePhotoStorage() savedStateHandle = SavedStateHandle() - viewModel = - ListingFormViewModel(null, repository, photoStorage, savedStateHandle, locationRepository) { - today - } - } + viewModel = newForm(null) { today } + } + + /** A form on this test's fakes, editing [listingId] or creating a listing when it is null. */ + private fun newForm( + listingId: String?, + handle: SavedStateHandle = savedStateHandle, + today: () -> LocalDate = LocalDate::now, + ) = + ListingFormViewModel( + listingId, + repository, + photoStorage, + handle, + locationRepository, + connectivity, + today, + ) @After fun tearDown() { @@ -293,14 +308,7 @@ class ListingFormViewModelTest { viewModel.addPhotos(uris(1)) viewModel.startTakingPhoto(retakeIndex = null) - val restored = - ListingFormViewModel( - null, - repository, - photoStorage, - afterAppKilled(savedStateHandle), - locationRepository, - ) + val restored = newForm(null, afterAppKilled(savedStateHandle)) restored.finishTakingPhoto(saved = true) assertEquals( @@ -316,7 +324,7 @@ class ListingFormViewModelTest { viewModel.addPhotos(uris(1)) viewModel.startTakingPhoto(retakeIndex = null) - ListingFormViewModel(null, repository, photoStorage, savedStateHandle, locationRepository) + newForm(null) assertEquals(uris(1) + photoStorage.taken[0].uri, photoStorage.keptOnCleanup.last()) } @@ -498,14 +506,7 @@ class ListingFormViewModelTest { testDispatcher.scheduler.advanceUntilIdle() assertEquals(AppError.NETWORK, viewModel.uiState.value.saveError) - val restored = - ListingFormViewModel( - null, - repository, - photoStorage, - afterAppKilled(savedStateHandle), - locationRepository, - ) + val restored = newForm(null, afterAppKilled(savedStateHandle)) // The form comes back, the error of a save that no longer runs does not. assertEquals("Math tutoring", restored.uiState.value.title) @@ -641,8 +642,7 @@ class ListingFormViewModelTest { repository.storedListing = storedItem // The same fixed day as the other forms: with the real date, available days chosen in these // tests end up in the past and are dropped. - val editViewModel = - ListingFormViewModel("l1", repository, photoStorage, handle, locationRepository) { today } + val editViewModel = newForm("l1", handle) { today } testDispatcher.scheduler.advanceUntilIdle() return editViewModel } @@ -661,8 +661,7 @@ class ListingFormViewModelTest { fun edit_showsLoadingUntilTheListingArrives() = runTest { repository.storedListing = storedItem repository.pendingLoad = CompletableDeferred() - val editViewModel = - ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) + val editViewModel = newForm("l1") testDispatcher.scheduler.runCurrent() assertTrue(editViewModel.uiState.value.isLoading) @@ -680,8 +679,7 @@ class ListingFormViewModelTest { fun edit_formCannotBeChangedWhileLoading() = runTest { repository.storedListing = storedItem repository.pendingLoad = CompletableDeferred() - val editViewModel = - ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) + val editViewModel = newForm("l1") testDispatcher.scheduler.runCurrent() assertFalse(editViewModel.uiState.value.canEdit) @@ -708,8 +706,7 @@ class ListingFormViewModelTest { fun edit_formCannotBeChangedAfterALoadFailure() = runTest { repository.storedListing = storedItem repository.loadFailure = UnknownHostException("offline") - val editViewModel = - ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) + val editViewModel = newForm("l1") testDispatcher.scheduler.advanceUntilIdle() assertFalse(editViewModel.uiState.value.canEdit) @@ -733,8 +730,7 @@ class ListingFormViewModelTest { savedStateHandle["pendingPhoto"] = photo repository.storedListing = storedItem repository.pendingLoad = CompletableDeferred() - val editViewModel = - ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) + val editViewModel = newForm("l1") testDispatcher.scheduler.runCurrent() editViewModel.finishTakingPhoto(saved = true) @@ -763,8 +759,7 @@ class ListingFormViewModelTest { repository.storedListing = storedItem repository.loadFailure = FirebaseFirestoreException("missing", FirebaseFirestoreException.Code.NOT_FOUND) - val editViewModel = - ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) + val editViewModel = newForm("l1") testDispatcher.scheduler.advanceUntilIdle() assertEquals(AppError.NOT_FOUND, editViewModel.uiState.value.loadError) @@ -901,8 +896,7 @@ class ListingFormViewModelTest { fun edit_loadFailureSetsLoadErrorNotSaveError() = runTest { repository.storedListing = storedItem repository.loadFailure = UnknownHostException("offline") - val editViewModel = - ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) + val editViewModel = newForm("l1") testDispatcher.scheduler.advanceUntilIdle() assertEquals(AppError.NETWORK, editViewModel.uiState.value.loadError) @@ -914,8 +908,7 @@ class ListingFormViewModelTest { fun edit_listingAboveThePhotoLimitAcceptsNoNewPhotos() = runTest { val paths = (0..MAX_PHOTOS).map { "listings/u/l1/old/$it" } repository.storedListing = storedItem.copy(imagePaths = paths) - val editViewModel = - ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) + val editViewModel = newForm("l1") testDispatcher.scheduler.advanceUntilIdle() editViewModel.addPhotos(uris(1)) @@ -930,8 +923,7 @@ class ListingFormViewModelTest { fun edit_cancelledLoadShowsNoErrorAndCanBeRetried() = runTest { repository.storedListing = storedItem repository.loadFailure = CancellationException() - val editViewModel = - ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) + val editViewModel = newForm("l1") testDispatcher.scheduler.advanceUntilIdle() // Cancellation means the screen closed, so it is not an error, and the load is not stuck. @@ -949,8 +941,7 @@ class ListingFormViewModelTest { fun edit_loadIsIgnoredWhileOneIsRunning() = runTest { repository.storedListing = storedItem repository.pendingLoad = CompletableDeferred() - val editViewModel = - ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) + val editViewModel = newForm("l1") testDispatcher.scheduler.runCurrent() editViewModel.loadListing() @@ -965,8 +956,7 @@ class ListingFormViewModelTest { fun edit_serviceListingLoadsWithoutARefundValue() = runTest { val service = listing.copy(imagePaths = storedPaths, listingId = "l1", ownerUid = "owner") repository.storedListing = service - val editViewModel = - ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) + val editViewModel = newForm("l1") testDispatcher.scheduler.advanceUntilIdle() assertEquals("", editViewModel.uiState.value.refundValue) @@ -1134,16 +1124,7 @@ class ListingFormViewModelTest { fun availableDates_surviveTheAppBeingKilled() = runTest { viewModel.updateAvailableDates(chosenDays) - val restored = - ListingFormViewModel( - null, - repository, - photoStorage, - afterAppKilled(savedStateHandle), - locationRepository, - ) { - today - } + val restored = newForm(null, afterAppKilled(savedStateHandle)) { today } assertEquals(chosenDays, restored.uiState.value.availableDates) } @@ -1151,16 +1132,7 @@ class ListingFormViewModelTest { @Test fun save_afterTheDayChanged_leavesOutTheDaysNowPast() = runTest { var now = today - val form = - ListingFormViewModel( - null, - repository, - photoStorage, - SavedStateHandle(), - locationRepository, - ) { - now - } + val form = newForm(null, SavedStateHandle()) { now } viewModel = form fillForm() form.updateAvailableDates(chosenDays) @@ -1177,16 +1149,7 @@ class ListingFormViewModelTest { viewModel.updateAvailableDates(chosenDays) val laterDay = LocalDate.of(2026, 11, 20) - val restored = - ListingFormViewModel( - null, - repository, - photoStorage, - afterAppKilled(savedStateHandle), - locationRepository, - ) { - laterDay - } + val restored = newForm(null, afterAppKilled(savedStateHandle)) { laterDay } assertEquals(setOf(LocalDate.of(2026, 11, 28)), restored.uiState.value.availableDates) assertEquals(laterDay, restored.uiState.value.today) @@ -1196,10 +1159,7 @@ class ListingFormViewModelTest { fun edit_showsTheStoredAvailableDays_withoutThePastOnes() = runTest { repository.storedListing = storedItem.copy(availableDates = chosenDays + LocalDate.of(2026, 11, 9) + today) - val editViewModel = - ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) { - today - } + val editViewModel = newForm("l1") { today } testDispatcher.scheduler.advanceUntilIdle() assertEquals(chosenDays + today, editViewModel.uiState.value.availableDates) @@ -1233,10 +1193,7 @@ class ListingFormViewModelTest { @Test fun edit_loadsTheStoredLocationIntoTheForm() = runTest { repository.storedListing = storedItem.copy(location = storedLocation) - val editViewModel = - ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) { - today - } + val editViewModel = newForm("l1") { today } testDispatcher.scheduler.advanceUntilIdle() assertEquals(storedLocation, editViewModel.uiState.value.location) @@ -1247,10 +1204,7 @@ class ListingFormViewModelTest { @Test fun edit_saveKeepsTheStoredLocation() = runTest { repository.storedListing = storedItem.copy(location = storedLocation) - val editViewModel = - ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) { - today - } + val editViewModel = newForm("l1") { today } testDispatcher.scheduler.advanceUntilIdle() repository.result = storedItem.copy(price = 15.0, location = storedLocation) @@ -1275,9 +1229,7 @@ class ListingFormViewModelTest { @Test fun location_survivesTheAppBeingKilled() = runTest { repository.storedListing = storedItem.copy(location = storedLocation) - ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) { - today - } + newForm("l1") { today } testDispatcher.scheduler.advanceUntilIdle() assertEquals(storedLocation.latitude, savedStateHandle.get("locationLatitude")) @@ -1309,8 +1261,7 @@ class ListingFormViewModelTest { ) handles.forEach { handle -> - val restored = - ListingFormViewModel(null, repository, photoStorage, handle, locationRepository) { today } + val restored = newForm(null, handle) { today } assertNull(restored.uiState.value.location) } } @@ -1439,8 +1390,7 @@ class ListingFormViewModelTest { locationRepository.result = Result.success(lausanne) repository.storedListing = storedItem.copy(location = storedLocation) repository.pendingLoad = CompletableDeferred() - val editViewModel = - ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) + val editViewModel = newForm("l1") testDispatcher.scheduler.runCurrent() editViewModel.locateLender() @@ -1504,8 +1454,7 @@ class ListingFormViewModelTest { fun locationChanges_areIgnoredWhileTheEditedListingLoads() = runTest { repository.storedListing = storedItem.copy(location = storedLocation) repository.pendingLoad = CompletableDeferred() - val editViewModel = - ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) + val editViewModel = newForm("l1") testDispatcher.scheduler.runCurrent() editViewModel.setLocationPoint(lausanne) @@ -1522,8 +1471,7 @@ class ListingFormViewModelTest { @Test fun edit_opensThePickerOnTheStoredLocation_orEpflWithoutOne() = runTest { repository.storedListing = storedItem.copy(location = ListingLocation(46.5, 6.6, "Flat")) - val withLocation = - ListingFormViewModel("l1", repository, photoStorage, SavedStateHandle(), locationRepository) + val withLocation = newForm("l1", SavedStateHandle()) testDispatcher.scheduler.advanceUntilIdle() assertEquals(Coordinates(46.5, 6.6), withLocation.uiState.value.suggestedPoint) @@ -1533,10 +1481,7 @@ class ListingFormViewModelTest { @Test fun edit_savesTheChangedLocation() = runTest { repository.storedListing = storedItem.copy(location = storedLocation) - val editViewModel = - ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) { - today - } + val editViewModel = newForm("l1") { today } testDispatcher.scheduler.advanceUntilIdle() repository.result = storedItem @@ -1549,18 +1494,7 @@ class ListingFormViewModelTest { @Test fun suggestedPointAndUnnamedLocation_surviveTheAppBeingKilled() = runTest { - fun restored() = - ListingFormViewModel( - null, - repository, - photoStorage, - afterAppKilled(savedStateHandle), - locationRepository, - ) { - today - } - .uiState - .value + fun restored() = newForm(null, afterAppKilled(savedStateHandle)) { today }.uiState.value locationRepository.result = Result.success(lausanne) viewModel.locateLender() testDispatcher.scheduler.advanceUntilIdle() @@ -1580,9 +1514,50 @@ class ListingFormViewModelTest { fun suggestedPoint_partlySavedIsRestoredAsEpfl() { listOf("suggestedLatitude", "suggestedLongitude").forEach { key -> val handle = SavedStateHandle(mapOf(key to 46.5)) - val restored = - ListingFormViewModel(null, repository, photoStorage, handle, locationRepository) { today } + val restored = newForm(null, handle) { today } assertEquals(epfl, restored.uiState.value.suggestedPoint) } } + + @Test + fun isOnline_followsTheConnectivityRepository() = runTest { + connectivity.isOnline.value = false + val form = newForm(null, SavedStateHandle()) + assertFalse(form.uiState.value.isOnline) + + connectivity.isOnline.value = true + testDispatcher.scheduler.advanceUntilIdle() + assertTrue(form.uiState.value.isOnline) + } + + @Test + fun isOnline_isKeptWhenTheEditedListingLoads() = runTest { + repository.storedListing = storedItem + repository.pendingLoad = CompletableDeferred() + val form = newForm("l1") + testDispatcher.scheduler.advanceUntilIdle() + connectivity.isOnline.value = false + testDispatcher.scheduler.advanceUntilIdle() + + repository.pendingLoad!!.complete(Unit) + testDispatcher.scheduler.advanceUntilIdle() + + assertEquals(storedItem.title, form.uiState.value.title) + assertFalse(form.uiState.value.isOnline) + } + + @Test + fun isOnline_isKeptWhenTheFormResetsAfterSaving() = runTest { + repository.result = listing + testDispatcher.scheduler.advanceUntilIdle() + connectivity.isOnline.value = false + testDispatcher.scheduler.advanceUntilIdle() + fillForm() + + viewModel.save() + testDispatcher.scheduler.advanceUntilIdle() + + assertEquals(listing, viewModel.uiState.value.savedListing) + assertFalse(viewModel.uiState.value.isOnline) + } } diff --git a/app/src/test/java/com/android/polybazaar/ui/navigation/AppNavHostTest.kt b/app/src/test/java/com/android/polybazaar/ui/navigation/AppNavHostTest.kt index b14f292d..c5e71b3a 100644 --- a/app/src/test/java/com/android/polybazaar/ui/navigation/AppNavHostTest.kt +++ b/app/src/test/java/com/android/polybazaar/ui/navigation/AppNavHostTest.kt @@ -65,6 +65,7 @@ import com.android.polybazaar.chat.model.Conversation import com.android.polybazaar.chat.model.FakeChatRepository import com.android.polybazaar.chat.ui.ConversationScreenTags import com.android.polybazaar.chat.ui.InboxScreenTags +import com.android.polybazaar.connectivity.model.FakeConnectivityRepository import com.android.polybazaar.error.model.AppError import com.android.polybazaar.error.model.AppException import com.android.polybazaar.listing.model.FakeListingRepository @@ -155,6 +156,7 @@ class AppNavHostTest { editPhotoStorage = editPhotoStorage, chatRepository = chatRepository, locationRepository = FakeLocationRepository(), + connectivityRepository = FakeConnectivityRepository(), navController = navController, ) } @@ -197,6 +199,7 @@ class AppNavHostTest { editPhotoStorage = editPhotoStorage, chatRepository = chatRepository, locationRepository = FakeLocationRepository(), + connectivityRepository = FakeConnectivityRepository(), navController = navController, ) } @@ -666,6 +669,7 @@ class AppNavHostTest { editPhotoStorage = editPhotoStorage, chatRepository = chatRepository, locationRepository = FakeLocationRepository(), + connectivityRepository = FakeConnectivityRepository(), navController = navController, ) } @@ -1258,6 +1262,7 @@ class AppNavHostTest { editPhotoStorage = editPhotoStorage, chatRepository = chatRepository, locationRepository = FakeLocationRepository(), + connectivityRepository = FakeConnectivityRepository(), navController = navController, ) } @@ -1334,6 +1339,7 @@ class AppNavHostTest { editPhotoStorage = editPhotoStorage, chatRepository = chatRepository, locationRepository = FakeLocationRepository(), + connectivityRepository = FakeConnectivityRepository(), navController = navController, ) } diff --git a/app/src/test/java/com/android/polybazaar/ui/navigation/EndToEndFlowTest.kt b/app/src/test/java/com/android/polybazaar/ui/navigation/EndToEndFlowTest.kt index 1ac52ca8..abd31d48 100644 --- a/app/src/test/java/com/android/polybazaar/ui/navigation/EndToEndFlowTest.kt +++ b/app/src/test/java/com/android/polybazaar/ui/navigation/EndToEndFlowTest.kt @@ -29,6 +29,7 @@ import com.android.polybazaar.auth.ui.VerifyEmailScreenTags import com.android.polybazaar.auth.viewmodel.AuthViewModel import com.android.polybazaar.browse.ui.BrowseScreenTags import com.android.polybazaar.chat.model.FakeChatRepository +import com.android.polybazaar.connectivity.model.FakeConnectivityRepository import com.android.polybazaar.listing.model.FakeListingRepository import com.android.polybazaar.listing.model.FilePhotoStorage import com.android.polybazaar.listing.model.ItemListing @@ -85,6 +86,7 @@ class EndToEndFlowTest { editPhotoStorage = editPhotoStorage, chatRepository = FakeChatRepository(), locationRepository = FakeLocationRepository(), + connectivityRepository = FakeConnectivityRepository(), navController = navController, ) } From ef028f4247f4cd328a9c807869284303312c46fe Mon Sep 17 00:00:00 2001 From: thanna23 <148076306+thanna23@users.noreply.github.com> Date: Thu, 19 Nov 2026 11:18:57 +0100 Subject: [PATCH 07/14] revert: stop following connectivity in the listing form Reverts 69be9ba. Nothing reads isOnline yet, and it isn't part of #364: it moves to its own PR next to the map picker (#365), which disables the picker offline. Co-Authored-By: Claude Opus 5.5 --- .../android/polybazaar/PolyBazaarTestCase.kt | 2 - .../com/android/polybazaar/MainActivity.kt | 15 -- .../listing/viewmodel/ListingFormViewModel.kt | 25 +-- .../polybazaar/ui/navigation/AppNavHost.kt | 5 - .../listing/ui/CreateListingScreenTest.kt | 3 - .../listing/ui/EditListingScreenTest.kt | 3 - .../viewmodel/ListingFormViewModelTest.kt | 205 ++++++++++-------- .../ui/navigation/AppNavHostTest.kt | 6 - .../ui/navigation/EndToEndFlowTest.kt | 2 - 9 files changed, 118 insertions(+), 148 deletions(-) diff --git a/app/src/androidTest/java/com/android/polybazaar/PolyBazaarTestCase.kt b/app/src/androidTest/java/com/android/polybazaar/PolyBazaarTestCase.kt index 6db7ff76..7fce26d5 100644 --- a/app/src/androidTest/java/com/android/polybazaar/PolyBazaarTestCase.kt +++ b/app/src/androidTest/java/com/android/polybazaar/PolyBazaarTestCase.kt @@ -9,7 +9,6 @@ import androidx.test.core.app.ApplicationProvider import com.android.polybazaar.auth.viewmodel.AuthViewModel import com.android.polybazaar.booking.model.FakeBookingRepository import com.android.polybazaar.chat.model.FakeChatRepository -import com.android.polybazaar.connectivity.model.FakeConnectivityRepository import com.android.polybazaar.listing.model.FakeListingRepository import com.android.polybazaar.listing.model.FilePhotoStorage import com.android.polybazaar.map.model.FakeLocationRepository @@ -59,7 +58,6 @@ abstract class PolyBazaarTestCase : ), chatRepository = FakeChatRepository(), locationRepository = FakeLocationRepository(), - connectivityRepository = FakeConnectivityRepository(), bookingRepository = FakeBookingRepository(), navController = rememberNavController(), ) diff --git a/app/src/main/java/com/android/polybazaar/MainActivity.kt b/app/src/main/java/com/android/polybazaar/MainActivity.kt index 92fdda3a..439a2712 100644 --- a/app/src/main/java/com/android/polybazaar/MainActivity.kt +++ b/app/src/main/java/com/android/polybazaar/MainActivity.kt @@ -19,8 +19,6 @@ import com.android.polybazaar.auth.model.FirebaseAuthRepository import com.android.polybazaar.auth.viewmodel.AuthViewModel import com.android.polybazaar.booking.model.FirebaseBookingRepository import com.android.polybazaar.chat.model.FirebaseChatRepository -import com.android.polybazaar.connectivity.model.AndroidConnectivityRepository -import com.android.polybazaar.connectivity.model.ConnectivityRepository import com.android.polybazaar.listing.model.FilePhotoStorage import com.android.polybazaar.listing.model.FirebaseListingRepository import com.android.polybazaar.map.model.FusedLocationRepository @@ -72,22 +70,9 @@ class MainActivity : ComponentActivity() { LocationServices.getFusedLocationProviderClient(applicationContext) ) }, - connectivityRepository = connectivityRepository(), ) } } } } - - /** The app's [ConnectivityRepository], created on first use. */ - private fun connectivityRepository(): ConnectivityRepository = - connectivity ?: AndroidConnectivityRepository(applicationContext).also { connectivity = it } - - private companion object { - /** - * One for the whole process, never released: the listing forms' ViewModels outlive a rotated - * activity and keep using it, and its network callback is registered only once. - */ - var connectivity: ConnectivityRepository? = null - } } diff --git a/app/src/main/java/com/android/polybazaar/listing/viewmodel/ListingFormViewModel.kt b/app/src/main/java/com/android/polybazaar/listing/viewmodel/ListingFormViewModel.kt index 727461f6..814888c2 100644 --- a/app/src/main/java/com/android/polybazaar/listing/viewmodel/ListingFormViewModel.kt +++ b/app/src/main/java/com/android/polybazaar/listing/viewmodel/ListingFormViewModel.kt @@ -8,7 +8,6 @@ import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.android.polybazaar.auth.model.AuthRules import com.android.polybazaar.booking.model.upcomingDays -import com.android.polybazaar.connectivity.model.ConnectivityRepository import com.android.polybazaar.error.model.AppError import com.android.polybazaar.error.model.toAppError import com.android.polybazaar.listing.model.ItemListing @@ -65,8 +64,6 @@ import kotlinx.coroutines.launch * until a Retry succeeds. * @property savedListing the saved listing, until the screen has handled it. * @property saveError why the last save failed, or null. - * @property isOnline whether the device is online, which choosing a location on the map needs. - * Followed live, never saved with the form. */ data class ListingFormUiState( val today: LocalDate, @@ -90,7 +87,6 @@ data class ListingFormUiState( val savedListing: Listing? = null, val isSaving: Boolean = false, val saveError: AppError? = null, - val isOnline: Boolean = true, ) { /** Whether this form edits a saved listing rather than creating one. */ val isEditing: Boolean @@ -185,8 +181,6 @@ private fun formFor(listing: Listing, today: LocalDate) = * camera app is in front. Pass `createSavedStateHandle()` from the factory: a handle made by hand * is not saved by Android. * @param locationRepository finds the lender, to open the map picker where they are. - * @param connectivityRepository tells whether the device is online, see - * [ListingFormUiState.isOnline]. * @param today the current day, to leave past available days out of an edited listing. */ class ListingFormViewModel( @@ -195,16 +189,10 @@ class ListingFormViewModel( private val photoStorage: PhotoStorage, private val savedStateHandle: SavedStateHandle, private val locationRepository: LocationRepository, - connectivityRepository: ConnectivityRepository, private val today: () -> LocalDate = LocalDate::now, ) : ViewModel() { - private val _uiState = - MutableStateFlow( - savedStateHandle - .restoreForm(listingId, today()) - .copy(isOnline = connectivityRepository.isOnline.value) - ) + private val _uiState = MutableStateFlow(savedStateHandle.restoreForm(listingId, today())) val uiState: StateFlow = _uiState.asStateFlow() /** @@ -242,11 +230,6 @@ class ListingFormViewModel( photoStorage.deleteAllExcept(_uiState.value.photos + listOfNotNull(pendingPhoto)) // A restored edit form holds the user's changes, which loading the listing would overwrite. if (listingId != null && savedStateHandle.get(LOADED) != true) loadListing() - viewModelScope.launch { - connectivityRepository.isOnline.collect { online -> - _uiState.update { it.copy(isOnline = online) } - } - } } /** @@ -264,9 +247,7 @@ class ListingFormViewModel( .getListing(id) .onSuccess { listing -> savedStateHandle[LOADED] = true - updateState { - formFor(listing, today()).copy(isLoading = true, isOnline = it.isOnline) - } + updateState { formFor(listing, today()).copy(isLoading = true) } } .onFailure { exception -> // Cancellation means the screen was closed: it is not an error to show. @@ -455,7 +436,7 @@ class ListingFormViewModel( val form = if (state.isEditing) formFor(savedListing, today()) else ListingFormUiState(today = today()) - form.copy(savedListing = savedListing, isOnline = it.isOnline) + form.copy(savedListing = savedListing) } } catch (exception: Exception) { if (exception is CancellationException) { diff --git a/app/src/main/java/com/android/polybazaar/ui/navigation/AppNavHost.kt b/app/src/main/java/com/android/polybazaar/ui/navigation/AppNavHost.kt index 4895edfb..07f83b09 100644 --- a/app/src/main/java/com/android/polybazaar/ui/navigation/AppNavHost.kt +++ b/app/src/main/java/com/android/polybazaar/ui/navigation/AppNavHost.kt @@ -72,7 +72,6 @@ import com.android.polybazaar.chat.ui.InboxScreen import com.android.polybazaar.chat.viewmodel.ConversationViewModel import com.android.polybazaar.chat.viewmodel.InboxViewModel import com.android.polybazaar.chat.viewmodel.photoUploadScope -import com.android.polybazaar.connectivity.model.ConnectivityRepository import com.android.polybazaar.error.model.AppError import com.android.polybazaar.error.ui.message import com.android.polybazaar.listing.model.FilePhotoStorage @@ -122,7 +121,6 @@ object AppNavHostTags { * @param editPhotoStorage keeps the photos added to the listing being edited. It must use another * folder than [photoStorage]: opening a form deletes the photos its folder holds for other forms. * @param locationRepository finds the lender, to open the listing form's map picker where they are. - * @param connectivityRepository tells the listing forms whether the device is online. */ @Composable fun AppNavHost( @@ -134,7 +132,6 @@ fun AppNavHost( editPhotoStorage: PhotoStorage, chatRepository: ChatRepository, locationRepository: LocationRepository, - connectivityRepository: ConnectivityRepository, bookingRepository: BookingRepository, navController: NavHostController = rememberNavController(), ) { @@ -307,7 +304,6 @@ fun AppNavHost( photoStorage = photoStorage, savedStateHandle = createSavedStateHandle(), locationRepository = locationRepository, - connectivityRepository = connectivityRepository, ) } } @@ -335,7 +331,6 @@ fun AppNavHost( photoStorage = editPhotoStorage, savedStateHandle = createSavedStateHandle(), locationRepository = locationRepository, - connectivityRepository = connectivityRepository, ) } } diff --git a/app/src/test/java/com/android/polybazaar/listing/ui/CreateListingScreenTest.kt b/app/src/test/java/com/android/polybazaar/listing/ui/CreateListingScreenTest.kt index aa88c48e..1943ad24 100644 --- a/app/src/test/java/com/android/polybazaar/listing/ui/CreateListingScreenTest.kt +++ b/app/src/test/java/com/android/polybazaar/listing/ui/CreateListingScreenTest.kt @@ -45,7 +45,6 @@ import androidx.test.ext.junit.runners.AndroidJUnit4 import com.android.polybazaar.R import com.android.polybazaar.booking.ui.AvailabilityCalendarSheetTags import com.android.polybazaar.booking.ui.AvailabilityCalendarTags -import com.android.polybazaar.connectivity.model.FakeConnectivityRepository import com.android.polybazaar.listing.model.FilePhotoStorage import com.android.polybazaar.listing.model.ItemListing import com.android.polybazaar.listing.model.Listing @@ -100,7 +99,6 @@ class CreateListingScreenTest { createStorage(), SavedStateHandle(), FakeLocationRepository(), - FakeConnectivityRepository(), today, ) setContentWithRegistry(registry) { @@ -889,7 +887,6 @@ class CreateListingScreenTest { createStorage(), SavedStateHandle(), FakeLocationRepository(), - FakeConnectivityRepository(), ) var createdCount = 0 val owner = diff --git a/app/src/test/java/com/android/polybazaar/listing/ui/EditListingScreenTest.kt b/app/src/test/java/com/android/polybazaar/listing/ui/EditListingScreenTest.kt index 464500b8..69638d6c 100644 --- a/app/src/test/java/com/android/polybazaar/listing/ui/EditListingScreenTest.kt +++ b/app/src/test/java/com/android/polybazaar/listing/ui/EditListingScreenTest.kt @@ -27,7 +27,6 @@ import androidx.test.ext.junit.runners.AndroidJUnit4 import com.android.polybazaar.R import com.android.polybazaar.booking.model.formatRuns import com.android.polybazaar.booking.model.groupIntoRuns -import com.android.polybazaar.connectivity.model.FakeConnectivityRepository import com.android.polybazaar.listing.model.FakeListingRepository import com.android.polybazaar.listing.model.FilePhotoStorage import com.android.polybazaar.listing.model.ItemListing @@ -100,7 +99,6 @@ class EditListingScreenTest { FilePhotoStorage(context, FilePhotoStorage.EDIT_FORM), SavedStateHandle(), FakeLocationRepository(), - FakeConnectivityRepository(), ) composeTestRule.setContent { EditListingScreen( @@ -345,7 +343,6 @@ class EditListingScreenTest { FilePhotoStorage(context, FilePhotoStorage.EDIT_FORM), SavedStateHandle(), FakeLocationRepository(), - FakeConnectivityRepository(), ) composeTestRule.setContent { dispatcher = LocalOnBackPressedDispatcherOwner.current!!.onBackPressedDispatcher diff --git a/app/src/test/java/com/android/polybazaar/listing/viewmodel/ListingFormViewModelTest.kt b/app/src/test/java/com/android/polybazaar/listing/viewmodel/ListingFormViewModelTest.kt index d437b4f3..6d18463a 100644 --- a/app/src/test/java/com/android/polybazaar/listing/viewmodel/ListingFormViewModelTest.kt +++ b/app/src/test/java/com/android/polybazaar/listing/viewmodel/ListingFormViewModelTest.kt @@ -7,7 +7,6 @@ import android.os.Parcel import androidx.core.os.bundleOf import androidx.lifecycle.SavedStateHandle import androidx.test.ext.junit.runners.AndroidJUnit4 -import com.android.polybazaar.connectivity.model.FakeConnectivityRepository import com.android.polybazaar.error.model.AppError import com.android.polybazaar.listing.model.ItemListing import com.android.polybazaar.listing.model.Listing @@ -58,7 +57,6 @@ class ListingFormViewModelTest { private lateinit var photoStorage: FakePhotoStorage private lateinit var savedStateHandle: SavedStateHandle private val locationRepository = FakeLocationRepository() - private val connectivity = FakeConnectivityRepository() private lateinit var viewModel: ListingFormViewModel private val listing = @@ -75,24 +73,11 @@ class ListingFormViewModelTest { repository = FakeListingRepository() photoStorage = FakePhotoStorage() savedStateHandle = SavedStateHandle() - viewModel = newForm(null) { today } - } - - /** A form on this test's fakes, editing [listingId] or creating a listing when it is null. */ - private fun newForm( - listingId: String?, - handle: SavedStateHandle = savedStateHandle, - today: () -> LocalDate = LocalDate::now, - ) = - ListingFormViewModel( - listingId, - repository, - photoStorage, - handle, - locationRepository, - connectivity, - today, - ) + viewModel = + ListingFormViewModel(null, repository, photoStorage, savedStateHandle, locationRepository) { + today + } + } @After fun tearDown() { @@ -308,7 +293,14 @@ class ListingFormViewModelTest { viewModel.addPhotos(uris(1)) viewModel.startTakingPhoto(retakeIndex = null) - val restored = newForm(null, afterAppKilled(savedStateHandle)) + val restored = + ListingFormViewModel( + null, + repository, + photoStorage, + afterAppKilled(savedStateHandle), + locationRepository, + ) restored.finishTakingPhoto(saved = true) assertEquals( @@ -324,7 +316,7 @@ class ListingFormViewModelTest { viewModel.addPhotos(uris(1)) viewModel.startTakingPhoto(retakeIndex = null) - newForm(null) + ListingFormViewModel(null, repository, photoStorage, savedStateHandle, locationRepository) assertEquals(uris(1) + photoStorage.taken[0].uri, photoStorage.keptOnCleanup.last()) } @@ -506,7 +498,14 @@ class ListingFormViewModelTest { testDispatcher.scheduler.advanceUntilIdle() assertEquals(AppError.NETWORK, viewModel.uiState.value.saveError) - val restored = newForm(null, afterAppKilled(savedStateHandle)) + val restored = + ListingFormViewModel( + null, + repository, + photoStorage, + afterAppKilled(savedStateHandle), + locationRepository, + ) // The form comes back, the error of a save that no longer runs does not. assertEquals("Math tutoring", restored.uiState.value.title) @@ -642,7 +641,8 @@ class ListingFormViewModelTest { repository.storedListing = storedItem // The same fixed day as the other forms: with the real date, available days chosen in these // tests end up in the past and are dropped. - val editViewModel = newForm("l1", handle) { today } + val editViewModel = + ListingFormViewModel("l1", repository, photoStorage, handle, locationRepository) { today } testDispatcher.scheduler.advanceUntilIdle() return editViewModel } @@ -661,7 +661,8 @@ class ListingFormViewModelTest { fun edit_showsLoadingUntilTheListingArrives() = runTest { repository.storedListing = storedItem repository.pendingLoad = CompletableDeferred() - val editViewModel = newForm("l1") + val editViewModel = + ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) testDispatcher.scheduler.runCurrent() assertTrue(editViewModel.uiState.value.isLoading) @@ -679,7 +680,8 @@ class ListingFormViewModelTest { fun edit_formCannotBeChangedWhileLoading() = runTest { repository.storedListing = storedItem repository.pendingLoad = CompletableDeferred() - val editViewModel = newForm("l1") + val editViewModel = + ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) testDispatcher.scheduler.runCurrent() assertFalse(editViewModel.uiState.value.canEdit) @@ -706,7 +708,8 @@ class ListingFormViewModelTest { fun edit_formCannotBeChangedAfterALoadFailure() = runTest { repository.storedListing = storedItem repository.loadFailure = UnknownHostException("offline") - val editViewModel = newForm("l1") + val editViewModel = + ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) testDispatcher.scheduler.advanceUntilIdle() assertFalse(editViewModel.uiState.value.canEdit) @@ -730,7 +733,8 @@ class ListingFormViewModelTest { savedStateHandle["pendingPhoto"] = photo repository.storedListing = storedItem repository.pendingLoad = CompletableDeferred() - val editViewModel = newForm("l1") + val editViewModel = + ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) testDispatcher.scheduler.runCurrent() editViewModel.finishTakingPhoto(saved = true) @@ -759,7 +763,8 @@ class ListingFormViewModelTest { repository.storedListing = storedItem repository.loadFailure = FirebaseFirestoreException("missing", FirebaseFirestoreException.Code.NOT_FOUND) - val editViewModel = newForm("l1") + val editViewModel = + ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) testDispatcher.scheduler.advanceUntilIdle() assertEquals(AppError.NOT_FOUND, editViewModel.uiState.value.loadError) @@ -896,7 +901,8 @@ class ListingFormViewModelTest { fun edit_loadFailureSetsLoadErrorNotSaveError() = runTest { repository.storedListing = storedItem repository.loadFailure = UnknownHostException("offline") - val editViewModel = newForm("l1") + val editViewModel = + ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) testDispatcher.scheduler.advanceUntilIdle() assertEquals(AppError.NETWORK, editViewModel.uiState.value.loadError) @@ -908,7 +914,8 @@ class ListingFormViewModelTest { fun edit_listingAboveThePhotoLimitAcceptsNoNewPhotos() = runTest { val paths = (0..MAX_PHOTOS).map { "listings/u/l1/old/$it" } repository.storedListing = storedItem.copy(imagePaths = paths) - val editViewModel = newForm("l1") + val editViewModel = + ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) testDispatcher.scheduler.advanceUntilIdle() editViewModel.addPhotos(uris(1)) @@ -923,7 +930,8 @@ class ListingFormViewModelTest { fun edit_cancelledLoadShowsNoErrorAndCanBeRetried() = runTest { repository.storedListing = storedItem repository.loadFailure = CancellationException() - val editViewModel = newForm("l1") + val editViewModel = + ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) testDispatcher.scheduler.advanceUntilIdle() // Cancellation means the screen closed, so it is not an error, and the load is not stuck. @@ -941,7 +949,8 @@ class ListingFormViewModelTest { fun edit_loadIsIgnoredWhileOneIsRunning() = runTest { repository.storedListing = storedItem repository.pendingLoad = CompletableDeferred() - val editViewModel = newForm("l1") + val editViewModel = + ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) testDispatcher.scheduler.runCurrent() editViewModel.loadListing() @@ -956,7 +965,8 @@ class ListingFormViewModelTest { fun edit_serviceListingLoadsWithoutARefundValue() = runTest { val service = listing.copy(imagePaths = storedPaths, listingId = "l1", ownerUid = "owner") repository.storedListing = service - val editViewModel = newForm("l1") + val editViewModel = + ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) testDispatcher.scheduler.advanceUntilIdle() assertEquals("", editViewModel.uiState.value.refundValue) @@ -1124,7 +1134,16 @@ class ListingFormViewModelTest { fun availableDates_surviveTheAppBeingKilled() = runTest { viewModel.updateAvailableDates(chosenDays) - val restored = newForm(null, afterAppKilled(savedStateHandle)) { today } + val restored = + ListingFormViewModel( + null, + repository, + photoStorage, + afterAppKilled(savedStateHandle), + locationRepository, + ) { + today + } assertEquals(chosenDays, restored.uiState.value.availableDates) } @@ -1132,7 +1151,16 @@ class ListingFormViewModelTest { @Test fun save_afterTheDayChanged_leavesOutTheDaysNowPast() = runTest { var now = today - val form = newForm(null, SavedStateHandle()) { now } + val form = + ListingFormViewModel( + null, + repository, + photoStorage, + SavedStateHandle(), + locationRepository, + ) { + now + } viewModel = form fillForm() form.updateAvailableDates(chosenDays) @@ -1149,7 +1177,16 @@ class ListingFormViewModelTest { viewModel.updateAvailableDates(chosenDays) val laterDay = LocalDate.of(2026, 11, 20) - val restored = newForm(null, afterAppKilled(savedStateHandle)) { laterDay } + val restored = + ListingFormViewModel( + null, + repository, + photoStorage, + afterAppKilled(savedStateHandle), + locationRepository, + ) { + laterDay + } assertEquals(setOf(LocalDate.of(2026, 11, 28)), restored.uiState.value.availableDates) assertEquals(laterDay, restored.uiState.value.today) @@ -1159,7 +1196,10 @@ class ListingFormViewModelTest { fun edit_showsTheStoredAvailableDays_withoutThePastOnes() = runTest { repository.storedListing = storedItem.copy(availableDates = chosenDays + LocalDate.of(2026, 11, 9) + today) - val editViewModel = newForm("l1") { today } + val editViewModel = + ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) { + today + } testDispatcher.scheduler.advanceUntilIdle() assertEquals(chosenDays + today, editViewModel.uiState.value.availableDates) @@ -1193,7 +1233,10 @@ class ListingFormViewModelTest { @Test fun edit_loadsTheStoredLocationIntoTheForm() = runTest { repository.storedListing = storedItem.copy(location = storedLocation) - val editViewModel = newForm("l1") { today } + val editViewModel = + ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) { + today + } testDispatcher.scheduler.advanceUntilIdle() assertEquals(storedLocation, editViewModel.uiState.value.location) @@ -1204,7 +1247,10 @@ class ListingFormViewModelTest { @Test fun edit_saveKeepsTheStoredLocation() = runTest { repository.storedListing = storedItem.copy(location = storedLocation) - val editViewModel = newForm("l1") { today } + val editViewModel = + ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) { + today + } testDispatcher.scheduler.advanceUntilIdle() repository.result = storedItem.copy(price = 15.0, location = storedLocation) @@ -1229,7 +1275,9 @@ class ListingFormViewModelTest { @Test fun location_survivesTheAppBeingKilled() = runTest { repository.storedListing = storedItem.copy(location = storedLocation) - newForm("l1") { today } + ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) { + today + } testDispatcher.scheduler.advanceUntilIdle() assertEquals(storedLocation.latitude, savedStateHandle.get("locationLatitude")) @@ -1261,7 +1309,8 @@ class ListingFormViewModelTest { ) handles.forEach { handle -> - val restored = newForm(null, handle) { today } + val restored = + ListingFormViewModel(null, repository, photoStorage, handle, locationRepository) { today } assertNull(restored.uiState.value.location) } } @@ -1390,7 +1439,8 @@ class ListingFormViewModelTest { locationRepository.result = Result.success(lausanne) repository.storedListing = storedItem.copy(location = storedLocation) repository.pendingLoad = CompletableDeferred() - val editViewModel = newForm("l1") + val editViewModel = + ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) testDispatcher.scheduler.runCurrent() editViewModel.locateLender() @@ -1454,7 +1504,8 @@ class ListingFormViewModelTest { fun locationChanges_areIgnoredWhileTheEditedListingLoads() = runTest { repository.storedListing = storedItem.copy(location = storedLocation) repository.pendingLoad = CompletableDeferred() - val editViewModel = newForm("l1") + val editViewModel = + ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) testDispatcher.scheduler.runCurrent() editViewModel.setLocationPoint(lausanne) @@ -1471,7 +1522,8 @@ class ListingFormViewModelTest { @Test fun edit_opensThePickerOnTheStoredLocation_orEpflWithoutOne() = runTest { repository.storedListing = storedItem.copy(location = ListingLocation(46.5, 6.6, "Flat")) - val withLocation = newForm("l1", SavedStateHandle()) + val withLocation = + ListingFormViewModel("l1", repository, photoStorage, SavedStateHandle(), locationRepository) testDispatcher.scheduler.advanceUntilIdle() assertEquals(Coordinates(46.5, 6.6), withLocation.uiState.value.suggestedPoint) @@ -1481,7 +1533,10 @@ class ListingFormViewModelTest { @Test fun edit_savesTheChangedLocation() = runTest { repository.storedListing = storedItem.copy(location = storedLocation) - val editViewModel = newForm("l1") { today } + val editViewModel = + ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) { + today + } testDispatcher.scheduler.advanceUntilIdle() repository.result = storedItem @@ -1494,7 +1549,18 @@ class ListingFormViewModelTest { @Test fun suggestedPointAndUnnamedLocation_surviveTheAppBeingKilled() = runTest { - fun restored() = newForm(null, afterAppKilled(savedStateHandle)) { today }.uiState.value + fun restored() = + ListingFormViewModel( + null, + repository, + photoStorage, + afterAppKilled(savedStateHandle), + locationRepository, + ) { + today + } + .uiState + .value locationRepository.result = Result.success(lausanne) viewModel.locateLender() testDispatcher.scheduler.advanceUntilIdle() @@ -1514,50 +1580,9 @@ class ListingFormViewModelTest { fun suggestedPoint_partlySavedIsRestoredAsEpfl() { listOf("suggestedLatitude", "suggestedLongitude").forEach { key -> val handle = SavedStateHandle(mapOf(key to 46.5)) - val restored = newForm(null, handle) { today } + val restored = + ListingFormViewModel(null, repository, photoStorage, handle, locationRepository) { today } assertEquals(epfl, restored.uiState.value.suggestedPoint) } } - - @Test - fun isOnline_followsTheConnectivityRepository() = runTest { - connectivity.isOnline.value = false - val form = newForm(null, SavedStateHandle()) - assertFalse(form.uiState.value.isOnline) - - connectivity.isOnline.value = true - testDispatcher.scheduler.advanceUntilIdle() - assertTrue(form.uiState.value.isOnline) - } - - @Test - fun isOnline_isKeptWhenTheEditedListingLoads() = runTest { - repository.storedListing = storedItem - repository.pendingLoad = CompletableDeferred() - val form = newForm("l1") - testDispatcher.scheduler.advanceUntilIdle() - connectivity.isOnline.value = false - testDispatcher.scheduler.advanceUntilIdle() - - repository.pendingLoad!!.complete(Unit) - testDispatcher.scheduler.advanceUntilIdle() - - assertEquals(storedItem.title, form.uiState.value.title) - assertFalse(form.uiState.value.isOnline) - } - - @Test - fun isOnline_isKeptWhenTheFormResetsAfterSaving() = runTest { - repository.result = listing - testDispatcher.scheduler.advanceUntilIdle() - connectivity.isOnline.value = false - testDispatcher.scheduler.advanceUntilIdle() - fillForm() - - viewModel.save() - testDispatcher.scheduler.advanceUntilIdle() - - assertEquals(listing, viewModel.uiState.value.savedListing) - assertFalse(viewModel.uiState.value.isOnline) - } } diff --git a/app/src/test/java/com/android/polybazaar/ui/navigation/AppNavHostTest.kt b/app/src/test/java/com/android/polybazaar/ui/navigation/AppNavHostTest.kt index 7ebe8d86..b0604285 100644 --- a/app/src/test/java/com/android/polybazaar/ui/navigation/AppNavHostTest.kt +++ b/app/src/test/java/com/android/polybazaar/ui/navigation/AppNavHostTest.kt @@ -73,7 +73,6 @@ import com.android.polybazaar.chat.model.Conversation import com.android.polybazaar.chat.model.FakeChatRepository import com.android.polybazaar.chat.ui.ConversationScreenTags import com.android.polybazaar.chat.ui.InboxScreenTags -import com.android.polybazaar.connectivity.model.FakeConnectivityRepository import com.android.polybazaar.error.model.AppError import com.android.polybazaar.error.model.AppException import com.android.polybazaar.listing.model.FakeListingRepository @@ -166,7 +165,6 @@ class AppNavHostTest { editPhotoStorage = editPhotoStorage, chatRepository = chatRepository, locationRepository = FakeLocationRepository(), - connectivityRepository = FakeConnectivityRepository(), bookingRepository = bookingRepository, navController = navController, ) @@ -210,7 +208,6 @@ class AppNavHostTest { editPhotoStorage = editPhotoStorage, chatRepository = chatRepository, locationRepository = FakeLocationRepository(), - connectivityRepository = FakeConnectivityRepository(), bookingRepository = bookingRepository, navController = navController, ) @@ -681,7 +678,6 @@ class AppNavHostTest { editPhotoStorage = editPhotoStorage, chatRepository = chatRepository, locationRepository = FakeLocationRepository(), - connectivityRepository = FakeConnectivityRepository(), bookingRepository = bookingRepository, navController = navController, ) @@ -1514,7 +1510,6 @@ class AppNavHostTest { editPhotoStorage = editPhotoStorage, chatRepository = chatRepository, locationRepository = FakeLocationRepository(), - connectivityRepository = FakeConnectivityRepository(), bookingRepository = bookingRepository, navController = navController, ) @@ -1592,7 +1587,6 @@ class AppNavHostTest { editPhotoStorage = editPhotoStorage, chatRepository = chatRepository, locationRepository = FakeLocationRepository(), - connectivityRepository = FakeConnectivityRepository(), bookingRepository = bookingRepository, navController = navController, ) diff --git a/app/src/test/java/com/android/polybazaar/ui/navigation/EndToEndFlowTest.kt b/app/src/test/java/com/android/polybazaar/ui/navigation/EndToEndFlowTest.kt index 51ad3685..49ee02c6 100644 --- a/app/src/test/java/com/android/polybazaar/ui/navigation/EndToEndFlowTest.kt +++ b/app/src/test/java/com/android/polybazaar/ui/navigation/EndToEndFlowTest.kt @@ -31,7 +31,6 @@ import com.android.polybazaar.auth.viewmodel.AuthViewModel import com.android.polybazaar.booking.model.FakeBookingRepository import com.android.polybazaar.browse.ui.BrowseScreenTags import com.android.polybazaar.chat.model.FakeChatRepository -import com.android.polybazaar.connectivity.model.FakeConnectivityRepository import com.android.polybazaar.listing.model.FakeListingRepository import com.android.polybazaar.listing.model.FilePhotoStorage import com.android.polybazaar.listing.model.ItemListing @@ -88,7 +87,6 @@ class EndToEndFlowTest { editPhotoStorage = editPhotoStorage, chatRepository = FakeChatRepository(), locationRepository = FakeLocationRepository(), - connectivityRepository = FakeConnectivityRepository(), bookingRepository = FakeBookingRepository(), navController = navController, ) From 3115d5f2ecb05c56b3e97016f1add746d847d740 Mon Sep 17 00:00:00 2001 From: thanna23 <148076306+thanna23@users.noreply.github.com> Date: Thu, 19 Nov 2026 11:19:06 +0100 Subject: [PATCH 08/14] revert: remove the connectivity repository from this PR Reverts 62728eb (ConnectivityRepository, its Android version and fake, and the ACCESS_NETWORK_STATE permission). Not part of #364; it moves to its own PR with #365. Co-Authored-By: Claude Opus 5.5 --- app/src/main/AndroidManifest.xml | 2 - .../model/ConnectivityRepository.kt | 57 ----------------- .../model/FakeConnectivityRepository.kt | 9 --- .../AndroidConnectivityRepositoryTest.kt | 63 ------------------- 4 files changed, 131 deletions(-) delete mode 100644 app/src/main/java/com/android/polybazaar/connectivity/model/ConnectivityRepository.kt delete mode 100644 app/src/sharedTest/java/com/android/polybazaar/connectivity/model/FakeConnectivityRepository.kt delete mode 100644 app/src/test/java/com/android/polybazaar/connectivity/model/AndroidConnectivityRepositoryTest.kt diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 595b6737..6b2a57d6 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -15,8 +15,6 @@ - - -} - -/** - * A [ConnectivityRepository] that follows Android's default network. - * - * Its callback is never unregistered: create one per process, with the application context, and - * share it, so it lives as long as the app does. - */ -class AndroidConnectivityRepository(context: Context) : ConnectivityRepository { - - private val connectivityManager = - context.applicationContext.getSystemService(ConnectivityManager::class.java) - - private val _isOnline = - MutableStateFlow( - reachesInternet( - connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork) - ) - ) - override val isOnline: StateFlow = _isOnline.asStateFlow() - - init { - connectivityManager.registerDefaultNetworkCallback( - object : ConnectivityManager.NetworkCallback() { - // Also called right after a new default network becomes available. - override fun onCapabilitiesChanged(network: Network, capabilities: NetworkCapabilities) { - _isOnline.value = reachesInternet(capabilities) - } - - override fun onLost(network: Network) { - _isOnline.value = false - } - } - ) - } - - /** Whether [capabilities] reach the internet: validated, so not stuck behind a login page. */ - private fun reachesInternet(capabilities: NetworkCapabilities?): Boolean = - capabilities != null && - capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) && - capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED) -} diff --git a/app/src/sharedTest/java/com/android/polybazaar/connectivity/model/FakeConnectivityRepository.kt b/app/src/sharedTest/java/com/android/polybazaar/connectivity/model/FakeConnectivityRepository.kt deleted file mode 100644 index 5cdcef7b..00000000 --- a/app/src/sharedTest/java/com/android/polybazaar/connectivity/model/FakeConnectivityRepository.kt +++ /dev/null @@ -1,9 +0,0 @@ -// Co-authored-by: Claude Code (Claude Opus 5.5) -package com.android.polybazaar.connectivity.model - -import kotlinx.coroutines.flow.MutableStateFlow - -/** A [ConnectivityRepository] for tests: set [isOnline] to go offline or back online. */ -class FakeConnectivityRepository(online: Boolean = true) : ConnectivityRepository { - override val isOnline = MutableStateFlow(online) -} diff --git a/app/src/test/java/com/android/polybazaar/connectivity/model/AndroidConnectivityRepositoryTest.kt b/app/src/test/java/com/android/polybazaar/connectivity/model/AndroidConnectivityRepositoryTest.kt deleted file mode 100644 index ae2309c0..00000000 --- a/app/src/test/java/com/android/polybazaar/connectivity/model/AndroidConnectivityRepositoryTest.kt +++ /dev/null @@ -1,63 +0,0 @@ -// Co-authored-by: Claude Code (Claude Opus 5.5) -package com.android.polybazaar.connectivity.model - -import android.content.Context -import android.net.ConnectivityManager -import android.net.NetworkCapabilities -import androidx.test.core.app.ApplicationProvider -import androidx.test.ext.junit.runners.AndroidJUnit4 -import org.junit.Assert.assertFalse -import org.junit.Assert.assertTrue -import org.junit.Test -import org.junit.runner.RunWith -import org.robolectric.Shadows.shadowOf -import org.robolectric.shadows.ShadowNetworkCapabilities - -/** [AndroidConnectivityRepository] on Robolectric's [ConnectivityManager]. */ -@RunWith(AndroidJUnit4::class) -class AndroidConnectivityRepositoryTest { - - private val context: Context = ApplicationProvider.getApplicationContext() - private val connectivityManager = context.getSystemService(ConnectivityManager::class.java) - - private fun capabilities(vararg capabilities: Int): NetworkCapabilities = - ShadowNetworkCapabilities.newInstance().also { network -> - capabilities.forEach { shadowOf(network).addCapability(it) } - } - - private val validated = - capabilities( - NetworkCapabilities.NET_CAPABILITY_INTERNET, - NetworkCapabilities.NET_CAPABILITY_VALIDATED, - ) - - /** Gives the active network [capabilities], then creates the repository. */ - private fun repositoryOn(capabilities: NetworkCapabilities?): AndroidConnectivityRepository { - shadowOf(connectivityManager) - .setNetworkCapabilities(connectivityManager.activeNetwork, capabilities) - return AndroidConnectivityRepository(context) - } - - @Test - fun startsOffline_withoutAValidatedInternetNetwork() { - // Behind a login page, the network has the internet capability but is not validated. - assertFalse( - repositoryOn(capabilities(NetworkCapabilities.NET_CAPABILITY_INTERNET)).isOnline.value - ) - assertFalse(repositoryOn(null).isOnline.value) - } - - @Test - fun followsTheDefaultNetwork() { - val repository = repositoryOn(validated) - val callback = shadowOf(connectivityManager).networkCallbacks.single() - val network = connectivityManager.activeNetwork!! - assertTrue(repository.isOnline.value) - - callback.onLost(network) - assertFalse(repository.isOnline.value) - - callback.onCapabilitiesChanged(network, validated) - assertTrue(repository.isOnline.value) - } -} From 4cfcb4eb88d4a0c6b544e749c61625e47543aee6 Mon Sep 17 00:00:00 2001 From: thanna23 <148076306+thanna23@users.noreply.github.com> Date: Thu, 19 Nov 2026 11:20:54 +0100 Subject: [PATCH 09/14] docs(map): say the listing form keeps the approximate location on the device The LocationRepository KDoc and the ACCESS_COARSE_LOCATION comment said the location is never stored, but the listing form now keeps it in its saved state to reopen the map picker there after the app is killed. It is still never sent to the backend. Co-Authored-By: Claude Opus 5.5 --- app/src/main/AndroidManifest.xml | 6 ++++-- .../com/android/polybazaar/map/model/LocationRepository.kt | 5 ++++- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 6b2a57d6..d21d9861 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -12,8 +12,10 @@ - + } From e9b4d504f596990536cb09c7a7867c184e80d23c Mon Sep 17 00:00:00 2001 From: thanna23 <148076306+thanna23@users.noreply.github.com> Date: Thu, 19 Nov 2026 11:29:00 +0100 Subject: [PATCH 10/14] style(map): format the LocationRepository KDoc with ktfmt Co-Authored-By: Claude Opus 5.5 --- .../com/android/polybazaar/map/model/LocationRepository.kt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/com/android/polybazaar/map/model/LocationRepository.kt b/app/src/main/java/com/android/polybazaar/map/model/LocationRepository.kt index 50dec329..23af57a3 100644 --- a/app/src/main/java/com/android/polybazaar/map/model/LocationRepository.kt +++ b/app/src/main/java/com/android/polybazaar/map/model/LocationRepository.kt @@ -11,8 +11,8 @@ interface LocationRepository { * available (for example offline without a recent one), or when Play Services cannot answer. The * caller then falls back to a campus. * - * The location is never sent to the backend. The listing form keeps it on the device, in its saved - * state, so the map picker still opens there after the app is killed. + * The location is never sent to the backend. The listing form keeps it on the device, in its + * saved state, so the map picker still opens there after the app is killed. */ suspend fun currentLocation(): Result } From a6742c5f7704b5c31ce12c546b629670c0daea60 Mon Sep 17 00:00:00 2001 From: thanna23 <148076306+thanna23@users.noreply.github.com> Date: Thu, 19 Nov 2026 11:29:01 +0100 Subject: [PATCH 11/14] fix(listing): flag a missing location name only once its field is left Like the price and refund, showLocationNameError now waits for leaveLocationNameField(), so picking a point off campus no longer shows an error before the lender can type a name. Saving stays blocked while the name is blank. clearLocation() resets the flag, and it survives the app being killed. Co-Authored-By: Claude Opus 5.5 --- .../listing/viewmodel/ListingFormViewModel.kt | 22 ++++++++++++++---- .../viewmodel/ListingFormViewModelTest.kt | 23 +++++++++++++++++-- 2 files changed, 39 insertions(+), 6 deletions(-) diff --git a/app/src/main/java/com/android/polybazaar/listing/viewmodel/ListingFormViewModel.kt b/app/src/main/java/com/android/polybazaar/listing/viewmodel/ListingFormViewModel.kt index 814888c2..a06c8505 100644 --- a/app/src/main/java/com/android/polybazaar/listing/viewmodel/ListingFormViewModel.kt +++ b/app/src/main/java/com/android/polybazaar/listing/viewmodel/ListingFormViewModel.kt @@ -54,6 +54,8 @@ import kotlinx.coroutines.launch * @property maxRentalDays kept from the edited listing, so that saving does not erase it. The form * has no input for it yet. * @property location where the listing is offered, picked on the map, or null for none. + * @property locationNameTouched whether the user has left the location's name field, like + * [priceTouched]: a missing name is only flagged after that. * @property suggestedPoint where the map picker opens: the chosen location, else the lender's * position once found, else EPFL. * @property availableDates the days the owner offers the listing on, chosen in the calendar. @@ -80,6 +82,7 @@ data class ListingFormUiState( val photos: List = emptyList(), val maxRentalDays: Int? = null, val location: ListingLocation? = null, + val locationNameTouched: Boolean = false, val suggestedPoint: Coordinates = Campus.EPFL.centre, val availableDates: Set = emptySet(), val isLoading: Boolean = false, @@ -138,9 +141,12 @@ data class ListingFormUiState( get() = type == ListingType.ITEM && showAmountError(refundTouched, refundValue, MAX_REFUND_VALUE) - /** A chosen location needs a name: until it has one, the form cannot be saved. */ + /** + * A chosen location needs a name: until it has one, the form cannot be saved. Like the price, the + * missing name is only flagged once the user has left its field. + */ val showLocationNameError: Boolean - get() = location != null && location.name.isBlank() + get() = locationNameTouched && location != null && location.name.isBlank() } /** Whether to flag [input] as an invalid amount: only once the user has left a non-empty field. */ @@ -339,8 +345,13 @@ class ListingFormViewModel( ) } - /** Removes the location, so the listing is saved without one. */ - fun clearLocation() = changeForm { it.copy(location = null) } + fun leaveLocationNameField() = changeForm { it.copy(locationNameTouched = true) } + + /** + * Removes the location, so the listing is saved without one. A location picked again later starts + * without a name error. + */ + fun clearLocation() = changeForm { it.copy(location = null, locationNameTouched = false) } /** * Adds photos picked in the gallery, skipping duplicates and those beyond [MAX_PHOTOS], kept @@ -497,6 +508,7 @@ class ListingFormViewModel( const val LOCATION_LATITUDE = "locationLatitude" const val LOCATION_LONGITUDE = "locationLongitude" const val LOCATION_NAME = "locationName" + const val LOCATION_NAME_TOUCHED = "locationNameTouched" const val SUGGESTED_LATITUDE = "suggestedLatitude" const val SUGGESTED_LONGITUDE = "suggestedLongitude" const val PENDING_PHOTO = "pendingPhoto" @@ -523,6 +535,7 @@ class ListingFormViewModel( set(LOCATION_LATITUDE, state.location?.latitude) set(LOCATION_LONGITUDE, state.location?.longitude) set(LOCATION_NAME, state.location?.name) + set(LOCATION_NAME_TOUCHED, state.locationNameTouched) set(SUGGESTED_LATITUDE, state.suggestedPoint.latitude) set(SUGGESTED_LONGITUDE, state.suggestedPoint.longitude) // As days since 1970: a LongArray survives the app being killed, a set of dates might not. @@ -563,6 +576,7 @@ class ListingFormViewModel( photos = get>(PHOTOS).orEmpty(), maxRentalDays = get(MAX_RENTAL_DAYS), location = restoreLocation(), + locationNameTouched = get(LOCATION_NAME_TOUCHED) ?: false, suggestedPoint = restoreSuggestedPoint(), availableDates = upcomingDays( diff --git a/app/src/test/java/com/android/polybazaar/listing/viewmodel/ListingFormViewModelTest.kt b/app/src/test/java/com/android/polybazaar/listing/viewmodel/ListingFormViewModelTest.kt index 6d18463a..b107e0aa 100644 --- a/app/src/test/java/com/android/polybazaar/listing/viewmodel/ListingFormViewModelTest.kt +++ b/app/src/test/java/com/android/polybazaar/listing/viewmodel/ListingFormViewModelTest.kt @@ -1389,11 +1389,25 @@ class ListingFormViewModelTest { viewModel.setLocationPoint(lausanne) assertEquals(ListingLocation(lausanne.latitude, lausanne.longitude, ""), uiLocation()) - assertTrue(viewModel.uiState.value.showLocationNameError) assertNull(viewModel.uiState.value.listing) assertFalse(viewModel.uiState.value.canSave) } + @Test + fun locationNameError_showsOnlyOnceTheNameFieldIsLeft() { + fillForm() + viewModel.setLocationPoint(lausanne) + // The lender has not had a chance to type a name yet. + assertFalse(viewModel.uiState.value.showLocationNameError) + + viewModel.leaveLocationNameField() + assertTrue(viewModel.uiState.value.showLocationNameError) + + viewModel.updateLocationName("Flat") + assertFalse(viewModel.uiState.value.showLocationNameError) + assertTrue(viewModel.uiState.value.canSave) + } + @Test fun setLocationPoint_offCampus_keepsTheNameTypedForThePreviousPoint() { viewModel.setLocationPoint(lausanne) @@ -1415,7 +1429,6 @@ class ListingFormViewModelTest { viewModel.setLocationPoint(lausanne) assertEquals(ListingLocation(lausanne.latitude, lausanne.longitude, ""), uiLocation()) - assertTrue(viewModel.uiState.value.showLocationNameError) assertFalse(viewModel.uiState.value.canSave) } @@ -1476,12 +1489,17 @@ class ListingFormViewModelTest { fun clearLocation_removesItAndTheNameError() { fillForm() viewModel.setLocationPoint(lausanne) + viewModel.leaveLocationNameField() viewModel.clearLocation() assertNull(uiLocation()) assertFalse(viewModel.uiState.value.showLocationNameError) assertTrue(viewModel.uiState.value.canSave) + + // A point picked again starts without the error, until its name field is left. + viewModel.setLocationPoint(ouchy) + assertFalse(viewModel.uiState.value.showLocationNameError) } @Test @@ -1570,6 +1588,7 @@ class ListingFormViewModelTest { // A name still being typed, even blank, comes back as it was. viewModel.setLocationPoint(ouchy) viewModel.updateLocationName(" ") + viewModel.leaveLocationNameField() val form = restored() assertEquals(ouchy, form.suggestedPoint) assertEquals(ListingLocation(ouchy.latitude, ouchy.longitude, ""), form.location) From 3b6f37039f36cb86c1aef066c8fc9fcf22b477e7 Mon Sep 17 00:00:00 2001 From: thanna23 <148076306+thanna23@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:47:43 +0100 Subject: [PATCH 12/14] feat(connectivity): know whether the device can reach the internet Add ConnectivityRepository and its Android version, which follows the default network and counts it as online only once validated. Part of #364. Co-Authored-By: Claude Opus 5.5 --- app/src/main/AndroidManifest.xml | 2 + .../model/ConnectivityRepository.kt | 57 +++++++++++++++++ .../model/FakeConnectivityRepository.kt | 9 +++ .../AndroidConnectivityRepositoryTest.kt | 63 +++++++++++++++++++ 4 files changed, 131 insertions(+) create mode 100644 app/src/main/java/com/android/polybazaar/connectivity/model/ConnectivityRepository.kt create mode 100644 app/src/sharedTest/java/com/android/polybazaar/connectivity/model/FakeConnectivityRepository.kt create mode 100644 app/src/test/java/com/android/polybazaar/connectivity/model/AndroidConnectivityRepositoryTest.kt diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index d21d9861..fae0ddb6 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -17,6 +17,8 @@ keeps it on the device, in its saved state, so the picker still opens there after the app is killed. Without it the user picks their campus instead. --> + + +} + +/** + * A [ConnectivityRepository] that follows Android's default network. + * + * Its callback is never unregistered: create one per process, with the application context, and + * share it, so it lives as long as the app does. + */ +class AndroidConnectivityRepository(context: Context) : ConnectivityRepository { + + private val connectivityManager = + context.applicationContext.getSystemService(ConnectivityManager::class.java) + + private val _isOnline = + MutableStateFlow( + reachesInternet( + connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork) + ) + ) + override val isOnline: StateFlow = _isOnline.asStateFlow() + + init { + connectivityManager.registerDefaultNetworkCallback( + object : ConnectivityManager.NetworkCallback() { + // Also called right after a new default network becomes available. + override fun onCapabilitiesChanged(network: Network, capabilities: NetworkCapabilities) { + _isOnline.value = reachesInternet(capabilities) + } + + override fun onLost(network: Network) { + _isOnline.value = false + } + } + ) + } + + /** Whether [capabilities] reach the internet: validated, so not stuck behind a login page. */ + private fun reachesInternet(capabilities: NetworkCapabilities?): Boolean = + capabilities != null && + capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) && + capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED) +} diff --git a/app/src/sharedTest/java/com/android/polybazaar/connectivity/model/FakeConnectivityRepository.kt b/app/src/sharedTest/java/com/android/polybazaar/connectivity/model/FakeConnectivityRepository.kt new file mode 100644 index 00000000..5cdcef7b --- /dev/null +++ b/app/src/sharedTest/java/com/android/polybazaar/connectivity/model/FakeConnectivityRepository.kt @@ -0,0 +1,9 @@ +// Co-authored-by: Claude Code (Claude Opus 5.5) +package com.android.polybazaar.connectivity.model + +import kotlinx.coroutines.flow.MutableStateFlow + +/** A [ConnectivityRepository] for tests: set [isOnline] to go offline or back online. */ +class FakeConnectivityRepository(online: Boolean = true) : ConnectivityRepository { + override val isOnline = MutableStateFlow(online) +} diff --git a/app/src/test/java/com/android/polybazaar/connectivity/model/AndroidConnectivityRepositoryTest.kt b/app/src/test/java/com/android/polybazaar/connectivity/model/AndroidConnectivityRepositoryTest.kt new file mode 100644 index 00000000..ae2309c0 --- /dev/null +++ b/app/src/test/java/com/android/polybazaar/connectivity/model/AndroidConnectivityRepositoryTest.kt @@ -0,0 +1,63 @@ +// Co-authored-by: Claude Code (Claude Opus 5.5) +package com.android.polybazaar.connectivity.model + +import android.content.Context +import android.net.ConnectivityManager +import android.net.NetworkCapabilities +import androidx.test.core.app.ApplicationProvider +import androidx.test.ext.junit.runners.AndroidJUnit4 +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.Shadows.shadowOf +import org.robolectric.shadows.ShadowNetworkCapabilities + +/** [AndroidConnectivityRepository] on Robolectric's [ConnectivityManager]. */ +@RunWith(AndroidJUnit4::class) +class AndroidConnectivityRepositoryTest { + + private val context: Context = ApplicationProvider.getApplicationContext() + private val connectivityManager = context.getSystemService(ConnectivityManager::class.java) + + private fun capabilities(vararg capabilities: Int): NetworkCapabilities = + ShadowNetworkCapabilities.newInstance().also { network -> + capabilities.forEach { shadowOf(network).addCapability(it) } + } + + private val validated = + capabilities( + NetworkCapabilities.NET_CAPABILITY_INTERNET, + NetworkCapabilities.NET_CAPABILITY_VALIDATED, + ) + + /** Gives the active network [capabilities], then creates the repository. */ + private fun repositoryOn(capabilities: NetworkCapabilities?): AndroidConnectivityRepository { + shadowOf(connectivityManager) + .setNetworkCapabilities(connectivityManager.activeNetwork, capabilities) + return AndroidConnectivityRepository(context) + } + + @Test + fun startsOffline_withoutAValidatedInternetNetwork() { + // Behind a login page, the network has the internet capability but is not validated. + assertFalse( + repositoryOn(capabilities(NetworkCapabilities.NET_CAPABILITY_INTERNET)).isOnline.value + ) + assertFalse(repositoryOn(null).isOnline.value) + } + + @Test + fun followsTheDefaultNetwork() { + val repository = repositoryOn(validated) + val callback = shadowOf(connectivityManager).networkCallbacks.single() + val network = connectivityManager.activeNetwork!! + assertTrue(repository.isOnline.value) + + callback.onLost(network) + assertFalse(repository.isOnline.value) + + callback.onCapabilitiesChanged(network, validated) + assertTrue(repository.isOnline.value) + } +} From c38df59c608fbfeab0507afb8f90b6096fa04057 Mon Sep 17 00:00:00 2001 From: thanna23 <148076306+thanna23@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:47:44 +0100 Subject: [PATCH 13/14] feat(listing): follow whether the device is online in the listing form The form state exposes isOnline, followed live and never saved, so the location picker can be disabled offline. One ConnectivityRepository per process is passed through AppNavHost to both forms. Part of #364. Co-Authored-By: Claude Opus 5.5 --- .../android/polybazaar/PolyBazaarTestCase.kt | 2 + .../com/android/polybazaar/MainActivity.kt | 15 ++ .../listing/viewmodel/ListingFormViewModel.kt | 25 ++- .../polybazaar/ui/navigation/AppNavHost.kt | 5 + .../listing/ui/CreateListingScreenTest.kt | 3 + .../listing/ui/EditListingScreenTest.kt | 3 + .../viewmodel/ListingFormViewModelTest.kt | 205 ++++++++---------- .../ui/navigation/AppNavHostTest.kt | 6 + .../ui/navigation/EndToEndFlowTest.kt | 2 + 9 files changed, 148 insertions(+), 118 deletions(-) diff --git a/app/src/androidTest/java/com/android/polybazaar/PolyBazaarTestCase.kt b/app/src/androidTest/java/com/android/polybazaar/PolyBazaarTestCase.kt index 7fce26d5..67cd56aa 100644 --- a/app/src/androidTest/java/com/android/polybazaar/PolyBazaarTestCase.kt +++ b/app/src/androidTest/java/com/android/polybazaar/PolyBazaarTestCase.kt @@ -9,6 +9,7 @@ import androidx.test.core.app.ApplicationProvider import com.android.polybazaar.auth.viewmodel.AuthViewModel import com.android.polybazaar.booking.model.FakeBookingRepository import com.android.polybazaar.chat.model.FakeChatRepository +import com.android.polybazaar.connectivity.model.FakeConnectivityRepository import com.android.polybazaar.listing.model.FakeListingRepository import com.android.polybazaar.listing.model.FilePhotoStorage import com.android.polybazaar.map.model.FakeLocationRepository @@ -59,6 +60,7 @@ abstract class PolyBazaarTestCase : chatRepository = FakeChatRepository(), locationRepository = FakeLocationRepository(), bookingRepository = FakeBookingRepository(), + connectivityRepository = FakeConnectivityRepository(), navController = rememberNavController(), ) } diff --git a/app/src/main/java/com/android/polybazaar/MainActivity.kt b/app/src/main/java/com/android/polybazaar/MainActivity.kt index 439a2712..92fdda3a 100644 --- a/app/src/main/java/com/android/polybazaar/MainActivity.kt +++ b/app/src/main/java/com/android/polybazaar/MainActivity.kt @@ -19,6 +19,8 @@ import com.android.polybazaar.auth.model.FirebaseAuthRepository import com.android.polybazaar.auth.viewmodel.AuthViewModel import com.android.polybazaar.booking.model.FirebaseBookingRepository import com.android.polybazaar.chat.model.FirebaseChatRepository +import com.android.polybazaar.connectivity.model.AndroidConnectivityRepository +import com.android.polybazaar.connectivity.model.ConnectivityRepository import com.android.polybazaar.listing.model.FilePhotoStorage import com.android.polybazaar.listing.model.FirebaseListingRepository import com.android.polybazaar.map.model.FusedLocationRepository @@ -70,9 +72,22 @@ class MainActivity : ComponentActivity() { LocationServices.getFusedLocationProviderClient(applicationContext) ) }, + connectivityRepository = connectivityRepository(), ) } } } } + + /** The app's [ConnectivityRepository], created on first use. */ + private fun connectivityRepository(): ConnectivityRepository = + connectivity ?: AndroidConnectivityRepository(applicationContext).also { connectivity = it } + + private companion object { + /** + * One for the whole process, never released: the listing forms' ViewModels outlive a rotated + * activity and keep using it, and its network callback is registered only once. + */ + var connectivity: ConnectivityRepository? = null + } } diff --git a/app/src/main/java/com/android/polybazaar/listing/viewmodel/ListingFormViewModel.kt b/app/src/main/java/com/android/polybazaar/listing/viewmodel/ListingFormViewModel.kt index a06c8505..c9dd0f52 100644 --- a/app/src/main/java/com/android/polybazaar/listing/viewmodel/ListingFormViewModel.kt +++ b/app/src/main/java/com/android/polybazaar/listing/viewmodel/ListingFormViewModel.kt @@ -8,6 +8,7 @@ import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.android.polybazaar.auth.model.AuthRules import com.android.polybazaar.booking.model.upcomingDays +import com.android.polybazaar.connectivity.model.ConnectivityRepository import com.android.polybazaar.error.model.AppError import com.android.polybazaar.error.model.toAppError import com.android.polybazaar.listing.model.ItemListing @@ -66,6 +67,8 @@ import kotlinx.coroutines.launch * until a Retry succeeds. * @property savedListing the saved listing, until the screen has handled it. * @property saveError why the last save failed, or null. + * @property isOnline whether the device is online, which choosing a location on the map needs. + * Followed live, never saved with the form. */ data class ListingFormUiState( val today: LocalDate, @@ -90,6 +93,7 @@ data class ListingFormUiState( val savedListing: Listing? = null, val isSaving: Boolean = false, val saveError: AppError? = null, + val isOnline: Boolean = true, ) { /** Whether this form edits a saved listing rather than creating one. */ val isEditing: Boolean @@ -187,6 +191,8 @@ private fun formFor(listing: Listing, today: LocalDate) = * camera app is in front. Pass `createSavedStateHandle()` from the factory: a handle made by hand * is not saved by Android. * @param locationRepository finds the lender, to open the map picker where they are. + * @param connectivityRepository tells whether the device is online, see + * [ListingFormUiState.isOnline]. * @param today the current day, to leave past available days out of an edited listing. */ class ListingFormViewModel( @@ -195,10 +201,16 @@ class ListingFormViewModel( private val photoStorage: PhotoStorage, private val savedStateHandle: SavedStateHandle, private val locationRepository: LocationRepository, + connectivityRepository: ConnectivityRepository, private val today: () -> LocalDate = LocalDate::now, ) : ViewModel() { - private val _uiState = MutableStateFlow(savedStateHandle.restoreForm(listingId, today())) + private val _uiState = + MutableStateFlow( + savedStateHandle + .restoreForm(listingId, today()) + .copy(isOnline = connectivityRepository.isOnline.value) + ) val uiState: StateFlow = _uiState.asStateFlow() /** @@ -236,6 +248,11 @@ class ListingFormViewModel( photoStorage.deleteAllExcept(_uiState.value.photos + listOfNotNull(pendingPhoto)) // A restored edit form holds the user's changes, which loading the listing would overwrite. if (listingId != null && savedStateHandle.get(LOADED) != true) loadListing() + viewModelScope.launch { + connectivityRepository.isOnline.collect { online -> + _uiState.update { it.copy(isOnline = online) } + } + } } /** @@ -253,7 +270,9 @@ class ListingFormViewModel( .getListing(id) .onSuccess { listing -> savedStateHandle[LOADED] = true - updateState { formFor(listing, today()).copy(isLoading = true) } + updateState { + formFor(listing, today()).copy(isLoading = true, isOnline = it.isOnline) + } } .onFailure { exception -> // Cancellation means the screen was closed: it is not an error to show. @@ -447,7 +466,7 @@ class ListingFormViewModel( val form = if (state.isEditing) formFor(savedListing, today()) else ListingFormUiState(today = today()) - form.copy(savedListing = savedListing) + form.copy(savedListing = savedListing, isOnline = it.isOnline) } } catch (exception: Exception) { if (exception is CancellationException) { diff --git a/app/src/main/java/com/android/polybazaar/ui/navigation/AppNavHost.kt b/app/src/main/java/com/android/polybazaar/ui/navigation/AppNavHost.kt index 07f83b09..82dedea7 100644 --- a/app/src/main/java/com/android/polybazaar/ui/navigation/AppNavHost.kt +++ b/app/src/main/java/com/android/polybazaar/ui/navigation/AppNavHost.kt @@ -72,6 +72,7 @@ import com.android.polybazaar.chat.ui.InboxScreen import com.android.polybazaar.chat.viewmodel.ConversationViewModel import com.android.polybazaar.chat.viewmodel.InboxViewModel import com.android.polybazaar.chat.viewmodel.photoUploadScope +import com.android.polybazaar.connectivity.model.ConnectivityRepository import com.android.polybazaar.error.model.AppError import com.android.polybazaar.error.ui.message import com.android.polybazaar.listing.model.FilePhotoStorage @@ -121,6 +122,7 @@ object AppNavHostTags { * @param editPhotoStorage keeps the photos added to the listing being edited. It must use another * folder than [photoStorage]: opening a form deletes the photos its folder holds for other forms. * @param locationRepository finds the lender, to open the listing form's map picker where they are. + * @param connectivityRepository tells the listing forms whether the device is online. */ @Composable fun AppNavHost( @@ -133,6 +135,7 @@ fun AppNavHost( chatRepository: ChatRepository, locationRepository: LocationRepository, bookingRepository: BookingRepository, + connectivityRepository: ConnectivityRepository, navController: NavHostController = rememberNavController(), ) { val uiState by authViewModel.uiState.collectAsState() @@ -304,6 +307,7 @@ fun AppNavHost( photoStorage = photoStorage, savedStateHandle = createSavedStateHandle(), locationRepository = locationRepository, + connectivityRepository = connectivityRepository, ) } } @@ -331,6 +335,7 @@ fun AppNavHost( photoStorage = editPhotoStorage, savedStateHandle = createSavedStateHandle(), locationRepository = locationRepository, + connectivityRepository = connectivityRepository, ) } } diff --git a/app/src/test/java/com/android/polybazaar/listing/ui/CreateListingScreenTest.kt b/app/src/test/java/com/android/polybazaar/listing/ui/CreateListingScreenTest.kt index 1943ad24..aa88c48e 100644 --- a/app/src/test/java/com/android/polybazaar/listing/ui/CreateListingScreenTest.kt +++ b/app/src/test/java/com/android/polybazaar/listing/ui/CreateListingScreenTest.kt @@ -45,6 +45,7 @@ import androidx.test.ext.junit.runners.AndroidJUnit4 import com.android.polybazaar.R import com.android.polybazaar.booking.ui.AvailabilityCalendarSheetTags import com.android.polybazaar.booking.ui.AvailabilityCalendarTags +import com.android.polybazaar.connectivity.model.FakeConnectivityRepository import com.android.polybazaar.listing.model.FilePhotoStorage import com.android.polybazaar.listing.model.ItemListing import com.android.polybazaar.listing.model.Listing @@ -99,6 +100,7 @@ class CreateListingScreenTest { createStorage(), SavedStateHandle(), FakeLocationRepository(), + FakeConnectivityRepository(), today, ) setContentWithRegistry(registry) { @@ -887,6 +889,7 @@ class CreateListingScreenTest { createStorage(), SavedStateHandle(), FakeLocationRepository(), + FakeConnectivityRepository(), ) var createdCount = 0 val owner = diff --git a/app/src/test/java/com/android/polybazaar/listing/ui/EditListingScreenTest.kt b/app/src/test/java/com/android/polybazaar/listing/ui/EditListingScreenTest.kt index 69638d6c..464500b8 100644 --- a/app/src/test/java/com/android/polybazaar/listing/ui/EditListingScreenTest.kt +++ b/app/src/test/java/com/android/polybazaar/listing/ui/EditListingScreenTest.kt @@ -27,6 +27,7 @@ import androidx.test.ext.junit.runners.AndroidJUnit4 import com.android.polybazaar.R import com.android.polybazaar.booking.model.formatRuns import com.android.polybazaar.booking.model.groupIntoRuns +import com.android.polybazaar.connectivity.model.FakeConnectivityRepository import com.android.polybazaar.listing.model.FakeListingRepository import com.android.polybazaar.listing.model.FilePhotoStorage import com.android.polybazaar.listing.model.ItemListing @@ -99,6 +100,7 @@ class EditListingScreenTest { FilePhotoStorage(context, FilePhotoStorage.EDIT_FORM), SavedStateHandle(), FakeLocationRepository(), + FakeConnectivityRepository(), ) composeTestRule.setContent { EditListingScreen( @@ -343,6 +345,7 @@ class EditListingScreenTest { FilePhotoStorage(context, FilePhotoStorage.EDIT_FORM), SavedStateHandle(), FakeLocationRepository(), + FakeConnectivityRepository(), ) composeTestRule.setContent { dispatcher = LocalOnBackPressedDispatcherOwner.current!!.onBackPressedDispatcher diff --git a/app/src/test/java/com/android/polybazaar/listing/viewmodel/ListingFormViewModelTest.kt b/app/src/test/java/com/android/polybazaar/listing/viewmodel/ListingFormViewModelTest.kt index b107e0aa..ebe8460d 100644 --- a/app/src/test/java/com/android/polybazaar/listing/viewmodel/ListingFormViewModelTest.kt +++ b/app/src/test/java/com/android/polybazaar/listing/viewmodel/ListingFormViewModelTest.kt @@ -7,6 +7,7 @@ import android.os.Parcel import androidx.core.os.bundleOf import androidx.lifecycle.SavedStateHandle import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.android.polybazaar.connectivity.model.FakeConnectivityRepository import com.android.polybazaar.error.model.AppError import com.android.polybazaar.listing.model.ItemListing import com.android.polybazaar.listing.model.Listing @@ -57,6 +58,7 @@ class ListingFormViewModelTest { private lateinit var photoStorage: FakePhotoStorage private lateinit var savedStateHandle: SavedStateHandle private val locationRepository = FakeLocationRepository() + private val connectivity = FakeConnectivityRepository() private lateinit var viewModel: ListingFormViewModel private val listing = @@ -73,11 +75,24 @@ class ListingFormViewModelTest { repository = FakeListingRepository() photoStorage = FakePhotoStorage() savedStateHandle = SavedStateHandle() - viewModel = - ListingFormViewModel(null, repository, photoStorage, savedStateHandle, locationRepository) { - today - } - } + viewModel = newForm(null) { today } + } + + /** A form on this test's fakes, editing [listingId] or creating a listing when it is null. */ + private fun newForm( + listingId: String?, + handle: SavedStateHandle = savedStateHandle, + today: () -> LocalDate = LocalDate::now, + ) = + ListingFormViewModel( + listingId, + repository, + photoStorage, + handle, + locationRepository, + connectivity, + today, + ) @After fun tearDown() { @@ -293,14 +308,7 @@ class ListingFormViewModelTest { viewModel.addPhotos(uris(1)) viewModel.startTakingPhoto(retakeIndex = null) - val restored = - ListingFormViewModel( - null, - repository, - photoStorage, - afterAppKilled(savedStateHandle), - locationRepository, - ) + val restored = newForm(null, afterAppKilled(savedStateHandle)) restored.finishTakingPhoto(saved = true) assertEquals( @@ -316,7 +324,7 @@ class ListingFormViewModelTest { viewModel.addPhotos(uris(1)) viewModel.startTakingPhoto(retakeIndex = null) - ListingFormViewModel(null, repository, photoStorage, savedStateHandle, locationRepository) + newForm(null) assertEquals(uris(1) + photoStorage.taken[0].uri, photoStorage.keptOnCleanup.last()) } @@ -498,14 +506,7 @@ class ListingFormViewModelTest { testDispatcher.scheduler.advanceUntilIdle() assertEquals(AppError.NETWORK, viewModel.uiState.value.saveError) - val restored = - ListingFormViewModel( - null, - repository, - photoStorage, - afterAppKilled(savedStateHandle), - locationRepository, - ) + val restored = newForm(null, afterAppKilled(savedStateHandle)) // The form comes back, the error of a save that no longer runs does not. assertEquals("Math tutoring", restored.uiState.value.title) @@ -641,8 +642,7 @@ class ListingFormViewModelTest { repository.storedListing = storedItem // The same fixed day as the other forms: with the real date, available days chosen in these // tests end up in the past and are dropped. - val editViewModel = - ListingFormViewModel("l1", repository, photoStorage, handle, locationRepository) { today } + val editViewModel = newForm("l1", handle) { today } testDispatcher.scheduler.advanceUntilIdle() return editViewModel } @@ -661,8 +661,7 @@ class ListingFormViewModelTest { fun edit_showsLoadingUntilTheListingArrives() = runTest { repository.storedListing = storedItem repository.pendingLoad = CompletableDeferred() - val editViewModel = - ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) + val editViewModel = newForm("l1") testDispatcher.scheduler.runCurrent() assertTrue(editViewModel.uiState.value.isLoading) @@ -680,8 +679,7 @@ class ListingFormViewModelTest { fun edit_formCannotBeChangedWhileLoading() = runTest { repository.storedListing = storedItem repository.pendingLoad = CompletableDeferred() - val editViewModel = - ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) + val editViewModel = newForm("l1") testDispatcher.scheduler.runCurrent() assertFalse(editViewModel.uiState.value.canEdit) @@ -708,8 +706,7 @@ class ListingFormViewModelTest { fun edit_formCannotBeChangedAfterALoadFailure() = runTest { repository.storedListing = storedItem repository.loadFailure = UnknownHostException("offline") - val editViewModel = - ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) + val editViewModel = newForm("l1") testDispatcher.scheduler.advanceUntilIdle() assertFalse(editViewModel.uiState.value.canEdit) @@ -733,8 +730,7 @@ class ListingFormViewModelTest { savedStateHandle["pendingPhoto"] = photo repository.storedListing = storedItem repository.pendingLoad = CompletableDeferred() - val editViewModel = - ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) + val editViewModel = newForm("l1") testDispatcher.scheduler.runCurrent() editViewModel.finishTakingPhoto(saved = true) @@ -763,8 +759,7 @@ class ListingFormViewModelTest { repository.storedListing = storedItem repository.loadFailure = FirebaseFirestoreException("missing", FirebaseFirestoreException.Code.NOT_FOUND) - val editViewModel = - ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) + val editViewModel = newForm("l1") testDispatcher.scheduler.advanceUntilIdle() assertEquals(AppError.NOT_FOUND, editViewModel.uiState.value.loadError) @@ -901,8 +896,7 @@ class ListingFormViewModelTest { fun edit_loadFailureSetsLoadErrorNotSaveError() = runTest { repository.storedListing = storedItem repository.loadFailure = UnknownHostException("offline") - val editViewModel = - ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) + val editViewModel = newForm("l1") testDispatcher.scheduler.advanceUntilIdle() assertEquals(AppError.NETWORK, editViewModel.uiState.value.loadError) @@ -914,8 +908,7 @@ class ListingFormViewModelTest { fun edit_listingAboveThePhotoLimitAcceptsNoNewPhotos() = runTest { val paths = (0..MAX_PHOTOS).map { "listings/u/l1/old/$it" } repository.storedListing = storedItem.copy(imagePaths = paths) - val editViewModel = - ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) + val editViewModel = newForm("l1") testDispatcher.scheduler.advanceUntilIdle() editViewModel.addPhotos(uris(1)) @@ -930,8 +923,7 @@ class ListingFormViewModelTest { fun edit_cancelledLoadShowsNoErrorAndCanBeRetried() = runTest { repository.storedListing = storedItem repository.loadFailure = CancellationException() - val editViewModel = - ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) + val editViewModel = newForm("l1") testDispatcher.scheduler.advanceUntilIdle() // Cancellation means the screen closed, so it is not an error, and the load is not stuck. @@ -949,8 +941,7 @@ class ListingFormViewModelTest { fun edit_loadIsIgnoredWhileOneIsRunning() = runTest { repository.storedListing = storedItem repository.pendingLoad = CompletableDeferred() - val editViewModel = - ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) + val editViewModel = newForm("l1") testDispatcher.scheduler.runCurrent() editViewModel.loadListing() @@ -965,8 +956,7 @@ class ListingFormViewModelTest { fun edit_serviceListingLoadsWithoutARefundValue() = runTest { val service = listing.copy(imagePaths = storedPaths, listingId = "l1", ownerUid = "owner") repository.storedListing = service - val editViewModel = - ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) + val editViewModel = newForm("l1") testDispatcher.scheduler.advanceUntilIdle() assertEquals("", editViewModel.uiState.value.refundValue) @@ -1134,16 +1124,7 @@ class ListingFormViewModelTest { fun availableDates_surviveTheAppBeingKilled() = runTest { viewModel.updateAvailableDates(chosenDays) - val restored = - ListingFormViewModel( - null, - repository, - photoStorage, - afterAppKilled(savedStateHandle), - locationRepository, - ) { - today - } + val restored = newForm(null, afterAppKilled(savedStateHandle)) { today } assertEquals(chosenDays, restored.uiState.value.availableDates) } @@ -1151,16 +1132,7 @@ class ListingFormViewModelTest { @Test fun save_afterTheDayChanged_leavesOutTheDaysNowPast() = runTest { var now = today - val form = - ListingFormViewModel( - null, - repository, - photoStorage, - SavedStateHandle(), - locationRepository, - ) { - now - } + val form = newForm(null, SavedStateHandle()) { now } viewModel = form fillForm() form.updateAvailableDates(chosenDays) @@ -1177,16 +1149,7 @@ class ListingFormViewModelTest { viewModel.updateAvailableDates(chosenDays) val laterDay = LocalDate.of(2026, 11, 20) - val restored = - ListingFormViewModel( - null, - repository, - photoStorage, - afterAppKilled(savedStateHandle), - locationRepository, - ) { - laterDay - } + val restored = newForm(null, afterAppKilled(savedStateHandle)) { laterDay } assertEquals(setOf(LocalDate.of(2026, 11, 28)), restored.uiState.value.availableDates) assertEquals(laterDay, restored.uiState.value.today) @@ -1196,10 +1159,7 @@ class ListingFormViewModelTest { fun edit_showsTheStoredAvailableDays_withoutThePastOnes() = runTest { repository.storedListing = storedItem.copy(availableDates = chosenDays + LocalDate.of(2026, 11, 9) + today) - val editViewModel = - ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) { - today - } + val editViewModel = newForm("l1") { today } testDispatcher.scheduler.advanceUntilIdle() assertEquals(chosenDays + today, editViewModel.uiState.value.availableDates) @@ -1233,10 +1193,7 @@ class ListingFormViewModelTest { @Test fun edit_loadsTheStoredLocationIntoTheForm() = runTest { repository.storedListing = storedItem.copy(location = storedLocation) - val editViewModel = - ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) { - today - } + val editViewModel = newForm("l1") { today } testDispatcher.scheduler.advanceUntilIdle() assertEquals(storedLocation, editViewModel.uiState.value.location) @@ -1247,10 +1204,7 @@ class ListingFormViewModelTest { @Test fun edit_saveKeepsTheStoredLocation() = runTest { repository.storedListing = storedItem.copy(location = storedLocation) - val editViewModel = - ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) { - today - } + val editViewModel = newForm("l1") { today } testDispatcher.scheduler.advanceUntilIdle() repository.result = storedItem.copy(price = 15.0, location = storedLocation) @@ -1275,9 +1229,7 @@ class ListingFormViewModelTest { @Test fun location_survivesTheAppBeingKilled() = runTest { repository.storedListing = storedItem.copy(location = storedLocation) - ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) { - today - } + newForm("l1") { today } testDispatcher.scheduler.advanceUntilIdle() assertEquals(storedLocation.latitude, savedStateHandle.get("locationLatitude")) @@ -1309,8 +1261,7 @@ class ListingFormViewModelTest { ) handles.forEach { handle -> - val restored = - ListingFormViewModel(null, repository, photoStorage, handle, locationRepository) { today } + val restored = newForm(null, handle) { today } assertNull(restored.uiState.value.location) } } @@ -1452,8 +1403,7 @@ class ListingFormViewModelTest { locationRepository.result = Result.success(lausanne) repository.storedListing = storedItem.copy(location = storedLocation) repository.pendingLoad = CompletableDeferred() - val editViewModel = - ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) + val editViewModel = newForm("l1") testDispatcher.scheduler.runCurrent() editViewModel.locateLender() @@ -1522,8 +1472,7 @@ class ListingFormViewModelTest { fun locationChanges_areIgnoredWhileTheEditedListingLoads() = runTest { repository.storedListing = storedItem.copy(location = storedLocation) repository.pendingLoad = CompletableDeferred() - val editViewModel = - ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) + val editViewModel = newForm("l1") testDispatcher.scheduler.runCurrent() editViewModel.setLocationPoint(lausanne) @@ -1540,8 +1489,7 @@ class ListingFormViewModelTest { @Test fun edit_opensThePickerOnTheStoredLocation_orEpflWithoutOne() = runTest { repository.storedListing = storedItem.copy(location = ListingLocation(46.5, 6.6, "Flat")) - val withLocation = - ListingFormViewModel("l1", repository, photoStorage, SavedStateHandle(), locationRepository) + val withLocation = newForm("l1", SavedStateHandle()) testDispatcher.scheduler.advanceUntilIdle() assertEquals(Coordinates(46.5, 6.6), withLocation.uiState.value.suggestedPoint) @@ -1551,10 +1499,7 @@ class ListingFormViewModelTest { @Test fun edit_savesTheChangedLocation() = runTest { repository.storedListing = storedItem.copy(location = storedLocation) - val editViewModel = - ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) { - today - } + val editViewModel = newForm("l1") { today } testDispatcher.scheduler.advanceUntilIdle() repository.result = storedItem @@ -1567,18 +1512,7 @@ class ListingFormViewModelTest { @Test fun suggestedPointAndUnnamedLocation_surviveTheAppBeingKilled() = runTest { - fun restored() = - ListingFormViewModel( - null, - repository, - photoStorage, - afterAppKilled(savedStateHandle), - locationRepository, - ) { - today - } - .uiState - .value + fun restored() = newForm(null, afterAppKilled(savedStateHandle)) { today }.uiState.value locationRepository.result = Result.success(lausanne) viewModel.locateLender() testDispatcher.scheduler.advanceUntilIdle() @@ -1599,9 +1533,50 @@ class ListingFormViewModelTest { fun suggestedPoint_partlySavedIsRestoredAsEpfl() { listOf("suggestedLatitude", "suggestedLongitude").forEach { key -> val handle = SavedStateHandle(mapOf(key to 46.5)) - val restored = - ListingFormViewModel(null, repository, photoStorage, handle, locationRepository) { today } + val restored = newForm(null, handle) { today } assertEquals(epfl, restored.uiState.value.suggestedPoint) } } + + @Test + fun isOnline_followsTheConnectivityRepository() = runTest { + connectivity.isOnline.value = false + val form = newForm(null, SavedStateHandle()) + assertFalse(form.uiState.value.isOnline) + + connectivity.isOnline.value = true + testDispatcher.scheduler.advanceUntilIdle() + assertTrue(form.uiState.value.isOnline) + } + + @Test + fun isOnline_isKeptWhenTheEditedListingLoads() = runTest { + repository.storedListing = storedItem + repository.pendingLoad = CompletableDeferred() + val form = newForm("l1") + testDispatcher.scheduler.advanceUntilIdle() + connectivity.isOnline.value = false + testDispatcher.scheduler.advanceUntilIdle() + + repository.pendingLoad!!.complete(Unit) + testDispatcher.scheduler.advanceUntilIdle() + + assertEquals(storedItem.title, form.uiState.value.title) + assertFalse(form.uiState.value.isOnline) + } + + @Test + fun isOnline_isKeptWhenTheFormResetsAfterSaving() = runTest { + repository.result = listing + testDispatcher.scheduler.advanceUntilIdle() + connectivity.isOnline.value = false + testDispatcher.scheduler.advanceUntilIdle() + fillForm() + + viewModel.save() + testDispatcher.scheduler.advanceUntilIdle() + + assertEquals(listing, viewModel.uiState.value.savedListing) + assertFalse(viewModel.uiState.value.isOnline) + } } diff --git a/app/src/test/java/com/android/polybazaar/ui/navigation/AppNavHostTest.kt b/app/src/test/java/com/android/polybazaar/ui/navigation/AppNavHostTest.kt index b0604285..0db8d87e 100644 --- a/app/src/test/java/com/android/polybazaar/ui/navigation/AppNavHostTest.kt +++ b/app/src/test/java/com/android/polybazaar/ui/navigation/AppNavHostTest.kt @@ -73,6 +73,7 @@ import com.android.polybazaar.chat.model.Conversation import com.android.polybazaar.chat.model.FakeChatRepository import com.android.polybazaar.chat.ui.ConversationScreenTags import com.android.polybazaar.chat.ui.InboxScreenTags +import com.android.polybazaar.connectivity.model.FakeConnectivityRepository import com.android.polybazaar.error.model.AppError import com.android.polybazaar.error.model.AppException import com.android.polybazaar.listing.model.FakeListingRepository @@ -166,6 +167,7 @@ class AppNavHostTest { chatRepository = chatRepository, locationRepository = FakeLocationRepository(), bookingRepository = bookingRepository, + connectivityRepository = FakeConnectivityRepository(), navController = navController, ) } @@ -209,6 +211,7 @@ class AppNavHostTest { chatRepository = chatRepository, locationRepository = FakeLocationRepository(), bookingRepository = bookingRepository, + connectivityRepository = FakeConnectivityRepository(), navController = navController, ) } @@ -679,6 +682,7 @@ class AppNavHostTest { chatRepository = chatRepository, locationRepository = FakeLocationRepository(), bookingRepository = bookingRepository, + connectivityRepository = FakeConnectivityRepository(), navController = navController, ) } @@ -1511,6 +1515,7 @@ class AppNavHostTest { chatRepository = chatRepository, locationRepository = FakeLocationRepository(), bookingRepository = bookingRepository, + connectivityRepository = FakeConnectivityRepository(), navController = navController, ) } @@ -1588,6 +1593,7 @@ class AppNavHostTest { chatRepository = chatRepository, locationRepository = FakeLocationRepository(), bookingRepository = bookingRepository, + connectivityRepository = FakeConnectivityRepository(), navController = navController, ) } diff --git a/app/src/test/java/com/android/polybazaar/ui/navigation/EndToEndFlowTest.kt b/app/src/test/java/com/android/polybazaar/ui/navigation/EndToEndFlowTest.kt index 49ee02c6..3656eace 100644 --- a/app/src/test/java/com/android/polybazaar/ui/navigation/EndToEndFlowTest.kt +++ b/app/src/test/java/com/android/polybazaar/ui/navigation/EndToEndFlowTest.kt @@ -31,6 +31,7 @@ import com.android.polybazaar.auth.viewmodel.AuthViewModel import com.android.polybazaar.booking.model.FakeBookingRepository import com.android.polybazaar.browse.ui.BrowseScreenTags import com.android.polybazaar.chat.model.FakeChatRepository +import com.android.polybazaar.connectivity.model.FakeConnectivityRepository import com.android.polybazaar.listing.model.FakeListingRepository import com.android.polybazaar.listing.model.FilePhotoStorage import com.android.polybazaar.listing.model.ItemListing @@ -88,6 +89,7 @@ class EndToEndFlowTest { chatRepository = FakeChatRepository(), locationRepository = FakeLocationRepository(), bookingRepository = FakeBookingRepository(), + connectivityRepository = FakeConnectivityRepository(), navController = navController, ) } From d982d950733b56c50e4272f92175efd0c2731c89 Mon Sep 17 00:00:00 2001 From: thanna23 <148076306+thanna23@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:29:07 +0100 Subject: [PATCH 14/14] fix(connectivity): stay online when a previous default network is lost During a Wi-Fi/mobile handoff, the old network's onLost can arrive after the new one became the default. The repository now remembers the current default network and only reports offline when that one is lost. Co-Authored-By: Claude Opus 5.5 --- .../model/ConnectivityRepository.kt | 8 ++++++++ .../model/AndroidConnectivityRepositoryTest.kt | 17 +++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/app/src/main/java/com/android/polybazaar/connectivity/model/ConnectivityRepository.kt b/app/src/main/java/com/android/polybazaar/connectivity/model/ConnectivityRepository.kt index d0e56ef0..331ea197 100644 --- a/app/src/main/java/com/android/polybazaar/connectivity/model/ConnectivityRepository.kt +++ b/app/src/main/java/com/android/polybazaar/connectivity/model/ConnectivityRepository.kt @@ -34,15 +34,23 @@ class AndroidConnectivityRepository(context: Context) : ConnectivityRepository { ) override val isOnline: StateFlow = _isOnline.asStateFlow() + /** The default network the callback last reported, or null once it is lost. */ + @Volatile private var defaultNetwork: Network? = connectivityManager.activeNetwork + init { connectivityManager.registerDefaultNetworkCallback( object : ConnectivityManager.NetworkCallback() { // Also called right after a new default network becomes available. override fun onCapabilitiesChanged(network: Network, capabilities: NetworkCapabilities) { + defaultNetwork = network _isOnline.value = reachesInternet(capabilities) } + // During a Wi-Fi/mobile handoff the old network can be lost after the new one became + // the default: only losing the current default means the device is offline. override fun onLost(network: Network) { + if (network != defaultNetwork) return + defaultNetwork = null _isOnline.value = false } } diff --git a/app/src/test/java/com/android/polybazaar/connectivity/model/AndroidConnectivityRepositoryTest.kt b/app/src/test/java/com/android/polybazaar/connectivity/model/AndroidConnectivityRepositoryTest.kt index ae2309c0..d8529454 100644 --- a/app/src/test/java/com/android/polybazaar/connectivity/model/AndroidConnectivityRepositoryTest.kt +++ b/app/src/test/java/com/android/polybazaar/connectivity/model/AndroidConnectivityRepositoryTest.kt @@ -11,6 +11,7 @@ import org.junit.Assert.assertTrue import org.junit.Test import org.junit.runner.RunWith import org.robolectric.Shadows.shadowOf +import org.robolectric.shadows.ShadowNetwork import org.robolectric.shadows.ShadowNetworkCapabilities /** [AndroidConnectivityRepository] on Robolectric's [ConnectivityManager]. */ @@ -60,4 +61,20 @@ class AndroidConnectivityRepositoryTest { callback.onCapabilitiesChanged(network, validated) assertTrue(repository.isOnline.value) } + + @Test + fun staysOnline_whenThePreviousNetworkIsLostAfterAHandoff() { + val repository = repositoryOn(validated) + val callback = shadowOf(connectivityManager).networkCallbacks.single() + val wifi = connectivityManager.activeNetwork!! + val mobile = ShadowNetwork.newInstance(shadowOf(wifi).netId + 1) + + // Mobile becomes the default, validated, before Wi-Fi's loss arrives. + callback.onCapabilitiesChanged(mobile, validated) + callback.onLost(wifi) + assertTrue(repository.isOnline.value) + + callback.onLost(mobile) + assertFalse(repository.isOnline.value) + } }