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..c1fb3e3 --- /dev/null +++ b/app/src/main/java/com/example/roomie/data/ShoppingRepository.kt @@ -0,0 +1,58 @@ +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.ResponseFlow +import com.example.roomie.data.api.repositoryScope +import kotlinx.coroutines.flow.StateFlow +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 = ResponseFlow(scope) + + /** Needed and recently bought items. Refreshed after every change below succeeds. */ + val shoppingList: StateFlow> = _shoppingList.state + + /** Pipelines the response into [shoppingList]. */ + fun fetchShoppingList(houseId: Int, refresh: Boolean = false) { + _shoppingList.fetch(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 index 16e0211..d0fc1c5 100644 --- a/app/src/main/java/com/example/roomie/data/api/ApiModels.kt +++ b/app/src/main/java/com/example/roomie/data/api/ApiModels.kt @@ -17,6 +17,10 @@ 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 } + /** The public view of a person: members, rotation, assignee, claimedBy, … */ data class UserDto( val id: Int, @@ -110,3 +114,20 @@ data class TurnDto( ) 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, +) 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 index 543d259..a15e26c 100644 --- a/app/src/main/java/com/example/roomie/data/api/RetrofitInstance.kt +++ b/app/src/main/java/com/example/roomie/data/api/RetrofitInstance.kt @@ -29,6 +29,7 @@ class RetrofitInstance internal constructor(retrofit: Retrofit) { 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) } } /** Builds the client. Separate from [RetrofitInstance] so tests can point it at a fake server. */ 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/test/java/com/example/roomie/data/api/RoomieApiTest.kt b/app/src/test/java/com/example/roomie/data/api/RoomieApiTest.kt index 1497555..a1c1dc9 100644 --- a/app/src/test/java/com/example/roomie/data/api/RoomieApiTest.kt +++ b/app/src/test/java/com/example/roomie/data/api/RoomieApiTest.kt @@ -22,6 +22,7 @@ class RoomieApiTest { } private lateinit var choreApi: ChoreApiService private lateinit var houseApi: HouseApiService + private lateinit var shoppingApi: ShoppingApiService @Before fun setUp() { @@ -29,6 +30,7 @@ class RoomieApiTest { 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 @@ -126,6 +128,21 @@ class RoomieApiTest { assertEquals(1, 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")) @@ -135,6 +152,15 @@ class RoomieApiTest { 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()