diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 2c478d9..faaff55 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -1,6 +1,14 @@ +import java.util.Properties + plugins { alias(libs.plugins.android.application) alias(libs.plugins.kotlin.compose) + alias(libs.plugins.hilt) + alias(libs.plugins.ksp) +} + +val localProperties = Properties().apply { + rootProject.file("local.properties").takeIf { it.exists() }?.inputStream()?.use(::load) } android { @@ -22,7 +30,14 @@ android { } buildTypes { + debug { + // 10.0.2.2 is the host machine's localhost from the emulator, where the mock server runs. + // Set roomie.apiUrl in local.properties to point somewhere else. + val apiUrl = localProperties.getProperty("roomie.apiUrl") ?: "http://10.0.2.2:8000/" + buildConfigField("String", "API_URL", "\"$apiUrl\"") + } release { + buildConfigField("String", "API_URL", "\"https://roomie-dev.142-93-246-176.sslip.io/\"") optimization { enable = false } @@ -35,6 +50,7 @@ android { } buildFeatures { compose = true + buildConfig = true } } @@ -50,8 +66,16 @@ dependencies { implementation(libs.androidx.lifecycle.runtime.compose) implementation(libs.androidx.lifecycle.viewmodel.compose) implementation(libs.androidx.navigation.compose) + implementation(libs.hilt.android) + implementation(libs.androidx.hilt.lifecycle.viewmodel.compose) + ksp(libs.hilt.android.compiler) + implementation(libs.retrofit) + implementation(libs.retrofit.converter.gson) + implementation(libs.okhttp) + implementation(libs.okhttp.logging.interceptor) coreLibraryDesugaring(libs.desugar.jdk.libs) testImplementation(libs.junit) + testImplementation(libs.okhttp.mockwebserver) androidTestImplementation(platform(libs.androidx.compose.bom)) androidTestImplementation(libs.androidx.compose.ui.test.junit4) androidTestImplementation(libs.androidx.espresso.core) diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 24b3f84..64bb973 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -2,10 +2,14 @@ + + >(RoomieApiResponse.Pending) + + /** You, your house, and invites you've received. */ + val me: StateFlow> = _me.asStateFlow() + + /** Signs in to the local backend or mock server as [netId], with no Firebase involved. */ + suspend fun devLogin(netId: String): RoomieApiResponse { + devTokenProvider.netId = netId.trim().lowercase() + return login() + } + + /** Call right after sign-in, once the [com.example.roomie.data.api.TokenProvider] has a token. */ + suspend fun login(): RoomieApiResponse = apiCall { retrofitInstance.userApi.login() } + + /** Pipelines the response into [me]. */ + fun fetchMe(refresh: Boolean = false) { + scope.fetchInto(_me, refresh) { retrofitInstance.userApi.getMe() } + } + + suspend fun updateMe(name: String? = null, major: String? = null): RoomieApiResponse = + apiCall { retrofitInstance.userApi.updateMe(UpdateMeBody(name, major)) }.also { result -> + result.ifSuccess { _me.value = RoomieApiResponse.Success(it) } + } + + fun signOut() { + devTokenProvider.netId = null + _me.value = RoomieApiResponse.Pending + } +} diff --git a/app/src/main/java/com/example/roomie/data/ChoreRepository.kt b/app/src/main/java/com/example/roomie/data/ChoreRepository.kt new file mode 100644 index 0000000..99ca701 --- /dev/null +++ b/app/src/main/java/com/example/roomie/data/ChoreRepository.kt @@ -0,0 +1,110 @@ +package com.example.roomie.data + +import com.example.roomie.data.api.ChoreDto +import com.example.roomie.data.api.ChoreStatsResponse +import com.example.roomie.data.api.CreateChoreBody +import com.example.roomie.data.api.RetrofitInstance +import com.example.roomie.data.api.RoomieApiResponse +import com.example.roomie.data.api.SwapBody +import com.example.roomie.data.api.TurnDto +import com.example.roomie.data.api.UpdateChoreBody +import com.example.roomie.data.api.apiCall +import com.example.roomie.data.api.fetchInto +import com.example.roomie.data.api.repositoryScope +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import java.time.LocalDate +import java.time.YearMonth +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class ChoreRepository @Inject constructor(private val retrofitInstance: RetrofitInstance) { + + private val scope = repositoryScope() + private val api get() = retrofitInstance.choreApi + + private val _chores = MutableStateFlow>>(RoomieApiResponse.Pending) + + /** Every chore in the house. */ + val chores: StateFlow>> = _chores.asStateFlow() + + private val _myTurnsToday = MutableStateFlow>>(RoomieApiResponse.Pending) + + /** Your turns due today, plus any you've left overdue. What Home shows. */ + val myTurnsToday: StateFlow>> = _myTurnsToday.asStateFlow() + + private val _turns = MutableStateFlow>>(RoomieApiResponse.Pending) + + /** Everyone's turns over the range last passed to [fetchTurns], plus overdue ones. */ + val turns: StateFlow>> = _turns.asStateFlow() + + private val _stats = MutableStateFlow>(RoomieApiResponse.Pending) + + /** How many turns each member finished in the month last passed to [fetchStats]. */ + val stats: StateFlow> = _stats.asStateFlow() + + /** Pipelines the response into [chores]. */ + fun fetchChores(houseId: Int, refresh: Boolean = false) { + scope.fetchInto(_chores, refresh) { api.getChores(houseId).chores } + } + + /** Pipelines the response into [myTurnsToday]. */ + fun fetchMyTurnsToday(houseId: Int, today: LocalDate, refresh: Boolean = false) { + scope.fetchInto(_myTurnsToday, refresh) { + api.getAssignments(houseId, today, today, assignee = "me", includeOverdue = true).assignments + } + } + + /** Pipelines [from] to [to] (at most 62 days) into [turns]. */ + fun fetchTurns(houseId: Int, from: LocalDate, to: LocalDate, refresh: Boolean = false) { + scope.fetchInto(_turns, refresh) { + api.getAssignments(houseId, from, to, includeOverdue = true).assignments + } + } + + /** Pipelines the response into [stats]. Leave [month] null for this month. */ + fun fetchStats(houseId: Int, month: YearMonth? = null, refresh: Boolean = false) { + scope.fetchInto(_stats, refresh) { api.getChoreStats(houseId, month) } + } + + suspend fun getChore(houseId: Int, choreId: Int): RoomieApiResponse = + apiCall { api.getChore(houseId, choreId).chore } + + suspend fun createChore(houseId: Int, body: CreateChoreBody): RoomieApiResponse = + changingChores(houseId) { api.createChore(houseId, body).chore } + + suspend fun updateChore(houseId: Int, choreId: Int, body: UpdateChoreBody): RoomieApiResponse = + changingChores(houseId) { api.updateChore(houseId, choreId, body).chore } + + suspend fun deleteChore(houseId: Int, choreId: Int): RoomieApiResponse = + changingChores(houseId) { api.deleteChore(houseId, choreId) } + + suspend fun completeTurn(houseId: Int, turnId: Int): RoomieApiResponse = + apiCall { api.completeAssignment(houseId, turnId).assignment }.also { it.ifSuccess { turn -> replaceTurns(listOf(turn)) } } + + suspend fun uncompleteTurn(houseId: Int, turnId: Int): RoomieApiResponse = + apiCall { api.uncompleteAssignment(houseId, turnId).assignment }.also { it.ifSuccess { turn -> replaceTurns(listOf(turn)) } } + + /** Swapping can move a turn on or off your list, so [myTurnsToday] is refetched. */ + suspend fun swapTurns(houseId: Int, turnId: Int, withTurnId: Int, today: LocalDate): RoomieApiResponse> = + apiCall { api.swapAssignment(houseId, turnId, SwapBody(withTurnId)).assignments }.also { + it.ifSuccess { turns -> + replaceTurns(turns) + fetchMyTurnsToday(houseId, today, refresh = true) + } + } + + /** A chore change can rewrite its upcoming turns, so refetch the chores. Turn lists refresh on their next fetch. */ + private suspend fun changingChores(houseId: Int, call: suspend () -> T): RoomieApiResponse = + apiCall(call).also { it.ifSuccess { fetchChores(houseId, refresh = true) } } + + /** Swaps the changed turns into the cached lists that already have them. */ + private fun replaceTurns(changed: List) { + val byId = changed.associateBy { it.id } + for (flow in listOf(_turns, _myTurnsToday)) { + flow.value = flow.value.map { turns -> turns.map { byId[it.id] ?: it } } + } + } +} diff --git a/app/src/main/java/com/example/roomie/data/FakeDataModule.kt b/app/src/main/java/com/example/roomie/data/FakeDataModule.kt new file mode 100644 index 0000000..c43ec48 --- /dev/null +++ b/app/src/main/java/com/example/roomie/data/FakeDataModule.kt @@ -0,0 +1,15 @@ +package com.example.roomie.data + +import dagger.Module +import dagger.Provides +import dagger.hilt.InstallIn +import dagger.hilt.components.SingletonComponent + +/** Lets ViewModels inject the in-memory data until each screen moves to its real repository. */ +@Module +@InstallIn(SingletonComponent::class) +object FakeDataModule { + + @Provides + fun provideFakeRoomieRepository(): FakeRoomieRepository = FakeRoomieRepository +} diff --git a/app/src/main/java/com/example/roomie/data/HouseRepository.kt b/app/src/main/java/com/example/roomie/data/HouseRepository.kt new file mode 100644 index 0000000..300c46c --- /dev/null +++ b/app/src/main/java/com/example/roomie/data/HouseRepository.kt @@ -0,0 +1,67 @@ +package com.example.roomie.data + +import com.example.roomie.data.api.CreateHouseBody +import com.example.roomie.data.api.HouseDto +import com.example.roomie.data.api.InviteBody +import com.example.roomie.data.api.JoinHouseBody +import com.example.roomie.data.api.RetrofitInstance +import com.example.roomie.data.api.RoomieApiResponse +import com.example.roomie.data.api.UpdateHouseBody +import com.example.roomie.data.api.apiCall +import com.example.roomie.data.api.fetchInto +import com.example.roomie.data.api.repositoryScope +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class HouseRepository @Inject constructor(private val retrofitInstance: RetrofitInstance) { + + private val scope = repositoryScope() + private val api get() = retrofitInstance.houseApi + + private val _house = MutableStateFlow>(RoomieApiResponse.Pending) + + /** Your house. Every call below that returns the house updates this too. */ + val house: StateFlow> = _house.asStateFlow() + + /** Pipelines the response into [house]. */ + fun fetchHouse(houseId: Int, refresh: Boolean = false) { + scope.fetchInto(_house, refresh) { api.getHouse(houseId).house } + } + + suspend fun createHouse(body: CreateHouseBody): RoomieApiResponse = + updatingHouse { api.createHouse(body).house } + + suspend fun updateHouse(houseId: Int, body: UpdateHouseBody): RoomieApiResponse = + updatingHouse { api.updateHouse(houseId, body).house } + + suspend fun invite(houseId: Int, netIds: List): RoomieApiResponse = + updatingHouse { api.invite(houseId, InviteBody(netIds)).house } + + suspend fun cancelInvite(houseId: Int, inviteId: Int): RoomieApiResponse = + apiCall { api.cancelInvite(houseId, inviteId) }.also { it.ifSuccess { fetchHouse(houseId, refresh = true) } } + + suspend fun regenerateInviteCode(houseId: Int): RoomieApiResponse = + updatingHouse { api.regenerateInviteCode(houseId).house } + + suspend fun joinHouse(inviteCode: String): RoomieApiResponse = + updatingHouse { api.joinHouse(JoinHouseBody(inviteCode.trim())).house } + + suspend fun acceptInvite(inviteId: Int): RoomieApiResponse = + updatingHouse { api.acceptInvite(inviteId).house } + + suspend fun declineInvite(inviteId: Int): RoomieApiResponse = + apiCall { api.declineInvite(inviteId) } + + suspend fun leaveHouse(houseId: Int): RoomieApiResponse = + apiCall { api.leaveHouse(houseId) }.also { it.ifSuccess { _house.value = RoomieApiResponse.Pending } } + + suspend fun removeMember(houseId: Int, userId: Int): RoomieApiResponse = + apiCall { api.removeMember(houseId, userId) }.also { it.ifSuccess { fetchHouse(houseId, refresh = true) } } + + private suspend fun updatingHouse(call: suspend () -> HouseDto): RoomieApiResponse = + apiCall(call).also { result -> result.ifSuccess { _house.value = RoomieApiResponse.Success(it) } } +} diff --git a/app/src/main/java/com/example/roomie/data/NoteRepository.kt b/app/src/main/java/com/example/roomie/data/NoteRepository.kt new file mode 100644 index 0000000..6819f7a --- /dev/null +++ b/app/src/main/java/com/example/roomie/data/NoteRepository.kt @@ -0,0 +1,70 @@ +package com.example.roomie.data + +import com.example.roomie.data.api.CreateNoteBody +import com.example.roomie.data.api.NoteApiService +import com.example.roomie.data.api.NoteBoardResponse +import com.example.roomie.data.api.NoteColorDto +import com.example.roomie.data.api.NoteDto +import com.example.roomie.data.api.PinNoteBody +import com.example.roomie.data.api.ReportNoteBody +import com.example.roomie.data.api.RetrofitInstance +import com.example.roomie.data.api.RoomieApiResponse +import com.example.roomie.data.api.UpdateNoteBody +import com.example.roomie.data.api.apiCall +import com.example.roomie.data.api.fetchInto +import com.example.roomie.data.api.repositoryScope +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import java.time.Instant +import javax.inject.Inject +import javax.inject.Singleton + +/** The backend doesn't serve the Note Board yet; see [NoteApiService]. */ +@Singleton +class NoteRepository @Inject constructor(private val retrofitInstance: RetrofitInstance) { + + private val scope = repositoryScope() + private val api get() = retrofitInstance.noteApi + + private val _noteBoard = MutableStateFlow>(RoomieApiResponse.Pending) + + /** The first page of the board. Refreshed after every change below succeeds. */ + val noteBoard: StateFlow> = _noteBoard.asStateFlow() + + /** Pipelines the first page into [noteBoard]. */ + fun fetchNoteBoard(houseId: Int, refresh: Boolean = false) { + scope.fetchInto(_noteBoard, refresh) { api.getNotes(houseId, before = null) } + } + + /** Older notes. Pass the previous page's `nextCursor` as [before]. Doesn't touch [noteBoard]. */ + suspend fun getOlderNotes(houseId: Int, before: Int): RoomieApiResponse = + apiCall { api.getNotes(houseId, before) } + + suspend fun createNote( + houseId: Int, + body: String, + color: NoteColorDto? = null, + pinnedUntil: Instant? = null, + ): RoomieApiResponse = + changing(houseId) { api.createNote(houseId, CreateNoteBody(body.trim(), color, pinnedUntil)).note } + + suspend fun updateNote(houseId: Int, noteId: Int, body: String? = null, color: NoteColorDto? = null): RoomieApiResponse = + changing(houseId) { api.updateNote(houseId, noteId, UpdateNoteBody(body?.trim(), color)).note } + + suspend fun deleteNote(houseId: Int, noteId: Int): RoomieApiResponse = + changing(houseId) { api.deleteNote(houseId, noteId) } + + /** Leave [until] null to pin until someone unpins it. */ + suspend fun pinNote(houseId: Int, noteId: Int, until: Instant? = null): RoomieApiResponse = + changing(houseId) { api.pinNote(houseId, noteId, PinNoteBody(until)).note } + + suspend fun unpinNote(houseId: Int, noteId: Int): RoomieApiResponse = + changing(houseId) { api.unpinNote(houseId, noteId).note } + + suspend fun reportNote(houseId: Int, noteId: Int, reason: String? = null): RoomieApiResponse = + apiCall { api.reportNote(houseId, noteId, ReportNoteBody(reason)) } + + private suspend fun changing(houseId: Int, call: suspend () -> T): RoomieApiResponse = + apiCall(call).also { it.ifSuccess { fetchNoteBoard(houseId, refresh = true) } } +} diff --git a/app/src/main/java/com/example/roomie/data/ShoppingRepository.kt b/app/src/main/java/com/example/roomie/data/ShoppingRepository.kt new file mode 100644 index 0000000..df8aa87 --- /dev/null +++ b/app/src/main/java/com/example/roomie/data/ShoppingRepository.kt @@ -0,0 +1,60 @@ +package com.example.roomie.data + +import com.example.roomie.data.api.AddShoppingItemBody +import com.example.roomie.data.api.BuyItemBody +import com.example.roomie.data.api.RetrofitInstance +import com.example.roomie.data.api.RoomieApiResponse +import com.example.roomie.data.api.ShoppingCategory +import com.example.roomie.data.api.ShoppingItemDto +import com.example.roomie.data.api.ShoppingListResponse +import com.example.roomie.data.api.UpdateShoppingItemBody +import com.example.roomie.data.api.apiCall +import com.example.roomie.data.api.fetchInto +import com.example.roomie.data.api.repositoryScope +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class ShoppingRepository @Inject constructor(private val retrofitInstance: RetrofitInstance) { + + private val scope = repositoryScope() + private val api get() = retrofitInstance.shoppingApi + + private val _shoppingList = MutableStateFlow>(RoomieApiResponse.Pending) + + /** Needed and recently bought items. Refreshed after every change below succeeds. */ + val shoppingList: StateFlow> = _shoppingList.asStateFlow() + + /** Pipelines the response into [shoppingList]. */ + fun fetchShoppingList(houseId: Int, refresh: Boolean = false) { + scope.fetchInto(_shoppingList, refresh) { api.getShoppingList(houseId) } + } + + suspend fun addItem(houseId: Int, name: String, category: ShoppingCategory? = null): RoomieApiResponse = + changing(houseId) { api.addItem(houseId, AddShoppingItemBody(name.trim(), category)).item } + + suspend fun updateItem(houseId: Int, itemId: Int, body: UpdateShoppingItemBody): RoomieApiResponse = + changing(houseId) { api.updateItem(houseId, itemId, body).item } + + suspend fun deleteItem(houseId: Int, itemId: Int): RoomieApiResponse = + changing(houseId) { api.deleteItem(houseId, itemId) } + + suspend fun claimItem(houseId: Int, itemId: Int): RoomieApiResponse = + changing(houseId) { api.claimItem(houseId, itemId).item } + + suspend fun unclaimItem(houseId: Int, itemId: Int): RoomieApiResponse = + changing(houseId) { api.unclaimItem(houseId, itemId).item } + + suspend fun buyItem(houseId: Int, itemId: Int, priceCents: Int? = null): RoomieApiResponse = + changing(houseId) { api.buyItem(houseId, itemId, BuyItemBody(priceCents)).item } + + suspend fun unbuyItem(houseId: Int, itemId: Int): RoomieApiResponse = + changing(houseId) { api.unbuyItem(houseId, itemId).item } + + /** Moving an item can change both lists and the billable total, so refetch rather than patch. */ + private suspend fun changing(houseId: Int, call: suspend () -> T): RoomieApiResponse = + apiCall(call).also { it.ifSuccess { fetchShoppingList(houseId, refresh = true) } } +} diff --git a/app/src/main/java/com/example/roomie/data/api/ApiModels.kt b/app/src/main/java/com/example/roomie/data/api/ApiModels.kt new file mode 100644 index 0000000..42c1136 --- /dev/null +++ b/app/src/main/java/com/example/roomie/data/api/ApiModels.kt @@ -0,0 +1,145 @@ +package com.example.roomie.data.api + +import java.time.Instant +import java.time.LocalDate + +// Objects the backend returns, shared across services. Money is whole cents and IDs are ints. +// These mirror the API exactly; map them to the app's models in data/Models.kt at the repository +// or ViewModel layer. + +enum class MemberRole { OWNER, MEMBER } + +enum class ChoreFrequency { DAILY, EVERY_OTHER_DAY, WEEKLY, BIWEEKLY, MONTHLY } + +/** Computed by the server; not stored. */ +enum class TurnStatus { DONE, OVERDUE, DUE_TODAY, UPCOMING } + +enum class ShoppingCategory { GROCERIES, HOUSEHOLD, OTHER } + +enum class ShoppingStatus { NEEDED, BOUGHT } + +/** Proposed; the Note Board isn't built on the backend yet. */ +enum class NoteColorDto { YELLOW, PINK, BLUE, GREEN, PURPLE } + +/** The public view of a person: members, rotation, assignee, claimedBy, … */ +data class UserDto( + val id: Int, + /** Lowercase, e.g. `mnh49`. */ + val netid: String, + val name: String, + val avatarUrl: String?, +) + +/** Your own user, from `/auth/login` and `/users/me`. */ +data class SelfDto( + val id: Int, + val netid: String, + val name: String, + val avatarUrl: String?, + val email: String, + val major: String?, + val createdAt: Instant, +) + +/** A [UserDto] plus what only makes sense inside a house. */ +data class MemberDto( + val id: Int, + val netid: String, + val name: String, + val avatarUrl: String?, + val role: MemberRole, + /** If the owner leaves, the member who joined earliest becomes owner. */ + val joinedAt: Instant, +) + +data class HouseDto( + val id: Int, + val name: String, + /** e.g. `LOFT-4827`. Not case-sensitive. */ + val inviteCode: String, + val unit: String?, + val leaseEndsOn: LocalDate?, + /** IANA name. Decides what "today" means for chores. */ + val timezone: String, + val members: List, + val pendingInvites: List, +) + +/** An invite the house sent that hasn't been answered. */ +data class PendingInviteDto(val id: Int, val netid: String, val createdAt: Instant) + +/** The short house in `GET /users/me`. [role] is yours. */ +data class HouseSummaryDto(val id: Int, val name: String, val role: MemberRole) + +/** An invite you received. Has enough for the "Join this house?" prompt. */ +data class InviteDto( + val id: Int, + val createdAt: Instant, + val house: InviteHouseDto, + val invitedBy: UserDto, +) + +data class InviteHouseDto(val id: Int, val name: String, val members: List) + +data class ChoreDto( + val id: Int, + val title: String, + val frequency: ChoreFrequency, + /** The first turn's date. */ + val startsOn: LocalDate, + val allowSwaps: Boolean, + /** Remind the day before at this hour (0–23). Saved, but reminders aren't sent yet. */ + val reminderHour: Int?, + /** In turn order. */ + val rotation: List, + /** The next 3 turns. */ + val comingUp: List, +) + +/** One occurrence of a chore. Its ID is the `assignmentId` in URLs. */ +data class TurnDto( + val id: Int, + val chore: TurnChoreDto, + val dueOn: LocalDate, + val status: TurnStatus, + val assignee: UserDto, + val completedAt: Instant?, + /** Who actually did it. Can differ from [assignee]. */ + val completedBy: UserDto?, + /** The chore allows swaps and the turn is upcoming and unfinished. */ + val canSwap: Boolean, +) + +data class TurnChoreDto(val id: Int, val title: String, val frequency: ChoreFrequency) + +data class ShoppingItemDto( + val id: Int, + val name: String, + val category: ShoppingCategory, + val status: ShoppingStatus, + val priceCents: Int?, + val addedBy: UserDto, + /** "I'll get it". Cleared when bought. */ + val claimedBy: UserDto?, + val boughtBy: UserDto?, + val boughtAt: Instant?, + /** Non-null means the item is on a bill and locked. */ + val billId: Int?, + val createdAt: Instant, + val updatedAt: Instant, +) + +data class NoteDto( + val id: Int, + /** 1 to 500 characters. */ + val body: String, + val color: NoteColorDto, + /** Compare `author.id` with your own ID to show Edit and Delete. */ + val author: UserDto, + val pinned: Boolean, + /** When the pin ends. Null on a pinned note means until someone unpins it. */ + val pinnedUntil: Instant?, + val createdAt: Instant, + /** Later than [createdAt] means it was edited. */ + val updatedAt: Instant, +) diff --git a/app/src/main/java/com/example/roomie/data/api/ChoreApiService.kt b/app/src/main/java/com/example/roomie/data/api/ChoreApiService.kt new file mode 100644 index 0000000..ce2a8ed --- /dev/null +++ b/app/src/main/java/com/example/roomie/data/api/ChoreApiService.kt @@ -0,0 +1,113 @@ +package com.example.roomie.data.api + +import retrofit2.http.Body +import retrofit2.http.DELETE +import retrofit2.http.GET +import retrofit2.http.PATCH +import retrofit2.http.POST +import retrofit2.http.Path +import retrofit2.http.Query +import java.time.LocalDate +import java.time.YearMonth + +interface ChoreApiService { + + @GET("houses/{houseId}/chores") + suspend fun getChores(@Path("houseId") houseId: Int): ChoresResponse + + /** The first person in [CreateChoreBody.rotation] does the first turn. */ + @POST("houses/{houseId}/chores") + suspend fun createChore(@Path("houseId") houseId: Int, @Body body: CreateChoreBody): ChoreResponse + + @GET("houses/{houseId}/chores/{choreId}") + suspend fun getChore(@Path("houseId") houseId: Int, @Path("choreId") choreId: Int): ChoreResponse + + /** Finished and overdue turns never change. A new schedule can't start in the past. */ + @PATCH("houses/{houseId}/chores/{choreId}") + suspend fun updateChore( + @Path("houseId") houseId: Int, + @Path("choreId") choreId: Int, + @Body body: UpdateChoreBody, + ): ChoreResponse + + /** Finished turns stay in the history and stats. */ + @DELETE("houses/{houseId}/chores/{choreId}") + suspend fun deleteChore(@Path("houseId") houseId: Int, @Path("choreId") choreId: Int) + + /** + * Turns due between [from] and [to] (at most 62 days apart), sorted by due date. + * Home uses `from = to = today, assignee = "me", includeOverdue = true`. + * + * @param assignee `"me"` or a user ID. + * @param includeOverdue Adds unfinished turns from the 30 days before [from]. + */ + @GET("houses/{houseId}/chore-assignments") + suspend fun getAssignments( + @Path("houseId") houseId: Int, + @Query("from") from: LocalDate, + @Query("to") to: LocalDate, + @Query("assignee") assignee: String? = null, + @Query("includeOverdue") includeOverdue: Boolean? = null, + ): AssignmentsResponse + + /** Anyone in the house can do it, and it counts for whoever did. */ + @POST("houses/{houseId}/chore-assignments/{assignmentId}/complete") + suspend fun completeAssignment( + @Path("houseId") houseId: Int, + @Path("assignmentId") assignmentId: Int, + ): AssignmentResponse + + @DELETE("houses/{houseId}/chore-assignments/{assignmentId}/complete") + suspend fun uncompleteAssignment( + @Path("houseId") houseId: Int, + @Path("assignmentId") assignmentId: Int, + ): AssignmentResponse + + /** Trades two upcoming turns of the same chore. You must hold one of them. */ + @POST("houses/{houseId}/chore-assignments/{assignmentId}/swap") + suspend fun swapAssignment( + @Path("houseId") houseId: Int, + @Path("assignmentId") assignmentId: Int, + @Body body: SwapBody, + ): AssignmentsResponse + + /** Turns each person finished in [month] (defaults to this month). */ + @GET("houses/{houseId}/chores/stats") + suspend fun getChoreStats( + @Path("houseId") houseId: Int, + @Query("month") month: YearMonth? = null, + ): ChoreStatsResponse +} + +data class ChoresResponse(val chores: List) + +data class ChoreResponse(val chore: ChoreDto) + +data class AssignmentsResponse(val assignments: List) + +data class AssignmentResponse(val assignment: TurnDto) + +data class ChoreStatsResponse(val month: String, val members: List) + +data class MemberChoreStatsDto(val user: UserDto, val done: Int) + +data class CreateChoreBody( + val title: String, + val frequency: ChoreFrequency, + val startsOn: LocalDate, + /** User IDs in turn order. */ + val rotation: List, + val allowSwaps: Boolean? = null, + val reminderHour: Int? = null, +) + +data class UpdateChoreBody( + val title: String? = null, + val frequency: ChoreFrequency? = null, + val startsOn: LocalDate? = null, + val rotation: List? = null, + val allowSwaps: Boolean? = null, + val reminderHour: Int? = null, +) + +data class SwapBody(val withAssignmentId: Int) diff --git a/app/src/main/java/com/example/roomie/data/api/HouseApiService.kt b/app/src/main/java/com/example/roomie/data/api/HouseApiService.kt new file mode 100644 index 0000000..bd8d399 --- /dev/null +++ b/app/src/main/java/com/example/roomie/data/api/HouseApiService.kt @@ -0,0 +1,74 @@ +package com.example.roomie.data.api + +import retrofit2.http.Body +import retrofit2.http.DELETE +import retrofit2.http.GET +import retrofit2.http.PATCH +import retrofit2.http.POST +import retrofit2.http.Path +import java.time.LocalDate + +interface HouseApiService { + + /** Creates a house with you as owner and invites [CreateHouseBody.inviteNetids]. */ + @POST("houses") + suspend fun createHouse(@Body body: CreateHouseBody): HouseResponse + + @GET("houses/{houseId}") + suspend fun getHouse(@Path("houseId") houseId: Int): HouseResponse + + /** Any member can edit house settings. */ + @PATCH("houses/{houseId}") + suspend fun updateHouse(@Path("houseId") houseId: Int, @Body body: UpdateHouseBody): HouseResponse + + /** Skips people already in the house. */ + @POST("houses/{houseId}/invites") + suspend fun invite(@Path("houseId") houseId: Int, @Body body: InviteBody): HouseResponse + + @DELETE("houses/{houseId}/invites/{inviteId}") + suspend fun cancelInvite(@Path("houseId") houseId: Int, @Path("inviteId") inviteId: Int) + + /** Owner only. The old code stops working. */ + @POST("houses/{houseId}/invite-code") + suspend fun regenerateInviteCode(@Path("houseId") houseId: Int): HouseResponse + + @POST("houses/join") + suspend fun joinHouse(@Body body: JoinHouseBody): HouseResponse + + @POST("invites/{inviteId}/accept") + suspend fun acceptInvite(@Path("inviteId") inviteId: Int): HouseResponse + + @POST("invites/{inviteId}/decline") + suspend fun declineInvite(@Path("inviteId") inviteId: Int) + + /** Also removes you from rotations, releases your shopping claims and passes on ownership. */ + @DELETE("houses/{houseId}/members/me") + suspend fun leaveHouse(@Path("houseId") houseId: Int) + + /** Owner only, with the same cleanup as leaving. */ + @DELETE("houses/{houseId}/members/{userId}") + suspend fun removeMember(@Path("houseId") houseId: Int, @Path("userId") userId: Int) +} + +data class HouseResponse(val house: HouseDto) + +data class CreateHouseBody( + val name: String, + val unit: String? = null, + val leaseEndsOn: LocalDate? = null, + /** IANA name. The server defaults to America/New_York. */ + val timezone: String? = null, + val inviteNetids: List? = null, +) + +data class UpdateHouseBody( + val name: String? = null, + val unit: String? = null, + val leaseEndsOn: LocalDate? = null, + val timezone: String? = null, +) + +data class InviteBody(val netids: List) + +/** Not case-sensitive. */ +data class JoinHouseBody(val inviteCode: String) diff --git a/app/src/main/java/com/example/roomie/data/api/NetworkModule.kt b/app/src/main/java/com/example/roomie/data/api/NetworkModule.kt new file mode 100644 index 0000000..cdd507b --- /dev/null +++ b/app/src/main/java/com/example/roomie/data/api/NetworkModule.kt @@ -0,0 +1,14 @@ +package com.example.roomie.data.api + +import dagger.Binds +import dagger.Module +import dagger.hilt.InstallIn +import dagger.hilt.components.SingletonComponent + +@Module +@InstallIn(SingletonComponent::class) +abstract class NetworkModule { + + @Binds + abstract fun bindTokenProvider(provider: DevTokenProvider): TokenProvider +} diff --git a/app/src/main/java/com/example/roomie/data/api/NoteApiService.kt b/app/src/main/java/com/example/roomie/data/api/NoteApiService.kt new file mode 100644 index 0000000..988fb2b --- /dev/null +++ b/app/src/main/java/com/example/roomie/data/api/NoteApiService.kt @@ -0,0 +1,92 @@ +package com.example.roomie.data.api + +import retrofit2.http.Body +import retrofit2.http.DELETE +import retrofit2.http.GET +import retrofit2.http.PATCH +import retrofit2.http.POST +import retrofit2.http.Path +import retrofit2.http.Query +import java.time.Instant + +/** + * The Note Board. This is the proposed contract; the backend and the mock server don't serve + * it yet, so every call 404s for now. + */ +interface NoteApiService { + + /** + * Pinned notes, then the rest newest first. Pass the previous page's `nextCursor` as [before] + * to load older notes. [limit] defaults to 30 (max 100). + */ + @GET("houses/{houseId}/notes") + suspend fun getNotes( + @Path("houseId") houseId: Int, + @Query("before") before: Int? = null, + @Query("limit") limit: Int? = null, + ): NoteBoardResponse + + @POST("houses/{houseId}/notes") + suspend fun createNote(@Path("houseId") houseId: Int, @Body body: CreateNoteBody): NoteResponse + + @GET("houses/{houseId}/notes/{noteId}") + suspend fun getNote(@Path("houseId") houseId: Int, @Path("noteId") noteId: Int): NoteResponse + + /** Your own notes only. */ + @PATCH("houses/{houseId}/notes/{noteId}") + suspend fun updateNote( + @Path("houseId") houseId: Int, + @Path("noteId") noteId: Int, + @Body body: UpdateNoteBody, + ): NoteResponse + + /** The author or the house owner. */ + @DELETE("houses/{houseId}/notes/{noteId}") + suspend fun deleteNote(@Path("houseId") houseId: Int, @Path("noteId") noteId: Int) + + /** Pinning again replaces the end time. */ + @POST("houses/{houseId}/notes/{noteId}/pin") + suspend fun pinNote( + @Path("houseId") houseId: Int, + @Path("noteId") noteId: Int, + @Body body: PinNoteBody, + ): NoteResponse + + @DELETE("houses/{houseId}/notes/{noteId}/pin") + suspend fun unpinNote(@Path("houseId") houseId: Int, @Path("noteId") noteId: Int): NoteResponse + + /** Hides the note from you. You can't report your own. */ + @POST("houses/{houseId}/notes/{noteId}/report") + suspend fun reportNote( + @Path("houseId") houseId: Int, + @Path("noteId") noteId: Int, + @Body body: ReportNoteBody, + ) +} + +data class NoteBoardResponse( + /** Only filled on the first page. */ + val pinned: List, + val notes: List, + /** The `before` value for the next page, or null at the end. */ + val nextCursor: Int?, +) + +data class NoteResponse(val note: NoteDto) + +data class CreateNoteBody( + val body: String, + val color: NoteColorDto? = null, + val pinnedUntil: Instant? = null, +) + +data class UpdateNoteBody( + val body: String? = null, + val color: NoteColorDto? = null, +) + +/** Leave [until] null to pin until someone unpins it. */ +data class PinNoteBody(val until: Instant? = null) + +/** Up to 200 characters. */ +data class ReportNoteBody(val reason: String? = null) diff --git a/app/src/main/java/com/example/roomie/data/api/RetrofitInstance.kt b/app/src/main/java/com/example/roomie/data/api/RetrofitInstance.kt new file mode 100644 index 0000000..f25f41c --- /dev/null +++ b/app/src/main/java/com/example/roomie/data/api/RetrofitInstance.kt @@ -0,0 +1,73 @@ +package com.example.roomie.data.api + +import com.example.roomie.BuildConfig +import kotlinx.coroutines.runBlocking +import okhttp3.Authenticator +import okhttp3.Interceptor +import okhttp3.OkHttpClient +import okhttp3.logging.HttpLoggingInterceptor +import retrofit2.Retrofit +import retrofit2.converter.gson.GsonConverterFactory +import javax.inject.Inject +import javax.inject.Singleton + +/** + * The Retrofit client every Roomie API service shares. It adds `Authorization: Bearer ` + * to each request and, on a 401, asks [TokenProvider] for a fresh token and retries once. + */ +@Singleton +class RetrofitInstance internal constructor(retrofit: Retrofit) { + + @Inject + constructor(tokenProvider: TokenProvider) : + this(roomieRetrofit(BuildConfig.API_URL, tokenProvider, logBodies = BuildConfig.DEBUG)) + + val userApi: UserApiService by lazy { retrofit.create(UserApiService::class.java) } + val houseApi: HouseApiService by lazy { retrofit.create(HouseApiService::class.java) } + val choreApi: ChoreApiService by lazy { retrofit.create(ChoreApiService::class.java) } + val shoppingApi: ShoppingApiService by lazy { retrofit.create(ShoppingApiService::class.java) } + val noteApi: NoteApiService by lazy { retrofit.create(NoteApiService::class.java) } +} + +/** Builds the client. Separate from [RetrofitInstance] so tests can point it at a fake server. */ +internal fun roomieRetrofit( + baseUrl: String, + tokenProvider: TokenProvider, + logBodies: Boolean, +): Retrofit { + val authInterceptor = Interceptor { chain -> + val request = chain.request() + val token = runBlocking { tokenProvider.token(forceRefresh = false) } + if (token == null || request.header("Authorization") != null) { + return@Interceptor chain.proceed(request) + } + chain.proceed(request.newBuilder().header("Authorization", "Bearer $token").build()) + } + + val authenticator = Authenticator { _, response -> + // Retry once. A second 401 means the fresh token was rejected too. + if (response.priorResponse != null) return@Authenticator null + val token = runBlocking { tokenProvider.token(forceRefresh = true) } + ?: return@Authenticator null + response.request.newBuilder().header("Authorization", "Bearer $token").build() + } + + val client = OkHttpClient.Builder() + .addInterceptor(authInterceptor) + .apply { + if (logBodies) { + addInterceptor(HttpLoggingInterceptor().apply { + level = HttpLoggingInterceptor.Level.BODY + redactHeader("Authorization") + }) + } + } + .authenticator(authenticator) + .build() + + return Retrofit.Builder() + .baseUrl(baseUrl) + .client(client) + .addConverterFactory(GsonConverterFactory.create(RoomieGson.gson)) + .build() +} diff --git a/app/src/main/java/com/example/roomie/data/api/RoomieApiResponse.kt b/app/src/main/java/com/example/roomie/data/api/RoomieApiResponse.kt new file mode 100644 index 0000000..65db4f8 --- /dev/null +++ b/app/src/main/java/com/example/roomie/data/api/RoomieApiResponse.kt @@ -0,0 +1,146 @@ +package com.example.roomie.data.api + +import androidx.compose.runtime.Composable +import com.google.gson.JsonElement +import com.google.gson.JsonParseException +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.launch +import retrofit2.HttpException +import java.io.IOException +import java.time.format.DateTimeParseException + +/** + * The state of an API call returning [T]: still loading ([Pending]), done ([Success]), or failed + * ([Error]). Endpoints that return 204 give `Success(Unit)`. + */ +sealed class RoomieApiResponse { + data object Pending : RoomieApiResponse() + data class Success(val data: T) : RoomieApiResponse() + data class Error(val error: ApiError) : RoomieApiResponse() + + fun map(transform: (T) -> R): RoomieApiResponse = when (this) { + Pending -> Pending + is Success -> Success(transform(data)) + is Error -> this + } + + /** Both responses' data as a pair. [Error] wins over [Pending]. */ + fun combine(other: RoomieApiResponse): RoomieApiResponse> = when { + this is Error -> this + other is Error -> other + this is Success && other is Success -> Success(data to other.data) + else -> Pending + } + + fun dataOrNull(): T? = (this as? Success)?.data + + fun asSuccessOrNull(): Success? = this as? Success + + /** Basically a force `!!`, but for [Success] responses. */ + fun asSuccess(): Success = + this as? Success ?: throw IllegalStateException("Response is not a success: $this") + + /** Runs [block] if the response is a [Success]. */ + fun ifSuccess(block: (T) -> Unit) { + if (this is Success) block(data) + } + + @Composable + fun ComposableIfSuccess(block: @Composable (T) -> Unit) { + if (this is Success) block(data) + } +} + +/** A response with its data dropped, for screens that only show loading, done, or failed. */ +sealed class RoomieApiState { + data object Success : RoomieApiState() + data object Error : RoomieApiState() + data object Loading : RoomieApiState() +} + +fun RoomieApiResponse<*>.toRoomieApiState(): RoomieApiState = when (this) { + is RoomieApiResponse.Success -> RoomieApiState.Success + is RoomieApiResponse.Error -> RoomieApiState.Error + RoomieApiResponse.Pending -> RoomieApiState.Loading +} + +data class ApiError( + val code: ApiErrorCode, + /** The HTTP status, or null when the request never got a response. */ + val statusCode: Int?, + val message: String, + /** For [ApiErrorCode.VALIDATION_ERROR]: each bad field (e.g. `body.name`) and what's wrong with it. */ + val fieldErrors: Map = emptyMap(), +) + +/** The backend's `errorCode`s, plus [NETWORK] and [UNKNOWN] for failures it didn't describe. */ +enum class ApiErrorCode { + VALIDATION_ERROR, BAD_REQUEST, UNAUTHORIZED, FORBIDDEN, NOT_FOUND, CONFLICT, TOO_MANY_REQUESTS, + NETWORK, UNKNOWN, +} + +/** Runs one API call and turns any failure into a [RoomieApiResponse.Error] instead of throwing. */ +suspend fun apiCall(call: suspend () -> T): RoomieApiResponse = try { + RoomieApiResponse.Success(call()) +} catch (e: CancellationException) { + throw e +} catch (e: HttpException) { + RoomieApiResponse.Error(e.toApiError()) +} catch (e: IOException) { + RoomieApiResponse.Error(ApiError(ApiErrorCode.NETWORK, null, "Couldn't reach the server.")) +} catch (e: JsonParseException) { + RoomieApiResponse.Error(ApiError(ApiErrorCode.UNKNOWN, null, "Unexpected response: ${e.message}")) +} catch (e: DateTimeParseException) { + RoomieApiResponse.Error(ApiError(ApiErrorCode.UNKNOWN, null, "Unexpected date: ${e.message}")) +} + +/** The scope a repository runs its fetches in. Lives as long as the (singleton) repository. */ +internal fun repositoryScope(): CoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + +/** + * Starts [call] on this scope and pipelines the result into [into], like Resell's `fetchX()`s. + * Shows [RoomieApiResponse.Pending] first unless [refresh] is true; a failed refresh keeps the + * data already shown instead of replacing it with an error. + */ +internal fun CoroutineScope.fetchInto( + into: MutableStateFlow>, + refresh: Boolean = false, + call: suspend () -> T, +) { + if (!refresh) into.value = RoomieApiResponse.Pending + launch { + val result = apiCall(call) + if (!(refresh && result is RoomieApiResponse.Error && into.value is RoomieApiResponse.Success)) { + into.value = result + } + } +} + +/** `{ status, statusCode, message, errorCode, data }`, the body of every error response. */ +private class ErrorBody(val message: String?, val errorCode: String?, val data: JsonElement?) + +private fun HttpException.toApiError(): ApiError { + val body = try { + response()?.errorBody()?.string()?.let { RoomieGson.gson.fromJson(it, ErrorBody::class.java) } + } catch (e: Exception) { + null + } + val code = ApiErrorCode.entries.firstOrNull { it.name == body?.errorCode } ?: when (code()) { + 400 -> ApiErrorCode.BAD_REQUEST + 401 -> ApiErrorCode.UNAUTHORIZED + 403 -> ApiErrorCode.FORBIDDEN + 404 -> ApiErrorCode.NOT_FOUND + 409 -> ApiErrorCode.CONFLICT + 429 -> ApiErrorCode.TOO_MANY_REQUESTS + else -> ApiErrorCode.UNKNOWN + } + val fieldErrors = body?.data?.takeIf { it.isJsonObject }?.asJsonObject?.entrySet() + ?.filter { it.value.isJsonPrimitive } + ?.associate { it.key to it.value.asString } + .orEmpty() + return ApiError(code, code(), body?.message ?: message(), fieldErrors) +} diff --git a/app/src/main/java/com/example/roomie/data/api/RoomieGson.kt b/app/src/main/java/com/example/roomie/data/api/RoomieGson.kt new file mode 100644 index 0000000..a790153 --- /dev/null +++ b/app/src/main/java/com/example/roomie/data/api/RoomieGson.kt @@ -0,0 +1,38 @@ +package com.example.roomie.data.api + +import com.google.gson.Gson +import com.google.gson.GsonBuilder +import com.google.gson.TypeAdapter +import com.google.gson.stream.JsonReader +import com.google.gson.stream.JsonWriter +import java.time.Instant +import java.time.LocalDate +import java.time.OffsetDateTime + +/** + * The API sends dates as `YYYY-MM-DD` ([LocalDate]) and timestamps as ISO 8601 ([Instant]). + * Nulls are left out of request bodies, so an unset PATCH field isn't changed. + */ +object RoomieGson { + val gson: Gson = GsonBuilder() + .registerTypeAdapter(LocalDate::class.java, LocalDateAdapter.nullSafe()) + .registerTypeAdapter(Instant::class.java, InstantAdapter.nullSafe()) + .create() +} + +private object LocalDateAdapter : TypeAdapter() { + override fun write(out: JsonWriter, value: LocalDate) { + out.value(value.toString()) + } + + override fun read(reader: JsonReader): LocalDate = LocalDate.parse(reader.nextString()) +} + +private object InstantAdapter : TypeAdapter() { + override fun write(out: JsonWriter, value: Instant) { + out.value(value.toString()) + } + + // OffsetDateTime accepts both `Z` and `+00:00` offsets. + override fun read(reader: JsonReader): Instant = OffsetDateTime.parse(reader.nextString()).toInstant() +} diff --git a/app/src/main/java/com/example/roomie/data/api/ShoppingApiService.kt b/app/src/main/java/com/example/roomie/data/api/ShoppingApiService.kt new file mode 100644 index 0000000..e41ea93 --- /dev/null +++ b/app/src/main/java/com/example/roomie/data/api/ShoppingApiService.kt @@ -0,0 +1,79 @@ +package com.example.roomie.data.api + +import retrofit2.http.Body +import retrofit2.http.DELETE +import retrofit2.http.GET +import retrofit2.http.PATCH +import retrofit2.http.POST +import retrofit2.http.Path +import retrofit2.http.Query + +interface ShoppingApiService { + + /** The whole Shopping screen: Needed, Bought, and the "Split $X as a bill" total. */ + @GET("houses/{houseId}/shopping-items") + suspend fun getShoppingList( + @Path("houseId") houseId: Int, + @Query("category") category: ShoppingCategory? = null, + @Query("status") status: ShoppingStatus? = null, + ): ShoppingListResponse + + @POST("houses/{houseId}/shopping-items") + suspend fun addItem(@Path("houseId") houseId: Int, @Body body: AddShoppingItemBody): ShoppingItemResponse + + /** Fails once the item is on a bill. */ + @PATCH("houses/{houseId}/shopping-items/{itemId}") + suspend fun updateItem( + @Path("houseId") houseId: Int, + @Path("itemId") itemId: Int, + @Body body: UpdateShoppingItemBody, + ): ShoppingItemResponse + + @DELETE("houses/{houseId}/shopping-items/{itemId}") + suspend fun deleteItem(@Path("houseId") houseId: Int, @Path("itemId") itemId: Int) + + /** "I'll get it". */ + @POST("houses/{houseId}/shopping-items/{itemId}/claim") + suspend fun claimItem(@Path("houseId") houseId: Int, @Path("itemId") itemId: Int): ShoppingItemResponse + + @DELETE("houses/{houseId}/shopping-items/{itemId}/claim") + suspend fun unclaimItem(@Path("houseId") houseId: Int, @Path("itemId") itemId: Int): ShoppingItemResponse + + /** Marks the item bought and clears its claim. The price can be added later with [updateItem]. */ + @POST("houses/{houseId}/shopping-items/{itemId}/buy") + suspend fun buyItem( + @Path("houseId") houseId: Int, + @Path("itemId") itemId: Int, + @Body body: BuyItemBody, + ): ShoppingItemResponse + + /** Also clears the price. */ + @DELETE("houses/{houseId}/shopping-items/{itemId}/buy") + suspend fun unbuyItem(@Path("houseId") houseId: Int, @Path("itemId") itemId: Int): ShoppingItemResponse +} + +data class ShoppingListResponse( + val needed: List, + /** Bought in the last 14 days or not yet billed, newest first. */ + val bought: List, + val billable: BillableDto, +) + +/** Items you bought and priced that aren't on a bill yet. */ +data class BillableDto(val itemIds: List, val totalCents: Int) + +data class ShoppingItemResponse(val item: ShoppingItemDto) + +data class AddShoppingItemBody( + val name: String, + /** The server defaults to [ShoppingCategory.GROCERIES]. */ + val category: ShoppingCategory? = null, +) + +data class UpdateShoppingItemBody( + val name: String? = null, + val category: ShoppingCategory? = null, + val priceCents: Int? = null, +) + +data class BuyItemBody(val priceCents: Int? = null) diff --git a/app/src/main/java/com/example/roomie/data/api/TokenProvider.kt b/app/src/main/java/com/example/roomie/data/api/TokenProvider.kt new file mode 100644 index 0000000..6f41198 --- /dev/null +++ b/app/src/main/java/com/example/roomie/data/api/TokenProvider.kt @@ -0,0 +1,23 @@ +package com.example.roomie.data.api + +import javax.inject.Inject +import javax.inject.Singleton + +/** Where [RetrofitInstance] gets the token it sends as `Authorization: Bearer `. */ +fun interface TokenProvider { + /** Returns the token, or null when signed out. [forceRefresh] is true after a 401. */ + suspend fun token(forceRefresh: Boolean): String? +} + +/** + * Signs in as [netId] with the `dev:` tokens that the local backend and the mock server + * accept. The deployed server rejects them, so it needs a Firebase ID token instead. + * [NetworkModule] binds this as the app's [TokenProvider]; swap the binding once Google sign-in exists. + */ +@Singleton +class DevTokenProvider @Inject constructor() : TokenProvider { + @Volatile + var netId: String? = null + + override suspend fun token(forceRefresh: Boolean): String? = netId?.let { "dev:$it" } +} diff --git a/app/src/main/java/com/example/roomie/data/api/UserApiService.kt b/app/src/main/java/com/example/roomie/data/api/UserApiService.kt new file mode 100644 index 0000000..98551b7 --- /dev/null +++ b/app/src/main/java/com/example/roomie/data/api/UserApiService.kt @@ -0,0 +1,48 @@ +package com.example.roomie.data.api + +import retrofit2.http.Body +import retrofit2.http.GET +import retrofit2.http.PATCH +import retrofit2.http.POST + +interface UserApiService { + + /** Signs in, creating the account the first time. Call it right after Google sign-in. */ + @POST("auth/login") + suspend fun login(): LoginResponse + + /** The user, their house and pending invites. Use it on app launch. */ + @GET("users/me") + suspend fun getMe(): MeResponse + + @PATCH("users/me") + suspend fun updateMe(@Body body: UpdateMeBody): MeResponse + + /** Checks the server and its database are up. Needs no token. */ + @GET("health") + suspend fun health(): HealthResponse +} + +/** + * Open Home if there's a [house], a "Join this house?" prompt if there are [pendingInvites], + * otherwise onboarding. + */ +data class LoginResponse( + val isNewUser: Boolean, + val user: SelfDto, + val house: HouseDto?, + val pendingInvites: List, +) + +data class MeResponse( + val user: SelfDto, + val house: HouseSummaryDto?, + val pendingInvites: List, +) + +data class UpdateMeBody( + val name: String? = null, + val major: String? = null, +) + +data class HealthResponse(val status: String, val database: String) diff --git a/app/src/main/java/com/example/roomie/ui/chores/ChoresScreens.kt b/app/src/main/java/com/example/roomie/ui/chores/ChoresScreens.kt index e7f5d38..55a7170 100644 --- a/app/src/main/java/com/example/roomie/ui/chores/ChoresScreens.kt +++ b/app/src/main/java/com/example/roomie/ui/chores/ChoresScreens.kt @@ -49,7 +49,6 @@ import androidx.compose.ui.unit.sp import androidx.lifecycle.ViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.viewModelScope -import androidx.lifecycle.viewmodel.compose.viewModel import com.example.roomie.R import com.example.roomie.data.ChoreRules import com.example.roomie.data.FakeRoomieRepository @@ -104,8 +103,12 @@ import java.time.DayOfWeek import java.time.LocalDate import java.time.format.TextStyle import java.util.Locale +import dagger.hilt.android.lifecycle.HiltViewModel +import javax.inject.Inject +import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel -class ChoresViewModel(private val repo: FakeRoomieRepository = FakeRoomieRepository) : ViewModel() { +@HiltViewModel +class ChoresViewModel @Inject constructor(private val repo: FakeRoomieRepository) : ViewModel() { val state: StateFlow = repo.state.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), repo.state.value) fun today(): LocalDate = repo.today() fun toggleDone(id: String) = repo.toggleChoreDone(id) @@ -135,7 +138,7 @@ fun ChoresScreen( onOpenSettings: () -> Unit, onOpenChore: (String) -> Unit, onManageRotations: () -> Unit, - vm: ChoresViewModel = viewModel(), + vm: ChoresViewModel = hiltViewModel(), ) { val state by vm.state.collectAsStateWithLifecycle() val house = state.house ?: return @@ -498,7 +501,7 @@ private fun AddChoreSheet( /** "Chore details": who has it, when it's due, and Mark Complete. */ @Composable -fun ChoreDetailScreen(choreId: String, onBack: () -> Unit, onViewRotation: (String) -> Unit, vm: ChoresViewModel = viewModel()) { +fun ChoreDetailScreen(choreId: String, onBack: () -> Unit, onViewRotation: (String) -> Unit, vm: ChoresViewModel = hiltViewModel()) { val state by vm.state.collectAsStateWithLifecycle() val me = state.session?.userId val chore = ChoreRules.choreById(state, choreId) @@ -562,7 +565,7 @@ fun ChoreDetailScreen(choreId: String, onBack: () -> Unit, onViewRotation: (Stri /** "Manage Rotations": every rotation in the house with who's next. */ @Composable -fun ManageRotationsScreen(onBack: () -> Unit, onOpenRotation: (String) -> Unit, vm: ChoresViewModel = viewModel()) { +fun ManageRotationsScreen(onBack: () -> Unit, onOpenRotation: (String) -> Unit, vm: ChoresViewModel = hiltViewModel()) { val state by vm.state.collectAsStateWithLifecycle() val today = vm.today() @@ -603,7 +606,7 @@ fun ManageRotationsScreen(onBack: () -> Unit, onOpenRotation: (String) -> Unit, /** "Edit rotation": change people and pace from a future week, with a preview of the next turns. */ @Composable -fun EditRotationScreen(rotationId: String, onBack: () -> Unit, vm: ChoresViewModel = viewModel()) { +fun EditRotationScreen(rotationId: String, onBack: () -> Unit, vm: ChoresViewModel = hiltViewModel()) { val state by vm.state.collectAsStateWithLifecycle() val house = state.house ?: return val rotation = state.rotations.firstOrNull { it.id == rotationId } diff --git a/app/src/main/java/com/example/roomie/ui/home/HomeScreen.kt b/app/src/main/java/com/example/roomie/ui/home/HomeScreen.kt index 91384be..6958132 100644 --- a/app/src/main/java/com/example/roomie/ui/home/HomeScreen.kt +++ b/app/src/main/java/com/example/roomie/ui/home/HomeScreen.kt @@ -45,7 +45,6 @@ import androidx.compose.ui.unit.sp import androidx.lifecycle.ViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.viewModelScope -import androidx.lifecycle.viewmodel.compose.viewModel import com.example.roomie.R import com.example.roomie.data.ChoreRules import com.example.roomie.data.FakeRoomieRepository @@ -78,8 +77,12 @@ import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.stateIn import java.time.LocalDate import java.time.LocalTime +import dagger.hilt.android.lifecycle.HiltViewModel +import javax.inject.Inject +import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel -class HomeViewModel(private val repo: FakeRoomieRepository = FakeRoomieRepository) : ViewModel() { +@HiltViewModel +class HomeViewModel @Inject constructor(private val repo: FakeRoomieRepository) : ViewModel() { val state: StateFlow = repo.state.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), repo.state.value) fun today(): LocalDate = repo.today() fun togglePin(id: String) = repo.togglePin(id) @@ -93,7 +96,7 @@ fun HomeScreen( onOpenBoard: () -> Unit, onOpenChores: () -> Unit, onOpenChore: (String) -> Unit, - vm: HomeViewModel = viewModel(), + vm: HomeViewModel = hiltViewModel(), ) { val state by vm.state.collectAsStateWithLifecycle() val house = state.house ?: return diff --git a/app/src/main/java/com/example/roomie/ui/notes/NoteBoardScreen.kt b/app/src/main/java/com/example/roomie/ui/notes/NoteBoardScreen.kt index cb221c4..582b934 100644 --- a/app/src/main/java/com/example/roomie/ui/notes/NoteBoardScreen.kt +++ b/app/src/main/java/com/example/roomie/ui/notes/NoteBoardScreen.kt @@ -90,8 +90,12 @@ import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.stateIn import java.time.LocalDate +import dagger.hilt.android.lifecycle.HiltViewModel +import javax.inject.Inject +import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel -class NotesViewModel(private val repo: FakeRoomieRepository = FakeRoomieRepository) : ViewModel() { +@HiltViewModel +class NotesViewModel @Inject constructor(private val repo: FakeRoomieRepository) : ViewModel() { val state: StateFlow = repo.state.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), repo.state.value) fun today(): LocalDate = repo.today() fun addNote(text: String, due: LocalDate?, pin: Boolean) = repo.addNote(text, due, pin) @@ -105,7 +109,7 @@ fun NoteBoardScreen( startComposing: Boolean, onComposeHandled: () -> Unit, onOpenSettings: () -> Unit, - vm: NotesViewModel = viewModel(), + vm: NotesViewModel = hiltViewModel(), ) { val state by vm.state.collectAsStateWithLifecycle() val me = state.session?.userId diff --git a/app/src/main/java/com/example/roomie/ui/onboarding/OnboardingScreens.kt b/app/src/main/java/com/example/roomie/ui/onboarding/OnboardingScreens.kt index 4d6d02a..4668cbc 100644 --- a/app/src/main/java/com/example/roomie/ui/onboarding/OnboardingScreens.kt +++ b/app/src/main/java/com/example/roomie/ui/onboarding/OnboardingScreens.kt @@ -55,7 +55,6 @@ import androidx.compose.ui.text.style.LineHeightStyle import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.lifecycle.compose.collectAsStateWithLifecycle -import androidx.lifecycle.viewmodel.compose.viewModel import com.example.roomie.R import com.example.roomie.data.Buddy import com.example.roomie.data.MemberStatus @@ -80,6 +79,7 @@ import com.example.roomie.ui.theme.RoomieType import com.example.roomie.ui.theme.Surface import com.example.roomie.ui.theme.TabIcon import com.example.roomie.ui.theme.TextSecondary +import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel // region Shared onboarding layout @@ -147,7 +147,7 @@ private fun StepProgress(step: Int, modifier: Modifier = Modifier) { // region 1. Sign in @Composable -fun SignInScreen(onSignedIn: (hasHouse: Boolean) -> Unit, vm: OnboardingViewModel = viewModel()) { +fun SignInScreen(onSignedIn: (hasHouse: Boolean) -> Unit, vm: OnboardingViewModel = hiltViewModel()) { var netId by rememberSaveable { mutableStateOf("") } var password by rememberSaveable { mutableStateOf("") } var error by remember { mutableStateOf(null) } @@ -211,7 +211,7 @@ fun PickBuddyScreen( editing: Boolean, onNext: () -> Unit, onBack: (() -> Unit)?, - vm: OnboardingViewModel = viewModel(), + vm: OnboardingViewModel = hiltViewModel(), ) { val state by vm.state.collectAsStateWithLifecycle() val session = state.session ?: return @@ -300,7 +300,7 @@ fun SetupChoiceScreen( onStartHouse: () -> Unit, onJoined: () -> Unit, onBack: (() -> Unit)?, - vm: OnboardingViewModel = viewModel(), + vm: OnboardingViewModel = hiltViewModel(), ) { val state by vm.state.collectAsStateWithLifecycle() val session = state.session ?: return @@ -401,7 +401,7 @@ private fun ChoiceCard( // region 4. Add roommates @Composable -fun AddRoommatesScreen(onNext: () -> Unit, onBack: () -> Unit, vm: OnboardingViewModel = viewModel()) { +fun AddRoommatesScreen(onNext: () -> Unit, onBack: () -> Unit, vm: OnboardingViewModel = hiltViewModel()) { val state by vm.state.collectAsStateWithLifecycle() val house = state.house ?: return val me = state.session?.userId @@ -471,7 +471,7 @@ fun AddRoommatesScreen(onNext: () -> Unit, onBack: () -> Unit, vm: OnboardingVie // region 5. Set up your house @Composable -fun SetUpHouseScreen(onEnter: () -> Unit, onBack: () -> Unit, vm: OnboardingViewModel = viewModel()) { +fun SetUpHouseScreen(onEnter: () -> Unit, onBack: () -> Unit, vm: OnboardingViewModel = hiltViewModel()) { val state by vm.state.collectAsStateWithLifecycle() val house = state.house ?: return val me = state.session?.userId diff --git a/app/src/main/java/com/example/roomie/ui/onboarding/OnboardingViewModel.kt b/app/src/main/java/com/example/roomie/ui/onboarding/OnboardingViewModel.kt index 11029af..34d1afb 100644 --- a/app/src/main/java/com/example/roomie/ui/onboarding/OnboardingViewModel.kt +++ b/app/src/main/java/com/example/roomie/ui/onboarding/OnboardingViewModel.kt @@ -8,8 +8,11 @@ import com.example.roomie.data.RoomieState import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.stateIn +import dagger.hilt.android.lifecycle.HiltViewModel +import javax.inject.Inject -class OnboardingViewModel(private val repo: FakeRoomieRepository = FakeRoomieRepository) : ViewModel() { +@HiltViewModel +class OnboardingViewModel @Inject constructor(private val repo: FakeRoomieRepository) : ViewModel() { val state: StateFlow = repo.state.stateIn(viewModelScope, SharingStarted.Eagerly, repo.state.value) diff --git a/app/src/main/java/com/example/roomie/ui/profile/MeScreen.kt b/app/src/main/java/com/example/roomie/ui/profile/MeScreen.kt index 60868bb..86b5273 100644 --- a/app/src/main/java/com/example/roomie/ui/profile/MeScreen.kt +++ b/app/src/main/java/com/example/roomie/ui/profile/MeScreen.kt @@ -37,7 +37,6 @@ import androidx.compose.ui.unit.sp import androidx.lifecycle.ViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.viewModelScope -import androidx.lifecycle.viewmodel.compose.viewModel import com.example.roomie.R import com.example.roomie.data.FakeRoomieRepository import com.example.roomie.data.MemberStatus @@ -66,8 +65,12 @@ import com.example.roomie.ui.theme.RoomieType import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.stateIn +import dagger.hilt.android.lifecycle.HiltViewModel +import javax.inject.Inject +import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel -class MeViewModel(private val repo: FakeRoomieRepository = FakeRoomieRepository) : ViewModel() { +@HiltViewModel +class MeViewModel @Inject constructor(private val repo: FakeRoomieRepository) : ViewModel() { val state: StateFlow = repo.state.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), repo.state.value) fun renameHouse(name: String) = repo.renameHouse(name) fun signOut() = repo.signOut() @@ -75,7 +78,7 @@ class MeViewModel(private val repo: FakeRoomieRepository = FakeRoomieRepository) } @Composable -fun MeScreen(onChangePic: () -> Unit, onSignedOut: () -> Unit, onLeftHouse: () -> Unit, vm: MeViewModel = viewModel()) { +fun MeScreen(onChangePic: () -> Unit, onSignedOut: () -> Unit, onLeftHouse: () -> Unit, vm: MeViewModel = hiltViewModel()) { val state by vm.state.collectAsStateWithLifecycle() val session = state.session ?: return val house = state.house ?: return diff --git a/app/src/main/java/com/example/roomie/ui/shopping/ShoppingScreen.kt b/app/src/main/java/com/example/roomie/ui/shopping/ShoppingScreen.kt index 1bf186a..d641354 100644 --- a/app/src/main/java/com/example/roomie/ui/shopping/ShoppingScreen.kt +++ b/app/src/main/java/com/example/roomie/ui/shopping/ShoppingScreen.kt @@ -61,7 +61,6 @@ import androidx.compose.ui.unit.sp import androidx.lifecycle.ViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.viewModelScope -import androidx.lifecycle.viewmodel.compose.viewModel import com.example.roomie.R import com.example.roomie.data.FakeRoomieRepository import com.example.roomie.data.RoomieState @@ -100,8 +99,12 @@ import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.stateIn import java.time.Duration import java.time.LocalDateTime +import dagger.hilt.android.lifecycle.HiltViewModel +import javax.inject.Inject +import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel -class ShoppingViewModel(private val repo: FakeRoomieRepository = FakeRoomieRepository) : ViewModel() { +@HiltViewModel +class ShoppingViewModel @Inject constructor(private val repo: FakeRoomieRepository) : ViewModel() { val state: StateFlow = repo.state.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), repo.state.value) fun now(): LocalDateTime = repo.now() fun add(name: String) = repo.addItem(name) @@ -114,7 +117,7 @@ class ShoppingViewModel(private val repo: FakeRoomieRepository = FakeRoomieRepos } @Composable -fun ShoppingScreen(onOpenSettings: () -> Unit, vm: ShoppingViewModel = viewModel()) { +fun ShoppingScreen(onOpenSettings: () -> Unit, vm: ShoppingViewModel = hiltViewModel()) { val state by vm.state.collectAsStateWithLifecycle() val house = state.house ?: return val me = state.session?.userId diff --git a/app/src/main/res/xml/network_security_config.xml b/app/src/main/res/xml/network_security_config.xml new file mode 100644 index 0000000..0cfcd8c --- /dev/null +++ b/app/src/main/res/xml/network_security_config.xml @@ -0,0 +1,8 @@ + + + + + 10.0.2.2 + localhost + + diff --git a/app/src/test/java/com/example/roomie/data/api/RoomieApiTest.kt b/app/src/test/java/com/example/roomie/data/api/RoomieApiTest.kt new file mode 100644 index 0000000..87b2181 --- /dev/null +++ b/app/src/test/java/com/example/roomie/data/api/RoomieApiTest.kt @@ -0,0 +1,134 @@ +package com.example.roomie.data.api + +import kotlinx.coroutines.runBlocking +import okhttp3.mockwebserver.MockResponse +import okhttp3.mockwebserver.MockWebServer +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import java.time.Instant +import java.time.LocalDate + +class RoomieApiTest { + + private val server = MockWebServer() + private var refreshes = 0 + private val tokens = TokenProvider { forceRefresh -> + if (forceRefresh) "fresh-${++refreshes}" else "dev:mnh49" + } + private lateinit var choreApi: ChoreApiService + private lateinit var houseApi: HouseApiService + private lateinit var shoppingApi: ShoppingApiService + + @Before + fun setUp() { + server.start() + val retrofit = roomieRetrofit(server.url("/").toString(), tokens, logBodies = false) + choreApi = retrofit.create(ChoreApiService::class.java) + houseApi = retrofit.create(HouseApiService::class.java) + shoppingApi = retrofit.create(ShoppingApiService::class.java) + } + + @After + fun tearDown() { + server.shutdown() + } + + @Test + fun sendsTokenAndParsesDatesAndEnums() = runBlocking { + server.enqueue(json(200, """ + {"assignments":[{"id":7,"chore":{"id":1,"title":"Trash","frequency":"EVERY_OTHER_DAY"}, + "dueOn":"2026-10-28","status":"DUE_TODAY", + "assignee":{"id":3,"netid":"mnh49","name":"Mihili","avatarUrl":null}, + "completedAt":"2026-10-28T14:05:00.000Z","completedBy":null,"canSwap":false}]} + """)) + + val today = LocalDate.of(2026, 10, 28) + val turn = apiCall { + choreApi.getAssignments(1, today, today, assignee = "me", includeOverdue = true) + }.dataOrNull()!!.assignments.single() + + val request = server.takeRequest() + assertEquals("Bearer dev:mnh49", request.getHeader("Authorization")) + assertEquals( + "/houses/1/chore-assignments?from=2026-10-28&to=2026-10-28&assignee=me&includeOverdue=true", + request.path, + ) + assertEquals(today, turn.dueOn) + assertEquals(TurnStatus.DUE_TODAY, turn.status) + assertEquals(ChoreFrequency.EVERY_OTHER_DAY, turn.chore.frequency) + assertEquals(Instant.parse("2026-10-28T14:05:00Z"), turn.completedAt) + assertNull(turn.completedBy) + } + + @Test + fun retriesOnceWithRefreshedTokenAfter401() = runBlocking { + server.enqueue(json(401, """{"status":"fail","statusCode":401,"message":"Expired","errorCode":"UNAUTHORIZED"}""")) + server.enqueue(MockResponse().setResponseCode(204)) + + val result = apiCall { houseApi.leaveHouse(1) } + + assertEquals(RoomieApiResponse.Success(Unit), result) + assertEquals("Bearer dev:mnh49", server.takeRequest().getHeader("Authorization")) + assertEquals("Bearer fresh-1", server.takeRequest().getHeader("Authorization")) + } + + @Test + fun givesUpAfterSecond401() = runBlocking { + repeat(2) { server.enqueue(json(401, """{"errorCode":"UNAUTHORIZED","message":"Bad token"}""")) } + + val error = (apiCall { houseApi.leaveHouse(1) } as RoomieApiResponse.Error).error + + assertEquals(ApiErrorCode.UNAUTHORIZED, error.code) + assertEquals(2, server.requestCount) + } + + @Test + fun parsesValidationErrors() = runBlocking { + server.enqueue(json(400, """ + {"status":"fail","statusCode":400,"message":"Request validation failed", + "errorCode":"VALIDATION_ERROR","data":{"body.name":"Too small"}} + """)) + + val error = (apiCall { shoppingApi.addItem(1, AddShoppingItemBody("")) } as RoomieApiResponse.Error).error + + assertEquals(ApiErrorCode.VALIDATION_ERROR, error.code) + assertEquals(400, error.statusCode) + assertEquals("Request validation failed", error.message) + assertEquals(mapOf("body.name" to "Too small"), error.fieldErrors) + } + + @Test + fun fallsBackToStatusWhenBodyIsNotJson() = runBlocking { + server.enqueue(MockResponse().setResponseCode(409).setBody("Conflict")) + + val error = (apiCall { houseApi.joinHouse(JoinHouseBody("LOFT-4827")) } as RoomieApiResponse.Error).error + + assertEquals(ApiErrorCode.CONFLICT, error.code) + } + + @Test + fun leavesUnsetFieldsOutOfRequestBodies() = runBlocking { + server.enqueue(json(200, """{"item":null}""")) + + apiCall { shoppingApi.updateItem(1, 2, UpdateShoppingItemBody(priceCents = 429)) } + + assertEquals("""{"priceCents":429}""", server.takeRequest().body.readUtf8()) + } + + @Test + fun reportsNetworkFailures() = runBlocking { + server.shutdown() + + val error = (apiCall { houseApi.getHouse(1) } as RoomieApiResponse.Error).error + + assertEquals(ApiErrorCode.NETWORK, error.code) + assertTrue(error.statusCode == null) + } + + private fun json(code: Int, body: String) = + MockResponse().setResponseCode(code).setHeader("Content-Type", "application/json").setBody(body.trimIndent()) +} diff --git a/build.gradle.kts b/build.gradle.kts index 18318be..d58b870 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -2,4 +2,6 @@ plugins { alias(libs.plugins.android.application) apply false alias(libs.plugins.kotlin.compose) apply false + alias(libs.plugins.hilt) apply false + alias(libs.plugins.ksp) apply false } \ No newline at end of file diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index f8555d5..e99f073 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -10,6 +10,11 @@ kotlin = "2.2.10" composeBom = "2026.02.01" navigationCompose = "2.9.5" desugarJdkLibs = "2.1.5" +retrofit = "2.11.0" +okhttp = "4.12.0" +hilt = "2.60.1" +hiltAndroidx = "1.3.0" +ksp = "2.3.13" [libraries] androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" } @@ -30,8 +35,18 @@ androidx-compose-ui-tooling-preview = { group = "androidx.compose.ui", name = "u androidx-compose-ui-test-manifest = { group = "androidx.compose.ui", name = "ui-test-manifest" } androidx-compose-ui-test-junit4 = { group = "androidx.compose.ui", name = "ui-test-junit4" } androidx-compose-material3 = { group = "androidx.compose.material3", name = "material3" } +retrofit = { group = "com.squareup.retrofit2", name = "retrofit", version.ref = "retrofit" } +retrofit-converter-gson = { group = "com.squareup.retrofit2", name = "converter-gson", version.ref = "retrofit" } +okhttp = { group = "com.squareup.okhttp3", name = "okhttp", version.ref = "okhttp" } +okhttp-logging-interceptor = { group = "com.squareup.okhttp3", name = "logging-interceptor", version.ref = "okhttp" } +okhttp-mockwebserver = { group = "com.squareup.okhttp3", name = "mockwebserver", version.ref = "okhttp" } +hilt-android = { group = "com.google.dagger", name = "hilt-android", version.ref = "hilt" } +hilt-android-compiler = { group = "com.google.dagger", name = "hilt-android-compiler", version.ref = "hilt" } +androidx-hilt-lifecycle-viewmodel-compose = { group = "androidx.hilt", name = "hilt-lifecycle-viewmodel-compose", version.ref = "hiltAndroidx" } [plugins] android-application = { id = "com.android.application", version.ref = "agp" } kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" } +hilt = { id = "com.google.dagger.hilt.android", version.ref = "hilt" } +ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" }