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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 58 additions & 0 deletions app/src/main/java/com/example/roomie/data/ShoppingRepository.kt
Original file line number Diff line number Diff line change
@@ -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<ShoppingListResponse>(scope)

/** Needed and recently bought items. Refreshed after every change below succeeds. */
val shoppingList: StateFlow<RoomieApiResponse<ShoppingListResponse>> = _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<ShoppingItemDto> =
changing(houseId) { api.addItem(houseId, AddShoppingItemBody(name.trim(), category)).item }

suspend fun updateItem(houseId: Int, itemId: Int, body: UpdateShoppingItemBody): RoomieApiResponse<ShoppingItemDto> =
changing(houseId) { api.updateItem(houseId, itemId, body).item }

suspend fun deleteItem(houseId: Int, itemId: Int): RoomieApiResponse<Unit> =
changing(houseId) { api.deleteItem(houseId, itemId) }

suspend fun claimItem(houseId: Int, itemId: Int): RoomieApiResponse<ShoppingItemDto> =
changing(houseId) { api.claimItem(houseId, itemId).item }

suspend fun unclaimItem(houseId: Int, itemId: Int): RoomieApiResponse<ShoppingItemDto> =
changing(houseId) { api.unclaimItem(houseId, itemId).item }

suspend fun buyItem(houseId: Int, itemId: Int, priceCents: Int? = null): RoomieApiResponse<ShoppingItemDto> =
changing(houseId) { api.buyItem(houseId, itemId, BuyItemBody(priceCents)).item }

suspend fun unbuyItem(houseId: Int, itemId: Int): RoomieApiResponse<ShoppingItemDto> =
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 <T> changing(houseId: Int, call: suspend () -> T): RoomieApiResponse<T> =
apiCall(call).also { it.ifSuccess { fetchShoppingList(houseId, refresh = true) } }
}
21 changes: 21 additions & 0 deletions app/src/main/java/com/example/roomie/data/api/ApiModels.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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,
)
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down
Original file line number Diff line number Diff line change
@@ -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<ShoppingItemDto>,
/** Bought in the last 14 days or not yet billed, newest first. */
val bought: List<ShoppingItemDto>,
val billable: BillableDto,
)

/** Items you bought and priced that aren't on a bill yet. */
data class BillableDto(val itemIds: List<Int>, 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)
26 changes: 26 additions & 0 deletions app/src/test/java/com/example/roomie/data/api/RoomieApiTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,15 @@ class RoomieApiTest {
}
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
Expand Down Expand Up @@ -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"))
Expand All @@ -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()
Expand Down