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
136 changes: 136 additions & 0 deletions app/src/main/java/com/example/roomie/data/ChoreRepository.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
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.TurnStatus
import com.example.roomie.data.api.UpdateChoreBody
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 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 = ResponseFlow<List<ChoreDto>>(scope)

/** Every chore in the house. */
val chores: StateFlow<RoomieApiResponse<List<ChoreDto>>> = _chores.state

private val _myTurnsToday = ResponseFlow<List<TurnDto>>(scope)

/** Your turns due today, plus any you've left overdue. What Home shows. */
val myTurnsToday: StateFlow<RoomieApiResponse<List<TurnDto>>> = _myTurnsToday.state

private val _turns = ResponseFlow<List<TurnDto>>(scope)

/** Everyone's turns over the range last passed to [fetchTurns], plus overdue ones. */
val turns: StateFlow<RoomieApiResponse<List<TurnDto>>> = _turns.state

private val _stats = ResponseFlow<ChoreStatsResponse>(scope)

/** How many turns each member finished in the month last passed to [fetchStats]. */
val stats: StateFlow<RoomieApiResponse<ChoreStatsResponse>> = _stats.state

/** Pipelines the response into [chores]. */
fun fetchChores(houseId: Int, refresh: Boolean = false) {
_chores.fetch(refresh) { api.getChores(houseId).chores }
}

/** The house and day [myTurnsToday] was last fetched for, so completing a turn can refetch it. */
@Volatile
private var myTurnsQuery: Pair<Int, LocalDate>? = null

/** Pipelines the response into [myTurnsToday]. */
fun fetchMyTurnsToday(houseId: Int, today: LocalDate, refresh: Boolean = false) {
myTurnsQuery = houseId to today
_myTurnsToday.fetch(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) {
_turns.fetch(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) {
_stats.fetch(refresh) { api.getChoreStats(houseId, month) }
}

suspend fun getChore(houseId: Int, choreId: Int): RoomieApiResponse<ChoreDto> =
apiCall { api.getChore(houseId, choreId).chore }

suspend fun createChore(houseId: Int, body: CreateChoreBody): RoomieApiResponse<ChoreDto> =
changingChores(houseId) { api.createChore(houseId, body).chore }

suspend fun updateChore(houseId: Int, choreId: Int, body: UpdateChoreBody): RoomieApiResponse<ChoreDto> =
changingChores(houseId) { api.updateChore(houseId, choreId, body).chore }

suspend fun deleteChore(houseId: Int, choreId: Int): RoomieApiResponse<Unit> =
changingChores(houseId) { api.deleteChore(houseId, choreId) }

/**
* A finished overdue turn leaves [myTurnsToday] right away (turns due today stay, shown done).
* [myTurnsToday] is then refetched in the background to pick up anything else that moved.
*/
suspend fun completeTurn(houseId: Int, turnId: Int): RoomieApiResponse<TurnDto> =
apiCall { api.completeAssignment(houseId, turnId).assignment }.also { it.ifSuccess { turn -> changedTurns(houseId, listOf(turn)) } }

/** Un-finishing an overdue turn puts it back on [myTurnsToday], which the refetch picks up. */
suspend fun uncompleteTurn(houseId: Int, turnId: Int): RoomieApiResponse<TurnDto> =
apiCall { api.uncompleteAssignment(houseId, turnId).assignment }.also { it.ifSuccess { turn -> changedTurns(houseId, 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<List<TurnDto>> =
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 <T> changingChores(houseId: Int, call: suspend () -> T): RoomieApiResponse<T> =
apiCall(call).also { it.ifSuccess { fetchChores(houseId, refresh = true) } }

/** Patches the cached lists, then refetches [myTurnsToday] if it's for the same house. */
private fun changedTurns(houseId: Int, changed: List<TurnDto>) {
replaceTurns(changed)
myTurnsQuery?.let { (queriedHouse, day) ->
if (queriedHouse == houseId) fetchMyTurnsToday(houseId, day, refresh = true)
}
}

/**
* Swaps the changed turns into the cached lists that already have them. [myTurnsToday] also
* drops turns that are done but were due before its day, as the server would.
* Each list is patched under its own lock, so concurrent mutations can't lose each other's changes.
*/
private fun replaceTurns(changed: List<TurnDto>) {
val byId = changed.associateBy { it.id }
_turns.update { response -> response.map { turns -> turns.map { byId[it.id] ?: it } } }
val day = myTurnsQuery?.second
_myTurnsToday.update { response ->
response.map { turns ->
turns.map { byId[it.id] ?: it }
.filterNot { day != null && it.status == TurnStatus.DONE && it.dueOn.isBefore(day) }
}
}
}
}
36 changes: 36 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 @@ -12,6 +12,11 @@ enum class MemberRole { OWNER, MEMBER }
/** The "I'm home / away" toggle. */
enum class Presence { HOME, AWAY }

enum class ChoreFrequency { DAILY, EVERY_OTHER_DAY, WEEKLY, BIWEEKLY, MONTHLY }

/** Computed by the server; not stored. */
enum class TurnStatus { DONE, OVERDUE, DUE_TODAY, UPCOMING }

/** The public view of a person: members, rotation, assignee, claimedBy, … */
data class UserDto(
val id: Int,
Expand Down Expand Up @@ -74,3 +79,34 @@ data class InviteDto(
)

data class InviteHouseDto(val id: Int, val name: String, val members: List<UserDto>)

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<UserDto>,
/** The next 3 turns. */
val comingUp: List<TurnDto>,
)

/** 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)
113 changes: 113 additions & 0 deletions app/src/main/java/com/example/roomie/data/api/ChoreApiService.kt
Original file line number Diff line number Diff line change
@@ -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<ChoreDto>)

data class ChoreResponse(val chore: ChoreDto)

data class AssignmentsResponse(val assignments: List<TurnDto>)

data class AssignmentResponse(val assignment: TurnDto)

data class ChoreStatsResponse(val month: String, val members: List<MemberChoreStatsDto>)

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<Int>,
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<Int>? = null,
val allowSwaps: Boolean? = null,
val reminderHour: Int? = null,
)

data class SwapBody(val withAssignmentId: Int)
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,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) }
}

/** Builds the client. Separate from [RetrofitInstance] so tests can point it at a fake server. */
Expand Down
33 changes: 33 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 @@ -6,9 +6,12 @@ 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 {

Expand All @@ -17,12 +20,14 @@ class RoomieApiTest {
private val tokens = TokenProvider { forceRefresh ->
if (forceRefresh) "fresh-${++refreshes}" else "dev:mnh49"
}
private lateinit var choreApi: ChoreApiService
private lateinit var houseApi: HouseApiService

@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)
}

Expand All @@ -31,6 +36,34 @@ class RoomieApiTest {
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,"presence":"AWAY"},
"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)
assertEquals(Presence.AWAY, turn.assignee.presence)
}

@Test
fun retriesOnceWithRefreshedTokenAfter401() = runBlocking {
server.enqueue(json(401, """{"status":"fail","statusCode":401,"message":"Expired","errorCode":"UNAUTHORIZED"}"""))
Expand Down