diff --git a/app/src/main/java/com/example/roomie/data/AuthRepository.kt b/app/src/main/java/com/example/roomie/data/AuthRepository.kt index 4f9bc00..33aa315 100644 --- a/app/src/main/java/com/example/roomie/data/AuthRepository.kt +++ b/app/src/main/java/com/example/roomie/data/AuthRepository.kt @@ -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 @@ -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 = 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 { + 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, diff --git a/app/src/main/java/com/example/roomie/data/ChoreRepository.kt b/app/src/main/java/com/example/roomie/data/ChoreRepository.kt index 3851557..6832a77 100644 --- a/app/src/main/java/com/example/roomie/data/ChoreRepository.kt +++ b/app/src/main/java/com/example/roomie/data/ChoreRepository.kt @@ -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 @@ -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>> = _turns.state + private val _weeks = KeyedResponseFlow>(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>>> = _weeks.state + private val _stats = ResponseFlow(scope) /** How many turns each member finished in the month last passed to [fetchStats]. */ @@ -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) } @@ -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 changingChores(houseId: Int, call: suspend () -> T): RoomieApiResponse = - 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) { @@ -125,6 +161,7 @@ class ChoreRepository @Inject constructor(private val retrofitInstance: Retrofit private fun replaceTurns(changed: List) { 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 -> diff --git a/app/src/main/java/com/example/roomie/data/ChoreRules.kt b/app/src/main/java/com/example/roomie/data/ChoreRules.kt index 536d250..2584a0a 100644 --- a/app/src/main/java/com/example/roomie/data/ChoreRules.kt +++ b/app/src/main/java/com/example/roomie/data/ChoreRules.kt @@ -36,14 +36,19 @@ object ChoreRules { fun choresInWeek(state: RoomieState, weekStart: LocalDate, today: LocalDate): List { 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 { 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 { 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 @@ -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>> = + (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, selected: List, id: String, on: Boolean): List { + 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. diff --git a/app/src/main/java/com/example/roomie/data/HouseRepository.kt b/app/src/main/java/com/example/roomie/data/HouseRepository.kt index 403ab53..80701f7 100644 --- a/app/src/main/java/com/example/roomie/data/HouseRepository.kt +++ b/app/src/main/java/com/example/roomie/data/HouseRepository.kt @@ -61,6 +61,9 @@ class HouseRepository @Inject constructor(private val retrofitInstance: Retrofit suspend fun removeMember(houseId: Int, userId: Int): RoomieApiResponse = 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 = apiCall(call).also { result -> result.ifSuccess { _house.set(RoomieApiResponse.Success(it)) } } } diff --git a/app/src/main/java/com/example/roomie/data/Models.kt b/app/src/main/java/com/example/roomie/data/Models.kt index 60573ca..f8d922b 100644 --- a/app/src/main/java/com/example/roomie/data/Models.kt +++ b/app/src/main/java/com/example/roomie/data/Models.kt @@ -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, @@ -130,6 +164,9 @@ data class RoomieState( /** Completion date of each rotation week, keyed by [ChoreRules.rotationChoreId]. */ val rotationCompletions: Map = emptyMap(), val shopping: List = 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 } } diff --git a/app/src/main/java/com/example/roomie/data/NoteRepository.kt b/app/src/main/java/com/example/roomie/data/NoteRepository.kt index 36cb57e..b8a4656 100644 --- a/app/src/main/java/com/example/roomie/data/NoteRepository.kt +++ b/app/src/main/java/com/example/roomie/data/NoteRepository.kt @@ -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) { @@ -27,42 +22,35 @@ class NoteRepository @Inject constructor(private val retrofitInstance: RetrofitI private val _noteBoard = ResponseFlow(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> = _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 = - 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 = - 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 = + 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 = - 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 = + changing(houseId) { api.updateNote(houseId, noteId, updateNoteBody(body.trim(), dueOn)).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 pinNote(houseId: Int, noteId: Int): RoomieApiResponse = + changing(houseId) { api.pinNote(houseId, noteId).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)) } - + /** Pinning moves notes between sections, so refetch rather than patch. */ 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/RemoteMapping.kt b/app/src/main/java/com/example/roomie/data/RemoteMapping.kt new file mode 100644 index 0000000..1684385 --- /dev/null +++ b/app/src/main/java/com/example/roomie/data/RemoteMapping.kt @@ -0,0 +1,180 @@ +package com.example.roomie.data + +import com.example.roomie.data.api.ChoreDto +import com.example.roomie.data.api.HouseDto +import com.example.roomie.data.api.MemberRole +import com.example.roomie.data.api.NoteColorDto +import com.example.roomie.data.api.NoteDto +import com.example.roomie.data.api.ShoppingItemDto +import com.example.roomie.data.api.TurnDto +import java.time.Instant +import java.time.LocalDate +import java.time.LocalDateTime +import java.time.ZoneId + +/** + * Turns the backend's DTOs into the app's models (data/Models.kt), so the screens built against + * [FakeRoomieRepository] work unchanged. Pure functions only; [RemoteRoomieRepository] does the I/O. + * + * IDs become strings. Turns get a `t` prefix ("t42") because a chore's ID and its turns' IDs come + * from different tables, and pending invites get `invite-` so they can't collide with user IDs. + */ +internal object RemoteMapping { + + const val TURN_PREFIX = "t" + const val INVITE_PREFIX = "invite-" + const val DRAFT_INVITE_PREFIX = "draft-" + + /** The backend's NetID rule (`houses.schema.ts`). Looser than the fake's. */ + private val NET_ID = Regex("^[a-z]{1,4}[0-9]{1,6}$") + + /** Shopping item names can be at most this long on the server. */ + private const val MAX_ITEM_NAME = 80 + + fun normalizeNetId(input: String): String = input.trim().lowercase().removeSuffix("@cornell.edu") + + fun isValidNetId(input: String): Boolean = NET_ID.matches(normalizeNetId(input)) + + /** "Leah Kim" → ("Leah", "Kim"); "Stef Rivera-Osorio" keeps the rest together as the last name. */ + fun splitName(name: String): Pair { + val parts = name.trim().split(Regex("\\s+"), limit = 2) + return parts[0] to parts.getOrElse(1) { "" } + } + + /** + * The backend has no house buddy, so roommates get one picked from their user ID: stable across + * launches and devices, and different for neighbours in the member list. Your own pick is + * remembered on this device and shown instead. + */ + fun buddyFor(userId: Int): Buddy = Buddy.entries[Math.floorMod(userId, Buddy.entries.size)] + + fun house(dto: HouseDto, myId: Int, myBuddy: Buddy): House = House( + name = dto.name, + inviteCode = dto.inviteCode, + members = dto.members.map { member -> + val (first, last) = splitName(member.name) + Roommate( + id = member.id.toString(), + netId = member.netid, + firstName = first, + lastName = last, + buddy = if (member.id == myId) myBuddy else buddyFor(member.id), + status = if (member.role == MemberRole.OWNER) MemberStatus.Owner else MemberStatus.Joined, + ) + } + dto.pendingInvites.map { invite -> + Roommate( + id = INVITE_PREFIX + invite.id, + netId = invite.netid, + firstName = invite.netid, + buddy = buddyFor(invite.netid.hashCode()), + status = MemberStatus.InviteSent, + ) + }, + // The backend has no "at the store" status yet. + atStoreId = null, + ) + + /** A house that only exists on this device until onboarding's last step creates it. */ + fun draftHouse(name: String, me: Roommate, invites: List): House = House( + name = name, + // The server makes the code when the house is created. + inviteCode = "", + members = listOf(me) + invites.map { netId -> + Roommate(DRAFT_INVITE_PREFIX + netId, netId, netId, buddy = buddyFor(netId.hashCode()), status = MemberStatus.InviteSent) + }, + ) + + fun noteColor(dto: NoteColorDto): NoteColor = when (dto) { + NoteColorDto.YELLOW -> NoteColor.Yellow + NoteColorDto.ORANGE -> NoteColor.Peach + NoteColorDto.BLUE -> NoteColor.Blue + NoteColorDto.GREEN -> NoteColor.Green + NoteColorDto.PINK -> NoteColor.Pink + NoteColorDto.PURPLE -> NoteColor.Purple + } + + /** + * Pinned notes on the server stay pinned until someone unpins them, so the app's 7-day pin + * becomes "pinned until [LocalDate.MAX]". The tack isn't stored either; it's picked from the ID + * so a note keeps its tack between refreshes. + */ + fun note(dto: NoteDto, zone: ZoneId): Note = Note( + id = dto.id.toString(), + text = dto.body, + authorId = dto.author.id.toString(), + createdAt = dto.createdAt.toLocal(zone), + dueDate = dto.dueOn, + pinnedUntil = if (dto.pinned) LocalDate.MAX else null, + color = noteColor(dto.color), + tack = Tack.entries[Math.floorMod(dto.id, Tack.entries.size)], + ) + + /** One turn of a server chore. Every turn belongs to a chore, so it always has a [Chore.rotationId]. */ + fun chore(turn: TurnDto, houseZone: ZoneId): Chore = Chore( + id = TURN_PREFIX + turn.id, + title = turn.chore.title, + assigneeIds = listOf(turn.assignee.id.toString()), + dueDate = turn.dueOn, + completedOn = turn.completedAt?.atZone(houseZone)?.toLocalDate(), + rotationId = turn.chore.id.toString(), + ) + + /** + * A server chore as the app's weekly [Rotation]: one person per turn, due on its next turn's + * weekday. The plan starts the week of the next turn, with the members reordered so whoever has + * that turn comes first; [Rotation.assigneesFor] then predicts the following weeks the same way + * the server assigns them. + */ + fun rotation(dto: ChoreDto): Rotation { + val next = dto.comingUp.firstOrNull() + val anchor = next?.dueOn ?: dto.startsOn + val ids = dto.rotation.map { it.id.toString() } + val start = ids.indexOf(next?.assignee?.id?.toString()).coerceAtLeast(0) + return Rotation( + id = dto.id.toString(), + title = dto.title, + dueDay = anchor.dayOfWeek, + plans = listOf(RotationPlan(ChoreRules.weekStart(anchor), ids.drop(start) + ids.take(start), peoplePerWeek = 1)), + ) + } + + fun item(dto: ShoppingItemDto, zone: ZoneId): ShoppingItem { + val (name, quantity) = decodeItemName(dto.name) + return ShoppingItem( + id = dto.id.toString(), + name = name, + quantity = quantity, + addedById = dto.addedBy.id.toString(), + addedAt = dto.createdAt.toLocal(zone), + boughtById = dto.boughtBy?.id?.toString(), + boughtAt = dto.boughtAt?.toLocal(zone), + ) + } + + /** + * The backend has no quantity, so "Eggs" ×2 is stored as the name `Eggs ×2`. Roommates on other + * clients see the same readable name. Quantities of 1 are left off. + */ + fun encodeItemName(name: String, quantity: Int): String { + val suffix = if (quantity > 1) " ×$quantity" else "" + return name.trim().take(MAX_ITEM_NAME - suffix.length).trimEnd() + suffix + } + + fun decodeItemName(raw: String): Pair { + val match = Regex("^(.*\\S)\\s+×(\\d{1,4})$").find(raw.trim()) ?: return raw.trim() to 1 + val quantity = match.groupValues[2].toInt() + return if (quantity >= 2) match.groupValues[1] to quantity else raw.trim() to 1 + } + + /** + * The first day a new weekly chore can start: [dueDay] in [startWeek], or the same weekday a + * week later if that's already past (the server rejects start dates before [today]). + */ + fun firstTurn(startWeek: LocalDate, dueDay: java.time.DayOfWeek, today: LocalDate): LocalDate { + var date = ChoreRules.weekStart(startWeek).plusDays(dueDay.value - 1L) + while (date.isBefore(today)) date = date.plusWeeks(1) + return date + } + + private fun Instant.toLocal(zone: ZoneId): LocalDateTime = LocalDateTime.ofInstant(this, zone) +} diff --git a/app/src/main/java/com/example/roomie/data/RemoteRoomieRepository.kt b/app/src/main/java/com/example/roomie/data/RemoteRoomieRepository.kt new file mode 100644 index 0000000..162df87 --- /dev/null +++ b/app/src/main/java/com/example/roomie/data/RemoteRoomieRepository.kt @@ -0,0 +1,488 @@ +package com.example.roomie.data + +import android.content.Context +import com.example.roomie.data.api.ApiError +import com.example.roomie.data.api.ApiErrorCode +import com.example.roomie.data.api.ChoreDto +import com.example.roomie.data.api.ChoreFrequency +import com.example.roomie.data.api.CreateChoreBody +import com.example.roomie.data.api.CreateHouseBody +import com.example.roomie.data.api.HouseDto +import com.example.roomie.data.api.MeResponse +import com.example.roomie.data.api.NoteBoardResponse +import com.example.roomie.data.api.RoomieApiResponse +import com.example.roomie.data.api.ShoppingListResponse +import com.example.roomie.data.api.TurnDto +import com.example.roomie.data.api.UpdateChoreBody +import com.example.roomie.data.api.UpdateHouseBody +import com.example.roomie.data.api.UpdateShoppingItemBody +import dagger.hilt.android.qualifiers.ApplicationContext +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.SharingStarted +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asSharedFlow +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.stateIn +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import java.time.DayOfWeek +import java.time.LocalDate +import java.time.LocalDateTime +import java.time.ZoneId +import javax.inject.Inject +import javax.inject.Singleton + +/** + * [RoomieRepository] backed by the Roomie backend. It combines the per-resource repositories + * ([AuthRepository], [HouseRepository], [ChoreRepository], [NoteRepository], [ShoppingRepository]) + * into one [RoomieState], using [RemoteMapping] to turn DTOs into the app's models. + * + * Sign-in uses the backend's dev tokens (`dev:`), so it works against a local backend or + * the mock server, not the deployed one. The NetID is remembered so the app stays signed in. + */ +@Singleton +class RemoteRoomieRepository @Inject constructor( + @ApplicationContext context: Context, + private val auth: AuthRepository, + private val houses: HouseRepository, + private val chores: ChoreRepository, + private val notes: NoteRepository, + private val shopping: ShoppingRepository, +) : RoomieRepository { + + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + private val prefs = context.getSharedPreferences("roomie_session", Context.MODE_PRIVATE) + + private val _messages = MutableSharedFlow(extraBufferCapacity = 16) + override val messages: Flow = _messages.asSharedFlow() + + /** Onboarding's "Start a House" until its last step creates the house on the server. */ + private data class Draft(val name: String = "", val invites: List = emptyList()) + + /** What only lives on this device. [buddyVersion] changes when a saved buddy does. */ + private data class Local(val draft: Draft? = null, val restoring: Boolean = false, val buddyVersion: Int = 0) + + private val local = MutableStateFlow(Local(restoring = savedNetId != null)) + + private class Data( + val chores: RoomieApiResponse>, + val weeks: Map>>, + val notes: RoomieApiResponse, + val shopping: RoomieApiResponse, + ) + + override val state: StateFlow = combine( + combine(auth.me, houses.house, local, ::Triple), + combine(chores.chores, chores.weeks, notes.noteBoard, shopping.shoppingList, ::Data), + ) { (me, house, device), data -> build(me, house, device, data) } + .stateIn(scope, SharingStarted.Eagerly, RoomieState(capabilities = Capabilities.Backend, restoring = local.value.restoring)) + + private val houseId: Int? get() = auth.me.value.dataOrNull()?.house?.id + + /** "Today" is the house's, since that's what the server uses for due and overdue. */ + private val houseZone: ZoneId + get() = houses.house.value.dataOrNull()?.takeIf { it.id == houseId }?.timezone + ?.let { runCatching { ZoneId.of(it) }.getOrNull() } ?: ZoneId.systemDefault() + + init { + // Load (or forget) the house's data whenever the house you're in changes. + scope.launch { + auth.me.map { it.dataOrNull()?.house?.id }.distinctUntilChanged().collect { id -> + houses.clear() + chores.clear() + notes.clear() + shopping.clear() + if (id != null) loadHouse(id, refresh = false) + } + } + savedNetId?.let { netId -> + scope.launch { + when (val result = auth.devLogin(netId)) { + is RoomieApiResponse.Error -> { + if (result.error.code == ApiErrorCode.UNAUTHORIZED) forgetSignIn() + report(result.error, "Couldn't restore your sign-in.") + } + else -> Unit + } + local.update { it.copy(restoring = false) } + } + } + } + + override fun today(): LocalDate = LocalDate.now(houseZone) + + override fun now(): LocalDateTime = LocalDateTime.now() + + override fun refresh() { + if (auth.me.value !is RoomieApiResponse.Success) return + auth.fetchMe(refresh = true) + houseId?.let { loadHouse(it, refresh = true) } + } + + // region Session and onboarding + + override fun isValidNetId(netId: String): Boolean = RemoteMapping.isValidNetId(netId) + + /** The backend's dev sign-in has no password, so [password] is only checked for being filled in. */ + override suspend fun signIn(netIdInput: String, password: String): RoomieRepository.SignInResult { + val netId = RemoteMapping.normalizeNetId(netIdInput) + return when (val result = auth.devLogin(netId)) { + is RoomieApiResponse.Success -> { + prefs.edit().putString(KEY_NET_ID, netId).apply() + local.update { it.copy(draft = null) } + RoomieRepository.SignInResult.Success(hasHouse = result.data.house != null) + } + is RoomieApiResponse.Error -> { + auth.signOut() + RoomieRepository.SignInResult.Invalid( + when (result.error.code) { + ApiErrorCode.NETWORK -> NETWORK_MESSAGE + ApiErrorCode.UNAUTHORIZED -> "The server turned down dev sign-in. Is the app pointed at a local backend?" + else -> result.error.message + }, + ) + } + RoomieApiResponse.Pending -> RoomieRepository.SignInResult.Invalid("Try again.") + } + } + + override fun signOut() { + forgetSignIn() + auth.signOut() + local.update { it.copy(draft = null) } + } + + override fun setBuddy(buddy: Buddy) { + val netId = savedNetId ?: return + prefs.edit().putString(KEY_BUDDY_PREFIX + netId, buddy.name).apply() + local.update { it.copy(buddyVersion = it.buddyVersion + 1) } + } + + override fun startHouse() { + if (houseId != null) return + local.update { if (it.draft == null) it.copy(draft = Draft()) else it } + } + + override suspend fun joinHouse(code: String): String? = + when (val result = houses.joinHouse(code)) { + is RoomieApiResponse.Success -> { + local.update { it.copy(draft = null) } + auth.fetchMe(refresh = true).join() + null + } + is RoomieApiResponse.Error -> when (result.error.code) { + ApiErrorCode.NOT_FOUND -> "We couldn't find a house with that code." + ApiErrorCode.CONFLICT -> "You're already in a house. Leave it first." + ApiErrorCode.VALIDATION_ERROR -> "That doesn't look like an invite code." + else -> messageFor(result.error, "Couldn't join the house.") + } + RoomieApiResponse.Pending -> null + } + + override suspend fun inviteRoommate(netIdInput: String): String? { + val netId = RemoteMapping.normalizeNetId(netIdInput) + if (!RemoteMapping.isValidNetId(netId)) return "Enter a Cornell NetID, like ab123." + val house = state.value.house ?: return "Start a house first." + if (house.members.any { it.netId == netId }) return "$netId is already in the house." + val id = houseId + if (id == null) { + local.update { it.copy(draft = (it.draft ?: Draft()).let { d -> d.copy(invites = d.invites + netId) }) } + return null + } + return when (val result = houses.invite(id, listOf(netId))) { + is RoomieApiResponse.Error -> messageFor(result.error, "Couldn't send the invite.") + else -> null + } + } + + override fun removeRoommate(id: String) { + when { + id.startsWith(RemoteMapping.DRAFT_INVITE_PREFIX) -> { + val netId = id.removePrefix(RemoteMapping.DRAFT_INVITE_PREFIX) + local.update { it.copy(draft = it.draft?.let { d -> d.copy(invites = d.invites - netId) }) } + } + id.startsWith(RemoteMapping.INVITE_PREFIX) -> { + val inviteId = id.removePrefix(RemoteMapping.INVITE_PREFIX).toIntOrNull() ?: return + inHouse("Couldn't cancel the invite.") { houses.cancelInvite(it, inviteId) } + } + else -> { + val userId = id.toIntOrNull() ?: return + inHouse("Couldn't remove them.") { houses.removeMember(it, userId) } + } + } + } + + /** Onboarding calls this on every keystroke, so a draft is only renamed locally. */ + override fun renameHouse(name: String) { + val trimmed = name.trim() + if (houseId == null) { + local.update { it.copy(draft = it.draft?.copy(name = trimmed)) } + return + } + if (trimmed.isEmpty() || trimmed == state.value.house?.name) return + inHouse("Couldn't rename the house.") { houses.updateHouse(it, UpdateHouseBody(name = trimmed)) } + } + + override suspend fun finishOnboarding(name: String): String? { + val draft = local.value.draft ?: return null + val body = CreateHouseBody(name = name.trim(), inviteNetids = draft.invites.ifEmpty { null }) + return when (val result = houses.createHouse(body)) { + is RoomieApiResponse.Success -> { + local.update { it.copy(draft = null) } + auth.fetchMe(refresh = true).join() + null + } + is RoomieApiResponse.Error -> when (result.error.code) { + ApiErrorCode.CONFLICT -> "You're already in a house." + else -> messageFor(result.error, "Couldn't create the house.") + } + RoomieApiResponse.Pending -> null + } + } + + override fun leaveHouse() { + inHouse("Couldn't leave the house.") { id -> + houses.leaveHouse(id).also { if (it is RoomieApiResponse.Success) auth.fetchMe(refresh = true) } + } + } + + // endregion + + // region Notes + + override fun addNote(text: String, dueDate: LocalDate?, pin: Boolean) { + val trimmed = text.trim().take(NoteRules.MAX_LENGTH) + if (trimmed.isEmpty()) return + val canPin = pin && NoteRules.pinsInUse(state.value.notes, today()) < NoteRules.MAX_PINS + inHouse("Couldn't post the note.") { notes.createNote(it, trimmed, dueDate, canPin) } + } + + override fun updateNote(id: String, text: String, dueDate: LocalDate?) { + val noteId = id.toIntOrNull() ?: return + if (text.isBlank()) return + inHouse("Couldn't save the note.") { notes.updateNote(it, noteId, text.take(NoteRules.MAX_LENGTH), dueDate) } + } + + override fun deleteNote(id: String) { + val noteId = id.toIntOrNull() ?: return + inHouse("Couldn't delete the note.") { notes.deleteNote(it, noteId) } + } + + override fun togglePin(id: String) { + val noteId = id.toIntOrNull() ?: return + val today = today() + val note = state.value.notes.firstOrNull { it.id == id } ?: return + when { + note.isPinned(today) -> inHouse("Couldn't unpin the note.") { notes.unpinNote(it, noteId) } + NoteRules.pinsInUse(state.value.notes, today) < NoteRules.MAX_PINS -> + inHouse("Couldn't pin the note.") { notes.pinNote(it, noteId) } + } + } + + // endregion + + // region Chores + + override fun showWeek(weekStart: LocalDate) { + val id = houseId ?: return + if (weekStart !in chores.weeks.value) chores.fetchWeek(id, weekStart) + } + + override fun addChore(title: String, assigneeIds: List, dueDate: LocalDate) { + _messages.tryEmit("One-time chores aren't available yet. Use Rotate Weekly.") + } + + override fun addRotation(title: String, dueDay: DayOfWeek, memberIds: List, peoplePerWeek: Int, startWeek: LocalDate) { + val rotation = memberIds.mapNotNull { it.toIntOrNull() } + if (title.isBlank() || rotation.isEmpty()) return + val body = CreateChoreBody( + title = title.trim(), + frequency = ChoreFrequency.WEEKLY, + startsOn = RemoteMapping.firstTurn(startWeek, dueDay, today()), + rotation = rotation, + ) + inHouse("Couldn't add the chore.") { chores.createChore(it, body) } + } + + override fun toggleChoreDone(id: String) { + val turnId = id.removePrefix(RemoteMapping.TURN_PREFIX).toIntOrNull() ?: return + val turn = chores.weeks.value.values.firstNotNullOfOrNull { week -> + week.dataOrNull()?.firstOrNull { it.id == turnId } + } ?: return + if (turn.completedAt != null) { + inHouse("Couldn't undo that.") { chores.uncompleteTurn(it, turnId) } + } else { + inHouse("Couldn't mark it done.") { chores.completeTurn(it, turnId) } + } + } + + /** Only one-time chores can be deleted on their own, and the backend doesn't have those. */ + override fun deleteChore(id: String) { + _messages.tryEmit("Delete the rotation to remove this chore.") + } + + /** + * The server gives the next turn to whoever is first in the new rotation, so the list is + * reordered to start with whoever was up next (as [ChoreRules.withPlan] does for the fake). + * [peoplePerWeek] and [fromWeek] aren't supported (see [Capabilities.Backend]). + */ + override fun updateRotation(id: String, memberIds: List, peoplePerWeek: Int, fromWeek: LocalDate) { + val choreId = id.toIntOrNull() ?: return + val rotation = state.value.rotations.firstOrNull { it.id == id } ?: return + if (memberIds.isEmpty()) return + val ordered = ChoreRules.withPlan(rotation, rotation.startWeek, memberIds, 1).plans.last().memberIds + val body = UpdateChoreBody(rotation = ordered.mapNotNull { it.toIntOrNull() }) + inHouse("Couldn't save the rotation.") { chores.updateChore(it, choreId, body) } + } + + override fun deleteRotation(id: String) { + val choreId = id.toIntOrNull() ?: return + inHouse("Couldn't delete the rotation.") { chores.deleteChore(it, choreId) } + } + + // endregion + + // region Shopping + + override fun addItem(name: String) { + if (name.isBlank()) return + inHouse("Couldn't add the item.") { shopping.addItem(it, RemoteMapping.encodeItemName(name, 1)) } + } + + override fun incrementQuantity(id: String) { + val item = state.value.shopping.firstOrNull { it.id == id } ?: return + rename(item, item.name, item.quantity + 1) + } + + override fun markBought(id: String) { + val itemId = id.toIntOrNull() ?: return + inHouse("Couldn't mark it bought.") { shopping.buyItem(it, itemId) } + } + + override fun undoBought(id: String) { + val itemId = id.toIntOrNull() ?: return + inHouse("Couldn't undo that.") { shopping.unbuyItem(it, itemId) } + } + + override fun toggleCouldntFind(id: String) { + _messages.tryEmit("\"Couldn't find it\" isn't available yet.") + } + + /** [note] isn't saved: the backend has no item notes yet (see [Capabilities.Backend]). */ + override fun saveItem(id: String, name: String, quantity: Int, note: String) { + val item = state.value.shopping.firstOrNull { it.id == id } ?: return + rename(item, name.trim().ifEmpty { item.name }, quantity.coerceAtLeast(1)) + } + + override fun deleteItem(id: String) { + val itemId = id.toIntOrNull() ?: return + inHouse("Couldn't delete the item.") { shopping.deleteItem(it, itemId) } + } + + private fun rename(item: ShoppingItem, name: String, quantity: Int) { + val itemId = item.id.toIntOrNull() ?: return + val encoded = RemoteMapping.encodeItemName(name, quantity) + if (encoded == RemoteMapping.encodeItemName(item.name, item.quantity)) return + inHouse("Couldn't save the item.") { shopping.updateItem(it, itemId, UpdateShoppingItemBody(name = encoded)) } + } + + // endregion + + // region Plumbing + + private fun loadHouse(id: Int, refresh: Boolean) { + houses.fetchHouse(id, refresh) + chores.fetchChores(id, refresh) + notes.fetchNoteBoard(id, refresh) + shopping.fetchShoppingList(id, refresh) + if (refresh) chores.refreshWeeks(id) + val thisWeek = ChoreRules.weekStart(today()) + if (thisWeek !in chores.weeks.value) chores.fetchWeek(id, thisWeek) + } + + /** Runs [call] for the current house and reports a failure on [messages]. */ + private fun inHouse(failure: String, call: suspend (houseId: Int) -> RoomieApiResponse<*>) { + val id = houseId ?: return + scope.launch { + val result = call(id) + if (result is RoomieApiResponse.Error) report(result.error, failure) + } + } + + private fun report(error: ApiError, failure: String) { + _messages.tryEmit(messageFor(error, failure)) + } + + private fun messageFor(error: ApiError, failure: String): String = when (error.code) { + ApiErrorCode.NETWORK -> NETWORK_MESSAGE + ApiErrorCode.UNKNOWN -> failure + ApiErrorCode.VALIDATION_ERROR -> "$failure ${error.fieldErrors.values.firstOrNull() ?: error.message}" + else -> "$failure ${error.message}" + } + + private val savedNetId: String? get() = prefs.getString(KEY_NET_ID, null) + + private fun forgetSignIn() { + prefs.edit().remove(KEY_NET_ID).apply() + } + + private fun savedBuddy(netId: String): Buddy? = + prefs.getString(KEY_BUDDY_PREFIX + netId, null)?.let { name -> Buddy.entries.firstOrNull { it.name == name } } + + private fun build( + me: RoomieApiResponse, + house: RoomieApiResponse, + local: Local, + data: Data, + ): RoomieState { + val base = RoomieState(capabilities = Capabilities.Backend, restoring = local.restoring) + val session = me.dataOrNull() ?: return base + val user = session.user + val (first, last) = RemoteMapping.splitName(user.name) + val buddy = savedBuddy(user.netid) ?: RemoteMapping.buddyFor(user.id) + val houseDto = house.dataOrNull()?.takeIf { it.id == session.house?.id } + val uiSession = Session(user.id.toString(), user.netid, first, last, buddy, hasHouse = session.house != null) + val zone = houseDto?.timezone?.let { runCatching { ZoneId.of(it) }.getOrNull() } ?: ZoneId.systemDefault() + + val uiHouse = when { + houseDto != null -> RemoteMapping.house(houseDto, user.id, buddy) + session.house == null && local.draft != null -> RemoteMapping.draftHouse( + local.draft.name, + Roommate(user.id.toString(), user.netid, first, last, buddy, MemberStatus.Owner), + local.draft.invites, + ) + else -> null + } + if (houseDto == null) return base.copy(session = uiSession, house = uiHouse) + + val board = data.notes.dataOrNull() + val list = data.shopping.dataOrNull() + return base.copy( + session = uiSession, + house = uiHouse, + notes = board?.let { (it.pinned + it.notes).distinctBy { n -> n.id } }.orEmpty() + .map { RemoteMapping.note(it, ZoneId.systemDefault()) }, + chores = data.weeks.values.flatMap { it.dataOrNull().orEmpty() } + .distinctBy { it.id } + .map { RemoteMapping.chore(it, zone) }, + rotations = data.chores.dataOrNull().orEmpty().map(RemoteMapping::rotation), + shopping = list?.let { it.needed + it.bought }.orEmpty() + .map { RemoteMapping.item(it, ZoneId.systemDefault()) }, + ) + } + + // endregion + + private companion object { + const val KEY_NET_ID = "netId" + const val KEY_BUDDY_PREFIX = "buddy." + const val NETWORK_MESSAGE = "Couldn't reach the server. Check your connection and try again." + } +} diff --git a/app/src/main/java/com/example/roomie/data/RoomieRepository.kt b/app/src/main/java/com/example/roomie/data/RoomieRepository.kt new file mode 100644 index 0000000..4f16015 --- /dev/null +++ b/app/src/main/java/com/example/roomie/data/RoomieRepository.kt @@ -0,0 +1,80 @@ +package com.example.roomie.data + +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.StateFlow +import java.time.DayOfWeek +import java.time.LocalDate +import java.time.LocalDateTime + +/** + * Everything the screens read and do, as one [RoomieState]. Two implementations: + * [FakeRoomieRepository] (in memory, seeded demo data) and [RemoteRoomieRepository] (the Roomie + * backend). `roomie.fakeData` in `local.properties` picks between them; see `RepositoryModule`. + * + * Calls that return nothing apply their change as soon as the data source confirms it. If one + * fails, a one-line explanation arrives on [messages] instead. + */ +interface RoomieRepository { + + sealed interface SignInResult { + data class Invalid(val message: String) : SignInResult + data class Success(val hasHouse: Boolean) : SignInResult + } + + val state: StateFlow + + /** Problems to show the user, e.g. "Couldn't reach the server." Each is shown once. */ + val messages: Flow + + fun today(): LocalDate + fun now(): LocalDateTime + + /** Reloads everything from the data source, e.g. when the app comes back to the foreground. */ + fun refresh() {} + + // Session and onboarding + + fun isValidNetId(netId: String): Boolean + suspend fun signIn(netIdInput: String, password: String): SignInResult + fun signOut() + fun setBuddy(buddy: Buddy) + /** Starts a draft house owned by you; it's named on the last onboarding step. */ + fun startHouse() + /** Returns an error message, or null once you've joined. */ + suspend fun joinHouse(code: String): String? + /** Returns an error message, or null when the invite was sent (or queued in the draft). */ + suspend fun inviteRoommate(netIdInput: String): String? + fun removeRoommate(id: String) + fun renameHouse(name: String) + /** Creates the draft house, if there is one. Returns an error message, or null on success. */ + suspend fun finishOnboarding(name: String): String? + fun leaveHouse() + + // Notes + + fun addNote(text: String, dueDate: LocalDate?, pin: Boolean) + fun updateNote(id: String, text: String, dueDate: LocalDate?) + fun deleteNote(id: String) + fun togglePin(id: String) + + // Chores + + /** Loads the week starting [weekStart] (a Monday) if the data source fetches by week. */ + fun showWeek(weekStart: LocalDate) {} + fun addChore(title: String, assigneeIds: List, dueDate: LocalDate) + fun addRotation(title: String, dueDay: DayOfWeek, memberIds: List, peoplePerWeek: Int, startWeek: LocalDate) + fun toggleChoreDone(id: String) + fun deleteChore(id: String) + fun updateRotation(id: String, memberIds: List, peoplePerWeek: Int, fromWeek: LocalDate) + fun deleteRotation(id: String) + + // Shopping + + fun addItem(name: String) + fun incrementQuantity(id: String) + fun markBought(id: String) + fun undoBought(id: String) + fun toggleCouldntFind(id: String) + fun saveItem(id: String, name: String, quantity: Int, note: String) + fun deleteItem(id: String) +} diff --git a/app/src/main/java/com/example/roomie/data/ShoppingRepository.kt b/app/src/main/java/com/example/roomie/data/ShoppingRepository.kt index c1fb3e3..238956b 100644 --- a/app/src/main/java/com/example/roomie/data/ShoppingRepository.kt +++ b/app/src/main/java/com/example/roomie/data/ShoppingRepository.kt @@ -31,6 +31,9 @@ class ShoppingRepository @Inject constructor(private val retrofitInstance: Retro _shoppingList.fetch(refresh) { api.getShoppingList(houseId) } } + /** Forgets the list, e.g. on sign-out or after leaving the house. */ + fun clear() = _shoppingList.set(RoomieApiResponse.Pending) + suspend fun addItem(houseId: Int, name: String, category: ShoppingCategory? = null): RoomieApiResponse = changing(houseId) { api.addItem(houseId, AddShoppingItemBody(name.trim(), category)).item } 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 fceba6b..5c6cd5b 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 @@ -21,8 +21,10 @@ 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 six post-it colors, in the order the server hands them out. */ +enum class NoteColorDto { YELLOW, ORANGE, BLUE, GREEN, PINK, PURPLE } + +enum class LivingType { ON_CAMPUS, OFF_CAMPUS } /** The public view of a person: members, rotation, assignee, claimedBy, … */ data class UserDto( @@ -61,12 +63,18 @@ data class MemberDto( data class HouseDto( val id: Int, val name: String, + /** Hex, e.g. `#8B5A34`. */ + val color: String?, + val livingType: LivingType?, + val address: 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, + /** e.g. `CHORES`, `SHOPPING`. Kept as strings so a new feature doesn't break parsing. */ + val features: List?, val members: List, val pendingInvites: List, ) @@ -75,7 +83,7 @@ data class HouseDto( 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) +data class HouseSummaryDto(val id: Int, val name: String, val color: String?, val role: MemberRole) /** An invite you received. Has enough for the "Join this house?" prompt. */ data class InviteDto( @@ -85,7 +93,7 @@ data class InviteDto( val invitedBy: UserDto, ) -data class InviteHouseDto(val id: Int, val name: String, val members: List) +data class InviteHouseDto(val id: Int, val name: String, val color: String?, val members: List) data class ChoreDto( val id: Int, @@ -139,13 +147,16 @@ data class NoteDto( val id: Int, /** 1 to 500 characters. */ val body: String, + /** The server picks one when the app leaves it out. */ val color: NoteColorDto, - /** Compare `author.id` with your own ID to show Edit and Delete. */ - val author: UserDto, + /** Feeds "Coming up" on Home. Can't be in the past. */ + val dueOn: LocalDate?, + /** Pinned notes stay on the board until someone unpins them. */ val pinned: Boolean, - /** When the pin ends. Null on a pinned note means until someone unpins it. */ - val pinnedUntil: Instant?, + val pinnedAt: Instant?, val createdAt: Instant, /** Later than [createdAt] means it was edited. */ val updatedAt: Instant, + /** Compare `author.id` with your own ID to show Edit. */ + val author: UserDto, ) 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 index 988fb2b..6afb31f 100644 --- a/app/src/main/java/com/example/roomie/data/api/NoteApiService.kt +++ b/app/src/main/java/com/example/roomie/data/api/NoteApiService.kt @@ -1,30 +1,25 @@ package com.example.roomie.data.api +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.RequestBody +import okhttp3.RequestBody.Companion.toRequestBody 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 +import java.time.LocalDate /** - * 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. + * The Note Board. Notes stay on the board for 14 days after posting, or until their due date if + * that's later; pinned notes stay until someone unpins them. Notes off the board return 404. */ 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). - */ + /** Everything on the board: pinned notes (most recently pinned first), then the rest, newest first. */ @GET("houses/{houseId}/notes") - suspend fun getNotes( - @Path("houseId") houseId: Int, - @Query("before") before: Int? = null, - @Query("limit") limit: Int? = null, - ): NoteBoardResponse + suspend fun getNotes(@Path("houseId") houseId: Int): NoteBoardResponse @POST("houses/{houseId}/notes") suspend fun createNote(@Path("houseId") houseId: Int, @Body body: CreateNoteBody): NoteResponse @@ -32,61 +27,46 @@ interface NoteApiService { @GET("houses/{houseId}/notes/{noteId}") suspend fun getNote(@Path("houseId") houseId: Int, @Path("noteId") noteId: Int): NoteResponse - /** Your own notes only. */ + /** Author only. Build [body] with [updateNoteBody]: clearing the due date needs an explicit null. */ @PATCH("houses/{houseId}/notes/{noteId}") suspend fun updateNote( @Path("houseId") houseId: Int, @Path("noteId") noteId: Int, - @Body body: UpdateNoteBody, + @Body body: RequestBody, ): 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. */ + /** Any member. Pinning a pinned note moves it to the top. */ @POST("houses/{houseId}/notes/{noteId}/pin") - suspend fun pinNote( - @Path("houseId") houseId: Int, - @Path("noteId") noteId: Int, - @Body body: PinNoteBody, - ): NoteResponse + suspend fun pinNote(@Path("houseId") houseId: Int, @Path("noteId") noteId: Int): 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 NoteBoardResponse(val pinned: List, val notes: List) data class NoteResponse(val note: NoteDto) data class CreateNoteBody( val body: String, + /** Leave it out and the server picks the color used least recently. */ val color: NoteColorDto? = null, - val pinnedUntil: Instant? = null, -) - -data class UpdateNoteBody( - val body: String? = null, - val color: NoteColorDto? = null, + val dueOn: LocalDate? = null, + /** The "Pin Note" switch. */ + val pinned: Boolean? = null, + /** The "Notify Others" switch. Accepted, but ignored until push notifications exist. */ + val notify: Boolean? = 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) +/** + * A PATCH body for [NoteApiService.updateNote] that sends `body` and `dueOn` together, with + * `"dueOn": null` when [dueOn] is null so the due date is cleared. (The shared Gson leaves nulls + * out, which would mean "don't change it".) + */ +fun updateNoteBody(body: String, dueOn: LocalDate?): RequestBody = + RoomieGson.gsonWithNulls.toJson(mapOf("body" to body, "dueOn" to dueOn?.toString())) + .toRequestBody("application/json; charset=utf-8".toMediaType()) 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 index 8829afc..6d64960 100644 --- a/app/src/main/java/com/example/roomie/data/api/RoomieApiResponse.kt +++ b/app/src/main/java/com/example/roomie/data/api/RoomieApiResponse.kt @@ -163,6 +163,54 @@ internal class ResponseFlow(private val scope: CoroutineScope) { } } +/** + * Several [RoomieApiResponse]s of the same kind, one per key (e.g. one per week), with the same + * rules as [ResponseFlow] applied to each key: only a key's latest fetch publishes, [clear] drops + * everything and discards fetches in flight, and [updateAll] is serialized with every other write. + */ +internal class KeyedResponseFlow(private val scope: CoroutineScope) { + private val lock = Any() + private val flow = MutableStateFlow>>(emptyMap()) + private val generations = HashMap() + private val inFlight = HashMap() + private var nextGeneration = 0L + + val state: StateFlow>> = flow.asStateFlow() + + val keys: Set get() = flow.value.keys + + /** Like [ResponseFlow.fetch], for [key] only. */ + fun fetch(key: K, refresh: Boolean = false, call: suspend () -> T): Job = synchronized(lock) { + inFlight.remove(key)?.cancel() + val mine = ++nextGeneration + generations[key] = mine + if (!refresh || flow.value[key] == null) flow.value = flow.value + (key to RoomieApiResponse.Pending) + scope.launch { + val result = apiCall(call) + synchronized(lock) { + if (generations[key] != mine) return@synchronized + val keepShownData = refresh && result is RoomieApiResponse.Error && + flow.value[key] is RoomieApiResponse.Success + if (!keepShownData) flow.value = flow.value + (key to result) + inFlight.remove(key) + } + }.also { inFlight[key] = it } + } + + /** Patches every key's value in place. Fetches in flight are left alone, as in [ResponseFlow.update]. */ + fun updateAll(transform: (RoomieApiResponse) -> RoomieApiResponse) = synchronized(lock) { + flow.value = flow.value.mapValues { (_, value) -> transform(value) } + } + + /** Drops every key. Fetches in flight are cancelled and can't bring their key back. */ + fun clear() = synchronized(lock) { + inFlight.values.forEach { it.cancel() } + inFlight.clear() + generations.clear() + flow.value = emptyMap() + } +} + /** `{ status, statusCode, message, errorCode, data }`, the body of every error response. */ private class ErrorBody(val message: String?, val errorCode: String?, val data: JsonElement?) 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 index a790153..42badf8 100644 --- a/app/src/main/java/com/example/roomie/data/api/RoomieGson.kt +++ b/app/src/main/java/com/example/roomie/data/api/RoomieGson.kt @@ -18,6 +18,9 @@ object RoomieGson { .registerTypeAdapter(LocalDate::class.java, LocalDateAdapter.nullSafe()) .registerTypeAdapter(Instant::class.java, InstantAdapter.nullSafe()) .create() + + /** For the rare body where null means "clear this field", e.g. a note's due date. */ + val gsonWithNulls: Gson = gson.newBuilder().serializeNulls().create() } private object LocalDateAdapter : TypeAdapter() { 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 index 1225834..9eef69b 100644 --- a/app/src/main/java/com/example/roomie/data/api/UserApiService.kt +++ b/app/src/main/java/com/example/roomie/data/api/UserApiService.kt @@ -30,7 +30,8 @@ interface UserApiService { data class LoginResponse( val isNewUser: Boolean, val user: SelfDto, - val house: HouseDto?, + /** Just the summary; fetch the full house with `GET /houses/{id}`. */ + val house: HouseSummaryDto?, val pendingInvites: List, ) diff --git a/app/src/test/java/com/example/roomie/data/RemoteMappingTest.kt b/app/src/test/java/com/example/roomie/data/RemoteMappingTest.kt new file mode 100644 index 0000000..844d715 --- /dev/null +++ b/app/src/test/java/com/example/roomie/data/RemoteMappingTest.kt @@ -0,0 +1,101 @@ +package com.example.roomie.data + +import com.example.roomie.data.api.ChoreDto +import com.example.roomie.data.api.ChoreFrequency +import com.example.roomie.data.api.Presence +import com.example.roomie.data.api.TurnChoreDto +import com.example.roomie.data.api.TurnDto +import com.example.roomie.data.api.TurnStatus +import com.example.roomie.data.api.UserDto +import org.junit.Assert.assertEquals +import org.junit.Test +import java.time.DayOfWeek +import java.time.LocalDate + +class RemoteMappingTest { + + @Test + fun quantityRoundTripsThroughTheName() { + assertEquals("Eggs ×2", RemoteMapping.encodeItemName("Eggs", 2)) + assertEquals("Eggs", RemoteMapping.encodeItemName(" Eggs ", 1)) + assertEquals("Eggs" to 2, RemoteMapping.decodeItemName("Eggs ×2")) + assertEquals("Eggs" to 1, RemoteMapping.decodeItemName("Eggs")) + // Not ours: a name that happens to end in ×1, or has no space before ×. + assertEquals("Thing ×1" to 1, RemoteMapping.decodeItemName("Thing ×1")) + assertEquals("Size×2" to 1, RemoteMapping.decodeItemName("Size×2")) + } + + @Test + fun encodedNamesFitTheServerLimit() { + val encoded = RemoteMapping.encodeItemName("x".repeat(100), 12) + assertEquals(80, encoded.length) + assertEquals("x".repeat(76) to 12, RemoteMapping.decodeItemName(encoded)) + } + + @Test + fun splitsNamesOnTheFirstSpace() { + assertEquals("Stef" to "Rivera-Osorio", RemoteMapping.splitName("Stef Rivera-Osorio")) + assertEquals("Mary" to "Ann Lee", RemoteMapping.splitName("Mary Ann Lee")) + assertEquals("mnh49" to "", RemoteMapping.splitName("mnh49")) + } + + @Test + fun acceptsTheBackendsNetIds() { + assertEquals(true, RemoteMapping.isValidNetId("jw2877@cornell.edu")) + assertEquals(true, RemoteMapping.isValidNetId("a1")) + assertEquals(false, RemoteMapping.isValidNetId("abcde1")) + } + + @Test + fun firstTurnNeverStartsInThePast() { + val wednesday = LocalDate.of(2026, 11, 25) + val thisMonday = LocalDate.of(2026, 11, 23) + assertEquals(LocalDate.of(2026, 11, 26), RemoteMapping.firstTurn(thisMonday, DayOfWeek.THURSDAY, wednesday)) + assertEquals(LocalDate.of(2026, 11, 30), RemoteMapping.firstTurn(thisMonday, DayOfWeek.MONDAY, wednesday)) + assertEquals(wednesday, RemoteMapping.firstTurn(thisMonday, DayOfWeek.WEDNESDAY, wednesday)) + } + + @Test + fun rotationPredictsTheServersNextTurns() { + val a = user(1); val b = user(2); val c = user(3) + // B has the next turn, on Thursday Dec 3. + val chore = ChoreDto( + id = 9, title = "Trash", frequency = ChoreFrequency.WEEKLY, startsOn = LocalDate.of(2026, 11, 5), + allowSwaps = true, reminderHour = null, rotation = listOf(a, b, c), + comingUp = listOf(turn(40, b, LocalDate.of(2026, 12, 3))), + ) + + val rotation = RemoteMapping.rotation(chore) + + assertEquals(DayOfWeek.THURSDAY, rotation.dueDay) + val week = ChoreRules.weekStart(LocalDate.of(2026, 12, 3)) + assertEquals(listOf("2"), rotation.assigneesFor(week)) + assertEquals(listOf("3"), rotation.assigneesFor(week.plusWeeks(1))) + assertEquals(listOf("1"), rotation.assigneesFor(week.plusWeeks(2))) + } + + @Test + fun turnsBecomeChoresWithPrefixedIds() { + val chore = RemoteMapping.chore(turn(40, user(2), LocalDate.of(2026, 12, 3)), java.time.ZoneId.of("America/New_York")) + assertEquals("t40", chore.id) + assertEquals("9", chore.rotationId) + assertEquals(listOf("2"), chore.assigneeIds) + } + + @Test + fun serverTurnsAreNotDoubledByRotations() { + val week = LocalDate.of(2026, 11, 23) + val rotation = Rotation("9", "Trash", DayOfWeek.THURSDAY, listOf(RotationPlan(week, listOf("2"), 1))) + val turn = Chore("t40", "Trash", listOf("2"), week.plusDays(3), rotationId = "9") + val state = RoomieState(chores = listOf(turn), rotations = listOf(rotation), capabilities = Capabilities.Backend) + + assertEquals(listOf("t40"), ChoreRules.choresInWeek(state, week, week).map { it.id }) + } + + private fun user(id: Int) = UserDto(id, "u$id", "User $id", null, Presence.HOME) + + private fun turn(id: Int, assignee: UserDto, dueOn: LocalDate) = TurnDto( + id = id, chore = TurnChoreDto(9, "Trash", ChoreFrequency.WEEKLY), dueOn = dueOn, status = TurnStatus.UPCOMING, + assignee = assignee, completedAt = null, completedBy = null, canSwap = true, + ) +} diff --git a/app/src/test/java/com/example/roomie/data/api/LiveBackendTest.kt b/app/src/test/java/com/example/roomie/data/api/LiveBackendTest.kt new file mode 100644 index 0000000..ec825fe --- /dev/null +++ b/app/src/test/java/com/example/roomie/data/api/LiveBackendTest.kt @@ -0,0 +1,122 @@ +package com.example.roomie.data.api + +import com.example.roomie.data.ChoreRules +import com.example.roomie.data.NoteColor +import com.example.roomie.data.RemoteMapping +import kotlinx.coroutines.runBlocking +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Assume.assumeTrue +import org.junit.Test +import java.time.LocalDate +import java.time.ZoneId + +/** + * Runs the app's real client against a running backend, to catch DTOs that drift from the API. + * Skipped unless `ROOMIE_E2E_URL` is set, e.g. + * `ROOMIE_E2E_URL=http://localhost:8000/ ./gradlew :app:testDebugUnitTest --tests '*LiveBackendTest*'`. + * The backend needs `AUTH_DEV_BYPASS=true`. Each run signs up two new NetIDs. + */ +class LiveBackendTest { + + private val baseUrl: String? = System.getenv("ROOMIE_E2E_URL") + + /** `zz123456`-style NetIDs, new each run so runs don't collide. */ + private val run = (100_000..999_999).random() + private val alice = "za$run" + private val bob = "zb$run" + + private fun client(netId: String): RetrofitInstance { + val tokens = TokenProvider { "dev:$netId" } + return RetrofitInstance(roomieRetrofit(baseUrl!!, tokens, logBodies = false)) + } + + private fun RoomieApiResponse.ok(step: String): T { + assertTrue("$step failed: $this", this is RoomieApiResponse.Success) + return (this as RoomieApiResponse.Success).data + } + + @Test + fun wholeFlowParses() = runBlocking { + assumeTrue("Set ROOMIE_E2E_URL to run", baseUrl != null) + val a = client(alice) + val b = client(bob) + + // Sign up both; the login house is a summary. + val aliceLogin = apiCall { a.userApi.login() }.ok("login A") + assertNull(aliceLogin.house) + apiCall { b.userApi.login() }.ok("login B") + + // Alice makes a house and invites Bob, who accepts. + val house = apiCall { a.houseApi.createHouse(CreateHouseBody("E2E House $run", inviteNetids = listOf(bob))) }.ok("create house").house + assertEquals(listOf(bob), house.pendingInvites.map { it.netid }) + val invite = apiCall { b.userApi.getMe() }.ok("me B").pendingInvites.single() + apiCall { b.houseApi.acceptInvite(invite.id) }.ok("accept") + val me = apiCall { a.userApi.getMe() }.ok("me A") + assertEquals(house.id, me.house?.id) + val full = apiCall { a.houseApi.getHouse(house.id) }.ok("get house").house + assertEquals(2, full.members.size) + assertNotNull(full.color) + val uiHouse = RemoteMapping.house(full, me.user.id, RemoteMapping.buddyFor(me.user.id)) + assertEquals(2, uiHouse.members.size) + + // Presence round-trips. + val away = apiCall { a.userApi.updateMe(UpdateMeBody(presence = Presence.AWAY)) }.ok("presence") + assertEquals(Presence.AWAY, away.user.presence) + + // A weekly chore rotating Alice, Bob; its turns map onto the app's chores. + val zone = ZoneId.of(full.timezone) + val today = LocalDate.now(zone) + val week = ChoreRules.weekStart(today) + val ids = full.members.map { it.id } + val startsOn = RemoteMapping.firstTurn(week, today.dayOfWeek, today) + val chore = apiCall { + a.choreApi.createChore(house.id, CreateChoreBody("Trash", ChoreFrequency.WEEKLY, startsOn, ids)) + }.ok("create chore").chore + val rotation = RemoteMapping.rotation(chore) + assertEquals(chore.comingUp.first().assignee.id.toString(), rotation.assigneesFor(ChoreRules.weekStart(chore.comingUp.first().dueOn)).single()) + val turns = apiCall { + a.choreApi.getAssignments(house.id, week, week.plusDays(6), includeOverdue = true) + }.ok("week").assignments + val turn = turns.single { it.chore.id == chore.id } + assertEquals(today, turn.dueOn) + val done = apiCall { a.choreApi.completeAssignment(house.id, turn.id) }.ok("complete").assignment + assertEquals(today, RemoteMapping.chore(done, zone).completedOn) + apiCall { a.choreApi.uncompleteAssignment(house.id, turn.id) }.ok("uncomplete") + // Edit the rotation, reversed, as updateRotation does. + apiCall { a.choreApi.updateChore(house.id, chore.id, UpdateChoreBody(rotation = ids.reversed())) }.ok("edit rotation") + + // Notes: due date, pin, clearing the due date with an explicit null. + val note = apiCall { + a.noteApi.createNote(house.id, CreateNoteBody("Rent due", dueOn = today.plusDays(3), pinned = true)) + }.ok("create note").note + assertTrue(note.pinned) + val board = apiCall { b.noteApi.getNotes(house.id) }.ok("board") + assertEquals(listOf(note.id), board.pinned.map { it.id }) + val cleared = apiCall { a.noteApi.updateNote(house.id, note.id, updateNoteBody("Rent paid", dueOn = null)) }.ok("edit note").note + assertNull(cleared.dueOn) + assertEquals("Rent paid", cleared.body) + apiCall { b.noteApi.unpinNote(house.id, note.id) }.ok("unpin") + val mapped = RemoteMapping.note(cleared, zone) + assertTrue(mapped.color in NoteColor.entries) + apiCall { a.noteApi.deleteNote(house.id, note.id) }.ok("delete note") + + // Shopping, with the quantity stored in the name. + val item = apiCall { + b.shoppingApi.addItem(house.id, AddShoppingItemBody(RemoteMapping.encodeItemName("Eggs", 2))) + }.ok("add item").item + assertEquals("Eggs" to 2, RemoteMapping.decodeItemName(item.name)) + apiCall { a.shoppingApi.buyItem(house.id, item.id, BuyItemBody()) }.ok("buy") + val list = apiCall { a.shoppingApi.getShoppingList(house.id) }.ok("list") + assertEquals(listOf(item.id), list.bought.map { it.id }) + assertEquals(alice, list.bought.single().boughtBy?.netid) + apiCall { a.shoppingApi.unbuyItem(house.id, item.id) }.ok("unbuy") + + // Both leave; the last one out deletes the house. + apiCall { b.houseApi.leaveHouse(house.id) }.ok("leave B") + apiCall { a.houseApi.leaveHouse(house.id) }.ok("leave A") + assertNull(apiCall { a.userApi.getMe() }.ok("me after").house) + } +} diff --git a/app/src/test/java/com/example/roomie/data/api/ResponseFlowTest.kt b/app/src/test/java/com/example/roomie/data/api/ResponseFlowTest.kt index 77dc7fa..8894c2f 100644 --- a/app/src/test/java/com/example/roomie/data/api/ResponseFlowTest.kt +++ b/app/src/test/java/com/example/roomie/data/api/ResponseFlowTest.kt @@ -39,6 +39,35 @@ class ResponseFlowTest { assertEquals(RoomieApiResponse.Pending, flow.state.value) } + @Test + fun keyedFetchesOnlyReplaceTheirOwnKey() = runBlocking { + val weeks = KeyedResponseFlow(scope) + val slowFirst = CompletableDeferred() + + weeks.fetch(1) { slowFirst.await() } + weeks.fetch(1) { "first, again" }.join() + weeks.fetch(2) { "second" }.join() + slowFirst.complete("first, stale") + + assertEquals( + mapOf(1 to RoomieApiResponse.Success("first, again"), 2 to RoomieApiResponse.Success("second")), + weeks.state.value, + ) + } + + @Test + fun clearDiscardsKeyedFetchesInFlight() = runBlocking { + val weeks = KeyedResponseFlow(scope) + val slow = CompletableDeferred() + + val fetch = weeks.fetch(1) { slow.await() } + weeks.clear() + slow.complete("from before sign-out") + fetch.join() + + assertEquals(emptyMap>(), weeks.state.value) + } + @Test fun concurrentUpdatesAreNotLost() = runBlocking { val flow = ResponseFlow(scope) 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 a1c1dc9..027dff2 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 @@ -161,6 +161,16 @@ class RoomieApiTest { assertEquals("""{"priceCents":429}""", server.takeRequest().body.readUtf8()) } + @Test + fun clearsANotesDueDateWithAnExplicitNull() = runBlocking { + server.enqueue(json(200, """{"note":null}""")) + val noteApi = roomieRetrofit(server.url("/").toString(), tokens, logBodies = false).create(NoteApiService::class.java) + + apiCall { noteApi.updateNote(1, 2, updateNoteBody("Rent", dueOn = null)) } + + assertEquals("""{"body":"Rent","dueOn":null}""", server.takeRequest().body.readUtf8()) + } + @Test fun reportsNetworkFailures() = runBlocking { server.shutdown()