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
23 changes: 17 additions & 6 deletions app/src/main/java/com/example/roomie/data/AuthRepository.kt
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import com.example.roomie.data.api.UpdateMeBody
import com.example.roomie.data.api.apiCall
import com.example.roomie.data.api.ResponseFlow
import com.example.roomie.data.api.repositoryScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.StateFlow
import javax.inject.Inject
import javax.inject.Singleton
Expand All @@ -32,14 +33,24 @@ class AuthRepository @Inject constructor(
return login()
}

/** Call right after sign-in, once the [com.example.roomie.data.api.TokenProvider] has a token. */
suspend fun login(): RoomieApiResponse<LoginResponse> = apiCall { retrofitInstance.userApi.login() }

/** Pipelines the response into [me]. */
fun fetchMe(refresh: Boolean = false) {
_me.fetch(refresh) { retrofitInstance.userApi.getMe() }
/**
* Call right after sign-in, once the [com.example.roomie.data.api.TokenProvider] has a token.
* Also fills [me], since login returns the same session as `GET /users/me`.
*/
suspend fun login(): RoomieApiResponse<LoginResponse> {
val session = devTokenProvider.session
return apiCall { retrofitInstance.userApi.login() }.also { result ->
result.ifSuccess {
if (devTokenProvider.session == session) {
_me.set(RoomieApiResponse.Success(MeResponse(it.user, it.house, it.pendingInvites)))
}
}
}
}

/** Pipelines the response into [me]. Join the returned job to wait for it. */
fun fetchMe(refresh: Boolean = false): Job = _me.fetch(refresh) { retrofitInstance.userApi.getMe() }

/** Updates [me] too, unless you signed in as someone else while the request was out. */
suspend fun updateMe(
name: String? = null,
Expand Down
41 changes: 39 additions & 2 deletions app/src/main/java/com/example/roomie/data/ChoreRepository.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ 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.KeyedResponseFlow
import com.example.roomie.data.api.CreateChoreBody
import com.example.roomie.data.api.RetrofitInstance
import com.example.roomie.data.api.RoomieApiResponse
Expand Down Expand Up @@ -39,6 +40,14 @@ class ChoreRepository @Inject constructor(private val retrofitInstance: Retrofit
/** Everyone's turns over the range last passed to [fetchTurns], plus overdue ones. */
val turns: StateFlow<RoomieApiResponse<List<TurnDto>>> = _turns.state

private val _weeks = KeyedResponseFlow<LocalDate, List<TurnDto>>(scope)

/**
* Everyone's turns for each week passed to [fetchWeek] (keyed by its Monday), plus turns left
* unfinished in the 30 days before it. Weeks stay cached so switching back is instant.
*/
val weeks: StateFlow<Map<LocalDate, RoomieApiResponse<List<TurnDto>>>> = _weeks.state

private val _stats = ResponseFlow<ChoreStatsResponse>(scope)

/** How many turns each member finished in the month last passed to [fetchStats]. */
Expand Down Expand Up @@ -68,6 +77,28 @@ class ChoreRepository @Inject constructor(private val retrofitInstance: Retrofit
}
}

/** Pipelines Monday [weekStart] to Sunday into [weeks]. */
fun fetchWeek(houseId: Int, weekStart: LocalDate, refresh: Boolean = false) {
_weeks.fetch(weekStart, refresh) {
api.getAssignments(houseId, weekStart, weekStart.plusDays(6), includeOverdue = true).assignments
}
}

/** Refetches every week in [weeks], e.g. after a rotation change reschedules turns. */
fun refreshWeeks(houseId: Int) {
_weeks.keys.forEach { fetchWeek(houseId, it, refresh = true) }
}

/** Forgets everything, e.g. on sign-out or after leaving the house. */
fun clear() {
_chores.set(RoomieApiResponse.Pending)
_myTurnsToday.set(RoomieApiResponse.Pending)
_turns.set(RoomieApiResponse.Pending)
_stats.set(RoomieApiResponse.Pending)
_weeks.clear()
myTurnsQuery = null
}

/** 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) }
Expand Down Expand Up @@ -105,9 +136,14 @@ class ChoreRepository @Inject constructor(private val retrofitInstance: Retrofit
}
}

/** A chore change can rewrite its upcoming turns, so refetch the chores. Turn lists refresh on their next fetch. */
/** A chore change can rewrite its upcoming turns, so refetch the chores and the cached weeks. */
private suspend fun <T> changingChores(houseId: Int, call: suspend () -> T): RoomieApiResponse<T> =
apiCall(call).also { it.ifSuccess { fetchChores(houseId, refresh = true) } }
apiCall(call).also {
it.ifSuccess {
fetchChores(houseId, refresh = true)
refreshWeeks(houseId)
}
}

/** Patches the cached lists, then refetches [myTurnsToday] if it's for the same house. */
private fun changedTurns(houseId: Int, changed: List<TurnDto>) {
Expand All @@ -125,6 +161,7 @@ class ChoreRepository @Inject constructor(private val retrofitInstance: Retrofit
private fun replaceTurns(changed: List<TurnDto>) {
val byId = changed.associateBy { it.id }
_turns.update { response -> response.map { turns -> turns.map { byId[it.id] ?: it } } }
_weeks.updateAll { response -> response.map { turns -> turns.map { byId[it.id] ?: it } } }
val day = myTurnsQuery?.second
_myTurnsToday.update { response ->
response.map { turns ->
Expand Down
25 changes: 23 additions & 2 deletions app/src/main/java/com/example/roomie/data/ChoreRules.kt
Original file line number Diff line number Diff line change
Expand Up @@ -36,14 +36,19 @@ object ChoreRules {
fun choresInWeek(state: RoomieState, weekStart: LocalDate, today: LocalDate): List<Chore> {
val days = weekDays(weekStart)
val oneOffs = state.chores.filter { it.dueDate in days.first()..days.last() }
val weekly = state.rotations.mapNotNull { rotationChore(state, it, weekStart) }
val weekly = if (state.capabilities.turnsFromServer) emptyList()
else state.rotations.mapNotNull { rotationChore(state, it, weekStart) }
val carried = if (weekStart == weekStart(today)) overdue(state, weekStart) else emptyList()
return (carried + oneOffs + weekly).sortedWith(compareBy<Chore> { it.done }.thenBy { it.dueDate })
}

/** Undone one-offs from before [weekStart], plus last week's rotation turns nobody finished. */
/**
* Undone one-offs from before [weekStart], plus last week's rotation turns nobody finished.
* With [Capabilities.turnsFromServer], every turn is already in [RoomieState.chores].
*/
private fun overdue(state: RoomieState, weekStart: LocalDate): List<Chore> {
val oneOffs = state.chores.filter { !it.done && it.dueDate.isBefore(weekStart) }
if (state.capabilities.turnsFromServer) return oneOffs
val lastWeek = weekStart.minusWeeks(1)
val weekly = state.rotations.mapNotNull { rotationChore(state, it, lastWeek) }.filterNot { it.done }
return oneOffs + weekly
Expand All @@ -64,6 +69,22 @@ object ChoreRules {
return week to rotation.assigneesFor(week)
}

/** Who has [rotation] in each of the [count] weeks from [from], for the Rotation Preview card. */
fun previewWeeks(rotation: Rotation, from: LocalDate, count: Int = 3): List<Pair<LocalDate, List<String>>> =
(0L until count).map { from.plusWeeks(it) }.map { it to rotation.assigneesFor(it) }

/**
* [selected] with [id] added ([on]) or removed. The result keeps [houseOrder], so a rotation goes
* round the house the same way every time whatever order people were ticked in.
*/
fun toggleMember(houseOrder: List<String>, selected: List<String>, id: String, on: Boolean): List<String> {
val next = if (on) selected + id else selected - id
return houseOrder.filter { it in next }
}

/** People per week can't exceed the people in the rotation, and is at least 1. */
fun clampPerWeek(perWeek: Int, people: Int): Int = perWeek.coerceAtMost(people.coerceAtLeast(1))

/**
* The rotation as it would be with a new plan from [fromWeek]. The new member order starts with
* whoever was due next, so an edit doesn't send the chore back to the first person.
Expand Down
3 changes: 3 additions & 0 deletions app/src/main/java/com/example/roomie/data/HouseRepository.kt
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,9 @@ class HouseRepository @Inject constructor(private val retrofitInstance: Retrofit
suspend fun removeMember(houseId: Int, userId: Int): RoomieApiResponse<Unit> =
apiCall { api.removeMember(houseId, userId) }.also { it.ifSuccess { fetchHouse(houseId, refresh = true) } }

/** Forgets the house, e.g. on sign-out. */
fun clear() = _house.set(RoomieApiResponse.Pending)

private suspend fun updatingHouse(call: suspend () -> HouseDto): RoomieApiResponse<HouseDto> =
apiCall(call).also { result -> result.ifSuccess { _house.set(RoomieApiResponse.Success(it)) } }
}
37 changes: 37 additions & 0 deletions app/src/main/java/com/example/roomie/data/Models.kt
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,40 @@ data class Session(
val hasHouse: Boolean,
)

/**
* What the data source behind [RoomieState] can do. The in-memory fake does everything the design
* describes; the real backend doesn't support a few things yet, so screens hide those controls.
*/
data class Capabilities(
/** "Assign Once" chores. The backend only has repeating chores. */
val oneOffChores: Boolean = true,
/** The backend gives each turn to one person. */
val maxPeoplePerWeek: Int = ChoreRules.MAX_PEOPLE_PER_WEEK,
/** Picking the week a rotation edit starts from. The backend applies edits from the next turn. */
val rotationStartWeek: Boolean = true,
/** A free-text note on a shopping item. */
val itemNotes: Boolean = true,
/** "Couldn't find it" on a shopping item. */
val couldntFind: Boolean = true,
/**
* True when the server sends every turn, rotation weeks included, in [RoomieState.chores].
* False when [ChoreRules] works rotation weeks out from [RoomieState.rotations] (the fake).
*/
val turnsFromServer: Boolean = false,
) {
companion object {
/** The Roomie backend as of its `mvp-features` branch. */
val Backend = Capabilities(
oneOffChores = false,
maxPeoplePerWeek = 1,
rotationStartWeek = false,
itemNotes = false,
couldntFind = false,
turnsFromServer = true,
)
}
}

data class RoomieState(
val session: Session? = null,
val house: House? = null,
Expand All @@ -130,6 +164,9 @@ data class RoomieState(
/** Completion date of each rotation week, keyed by [ChoreRules.rotationChoreId]. */
val rotationCompletions: Map<String, LocalDate> = emptyMap(),
val shopping: List<ShoppingItem> = emptyList(),
val capabilities: Capabilities = Capabilities(),
/** True while a saved sign-in is being checked on launch, before the first screen is picked. */
val restoring: Boolean = false,
) {
fun member(id: String?): Roommate? = house?.members?.firstOrNull { it.id == id }
}
46 changes: 17 additions & 29 deletions app/src/main/java/com/example/roomie/data/NoteRepository.kt
Original file line number Diff line number Diff line change
@@ -1,24 +1,19 @@
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.ResponseFlow
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.ResponseFlow
import com.example.roomie.data.api.repositoryScope
import com.example.roomie.data.api.updateNoteBody
import kotlinx.coroutines.flow.StateFlow
import java.time.Instant
import java.time.LocalDate
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) {

Expand All @@ -27,42 +22,35 @@ class NoteRepository @Inject constructor(private val retrofitInstance: RetrofitI

private val _noteBoard = ResponseFlow<NoteBoardResponse>(scope)

/** The first page of the board. Refreshed after every change below succeeds. */
/** Everything on the board. Refreshed after every change below succeeds. */
val noteBoard: StateFlow<RoomieApiResponse<NoteBoardResponse>> = _noteBoard.state

/** Pipelines the first page into [noteBoard]. */
/** Pipelines the board into [noteBoard]. */
fun fetchNoteBoard(houseId: Int, refresh: Boolean = false) {
_noteBoard.fetch(refresh) { api.getNotes(houseId, before = null) }
_noteBoard.fetch(refresh) { api.getNotes(houseId) }
}

/** Older notes. Pass the previous page's `nextCursor` as [before]. Doesn't touch [noteBoard]. */
suspend fun getOlderNotes(houseId: Int, before: Int): RoomieApiResponse<NoteBoardResponse> =
apiCall { api.getNotes(houseId, before) }
/** Forgets the board, e.g. on sign-out or after leaving the house. */
fun clear() = _noteBoard.set(RoomieApiResponse.Pending)

suspend fun createNote(
houseId: Int,
body: String,
color: NoteColorDto? = null,
pinnedUntil: Instant? = null,
): RoomieApiResponse<NoteDto> =
changing(houseId) { api.createNote(houseId, CreateNoteBody(body.trim(), color, pinnedUntil)).note }
/** The server picks the color. [dueOn] can't be in the past. */
suspend fun createNote(houseId: Int, body: String, dueOn: LocalDate? = null, pinned: Boolean = false): RoomieApiResponse<NoteDto> =
changing(houseId) { api.createNote(houseId, CreateNoteBody(body.trim(), dueOn = dueOn, pinned = pinned)).note }

suspend fun updateNote(houseId: Int, noteId: Int, body: String? = null, color: NoteColorDto? = null): RoomieApiResponse<NoteDto> =
changing(houseId) { api.updateNote(houseId, noteId, UpdateNoteBody(body?.trim(), color)).note }
/** Your own notes only. Sets both fields; a null [dueOn] clears the due date. */
suspend fun updateNote(houseId: Int, noteId: Int, body: String, dueOn: LocalDate?): RoomieApiResponse<NoteDto> =
changing(houseId) { api.updateNote(houseId, noteId, updateNoteBody(body.trim(), dueOn)).note }

suspend fun deleteNote(houseId: Int, noteId: Int): RoomieApiResponse<Unit> =
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<NoteDto> =
changing(houseId) { api.pinNote(houseId, noteId, PinNoteBody(until)).note }
suspend fun pinNote(houseId: Int, noteId: Int): RoomieApiResponse<NoteDto> =
changing(houseId) { api.pinNote(houseId, noteId).note }

suspend fun unpinNote(houseId: Int, noteId: Int): RoomieApiResponse<NoteDto> =
changing(houseId) { api.unpinNote(houseId, noteId).note }

suspend fun reportNote(houseId: Int, noteId: Int, reason: String? = null): RoomieApiResponse<Unit> =
apiCall { api.reportNote(houseId, noteId, ReportNoteBody(reason)) }

/** Pinning moves notes between sections, so refetch rather than patch. */
private suspend fun <T> changing(houseId: Int, call: suspend () -> T): RoomieApiResponse<T> =
apiCall(call).also { it.ifSuccess { fetchNoteBoard(houseId, refresh = true) } }
}
Loading