diff --git a/code/app/src/androidTest/java/com/example/lambda_bbb_events/ui/review/ReviewSectionUITest.kt b/code/app/src/androidTest/java/com/example/lambda_bbb_events/ui/review/ReviewSectionUITest.kt index 2b2af545..ba89dc55 100644 --- a/code/app/src/androidTest/java/com/example/lambda_bbb_events/ui/review/ReviewSectionUITest.kt +++ b/code/app/src/androidTest/java/com/example/lambda_bbb_events/ui/review/ReviewSectionUITest.kt @@ -7,12 +7,14 @@ import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.test.assertCountEquals +import androidx.compose.ui.test.assertHasNoClickAction import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.assertIsEnabled import androidx.compose.ui.test.assertIsNotEnabled +import androidx.compose.ui.test.assertIsNotSelected import androidx.compose.ui.test.assertIsSelected +import androidx.compose.ui.test.getUnclippedBoundsInRoot import androidx.compose.ui.test.assertTextContains -import androidx.compose.ui.test.assertIsNotSelected import androidx.compose.ui.test.isDialog import androidx.compose.ui.test.junit4.v2.createComposeRule import androidx.compose.ui.test.onAllNodesWithTag @@ -25,9 +27,15 @@ import androidx.compose.ui.test.performTextReplacement import androidx.test.ext.junit.runners.AndroidJUnit4 import com.example.lambda_bbb_events.controller.AppControllers import com.example.lambda_bbb_events.controller.ReviewController +import com.example.lambda_bbb_events.controller.ReviewReactionController +import com.example.lambda_bbb_events.controller.ReviewReplyController import com.example.lambda_bbb_events.model.campsite.Campsite +import com.example.lambda_bbb_events.model.repository.ReviewReactionRepository +import com.example.lambda_bbb_events.model.repository.ReviewReplyRepository import com.example.lambda_bbb_events.model.repository.ReviewRepository import com.example.lambda_bbb_events.model.review.Review +import com.example.lambda_bbb_events.model.review.ReviewReaction +import com.example.lambda_bbb_events.model.review.ReviewReply import com.example.lambda_bbb_events.model.user.Admin import com.example.lambda_bbb_events.model.user.CampsiteOwner import com.example.lambda_bbb_events.model.user.Entrant @@ -41,10 +49,12 @@ import io.mockk.mockk import io.mockk.unmockkAll import org.junit.After import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import java.util.Date +import kotlin.math.abs /** * Tests reading, writing, editing, and deleting reviews on a campsite's page. The repository is @@ -62,12 +72,25 @@ class ReviewSectionUITest { /** The stored reviews. Compose state, like the repository's cache. */ private var stored by mutableStateOf>(emptyList()) + private val replyRepository = mockk() + private val reactionRepository = mockk() + private var storedReplies by mutableStateOf>(emptyList()) + private var storedReactions by mutableStateOf>(emptyList()) + private val campsite = Campsite(campsiteId = "site-1", ownerId = "owner-1", campsiteName = "Lakeside") private val ed = Entrant(deviceId = "user-1", name = "Ed") private fun review(userId: String, rating: Int, comment: String = "", day: Long = 1) = Review("site-1_$userId", "site-1", userId, rating, comment, Date(day * 86_400_000)) + private fun centerOf(tag: String): Pair { + val bounds = composeTestRule.onNodeWithTag(tag).getUnclippedBoundsInRoot() + return (bounds.left + bounds.right).value / 2 to (bounds.top + bounds.bottom).value / 2 + } + + private fun reactionBy(userId: String, emoji: String) = + ReviewReaction(ReviewReaction.idFor("site-1_user-3", userId), "site-1_user-3", userId, emoji) + private fun showSection(signedIn: User?, vararg reviews: Review) { stored = reviews.toList() every { repository.getReviewsForCampsite("site-1") } answers { stored } @@ -82,6 +105,22 @@ class ReviewSectionUITest { stored = stored.filter { it.reviewId != firstArg() } } every { controllers.reviews } returns ReviewController(repository) + storedReplies = emptyList() + storedReactions = emptyList() + every { replyRepository.newReplyId() } returns "reply-1" + every { replyRepository.getRepliesFor(any()) } answers { storedReplies.filter { it.reviewId == firstArg() } } + coEvery { replyRepository.add(any()) } answers { storedReplies = storedReplies + firstArg() } + every { reactionRepository.getReactionsFor(any()) } answers { storedReactions.filter { it.reviewId == firstArg() } } + every { reactionRepository.getCached(any()) } answers { storedReactions.find { it.reactionId == firstArg() } } + coEvery { reactionRepository.add(any()) } answers { + val saved = firstArg() + storedReactions = storedReactions.filter { it.reactionId != saved.reactionId } + saved + } + coEvery { reactionRepository.delete(any()) } answers { + storedReactions = storedReactions.filter { it.reactionId != firstArg() } + } + every { controllers.reviewReplies } returns ReviewReplyController(replyRepository) + every { controllers.reviewReactions } returns ReviewReactionController(reactionRepository) every { controllers.users.currentUser } returns signedIn every { controllers.users.getCachedUser(any()) } returns null every { controllers.users.getCachedUser("user-1") } returns ed @@ -106,6 +145,109 @@ class ReviewSectionUITest { clearAllMocks() } + @Test + fun emojiTrayStaysHiddenUntilTheReactButtonIsTapped() { + showSection(ed, review("user-3", 5, "Lovely")) + + composeTestRule.onNodeWithTag("emojiTray").assertDoesNotExist() + click("addReaction") + composeTestRule.onNodeWithTag("emojiTray").assertIsDisplayed() + click("addReaction") + composeTestRule.onNodeWithTag("emojiTray").assertDoesNotExist() + } + + @Test + fun tappedEmojiIsPlacedOnTheReviewAndTappingItRemovesIt() { + showSection(ed, review("user-3", 5, "Lovely")) + + click("addReaction") + click("pickReaction_👍") + composeTestRule.onNodeWithTag("placedReaction_👍").assertIsDisplayed() + composeTestRule.onNodeWithTag("emojiTray").assertDoesNotExist() + + click("placedReaction_👍") + composeTestRule.onNodeWithTag("placedReaction_👍").assertDoesNotExist() + } + + @Test + fun sameEmojisShareOneSpotWithTheirCount() { + showSection(ed, review("user-3", 5, "Lovely")) + storedReactions = listOf(reactionBy("user-7", "😂"), reactionBy("user-8", "😂"), reactionBy("user-9", "😮")) + + composeTestRule.onNodeWithTag("placedReaction_😂").assertTextContains("2", substring = true) + composeTestRule.onNodeWithTag("placedReaction_😮").assertIsDisplayed() + } + + @Test + fun emojisStayPutWhenTheTrayOpensAndOnlyBottomOnesFollowTheBottomEdge() { + showSection(ed, review("user-3", 5, "Lovely")) + storedReactions = ReviewReaction.EMOJIS.mapIndexed { i, emoji -> reactionBy("user-${i + 10}", emoji) } + val before = ReviewReaction.EMOJIS.associateWith { centerOf("placedReaction_$it") } + + click("addReaction") + + val cardBottom = composeTestRule.onNodeWithTag("reviewCard").getUnclippedBoundsInRoot().bottom.value + val stayed = ReviewReaction.EMOJIS.filter { abs(centerOf("placedReaction_$it").second - cardBottom) > 1f } + assertTrue(stayed.isNotEmpty()) + for (emoji in stayed) { + val (x, y) = centerOf("placedReaction_$emoji") + assertEquals(emoji, before.getValue(emoji).first, x, 1f) + assertEquals(emoji, before.getValue(emoji).second, y, 1f) + } + } + + @Test + fun pickingTheSameEmojiFromTheTrayAgainRemovesIt() { + showSection(ed, review("user-3", 5, "Lovely")) + + click("addReaction") + click("pickReaction_😮") + composeTestRule.onNodeWithTag("placedReaction_😮").assertIsDisplayed() + + click("addReaction") + click("pickReaction_😮") + composeTestRule.onNodeWithTag("placedReaction_😮").assertDoesNotExist() + } + + @Test + fun tappingSomeoneElsesEmojiAddsYoursToIt() { + showSection(ed, review("user-3", 5, "Lovely")) + storedReactions = listOf(reactionBy("user-9", "❤️")) + + click("placedReaction_❤️") + + composeTestRule.onNodeWithTag("placedReaction_❤️").assertTextContains("2", substring = true) + } + + @Test + fun signedOutUsersCannotTapEmojis() { + showSection(null, review("user-3", 5, "Lovely")) + storedReactions = listOf(reactionBy("user-9", "❤️")) + + composeTestRule.onNodeWithTag("placedReaction_❤️").assertIsDisplayed().assertHasNoClickAction() + } + + @Test + fun replyIsShownUnderTheReviewWithItsAuthor() { + showSection(ed, review("user-3", 5, "Lovely")) + + click("replyButton") + composeTestRule.onNodeWithTag("replyInput").performTextInput("Thanks for the tip") + click("sendReply") + + composeTestRule.onNodeWithTag("replyItem").assertIsDisplayed() + composeTestRule.onNodeWithText("Thanks for the tip").assertIsDisplayed() + composeTestRule.onNodeWithTag("replyInput").assertDoesNotExist() + } + + @Test + fun signedOutUsersCannotReactOrReply() { + showSection(null, review("user-3", 5, "Lovely")) + + composeTestRule.onNodeWithTag("addReaction").assertDoesNotExist() + composeTestRule.onNodeWithTag("replyButton").assertDoesNotExist() + } + @Test fun campsiteWithoutReviewsSaysSo() { showSection(ed) diff --git a/code/app/src/main/java/com/example/lambda_bbb_events/controller/AppControllers.kt b/code/app/src/main/java/com/example/lambda_bbb_events/controller/AppControllers.kt index 966414c3..d7d727cf 100644 --- a/code/app/src/main/java/com/example/lambda_bbb_events/controller/AppControllers.kt +++ b/code/app/src/main/java/com/example/lambda_bbb_events/controller/AppControllers.kt @@ -16,6 +16,8 @@ import com.example.lambda_bbb_events.model.services.PlaceSearch * @property waitlistEntries Controller for waitlist operations. * @property images Service for image processing. * @property reviews Controller for campsite reviews. + * @property reviewReplies Controller for the replies under reviews. + * @property reviewReactions Controller for the emoji reactions to reviews. * @property places Searches for places by name. * @property messages Controller for messaging operations. * @property notificationPreferences Controller for notification preferences. @@ -31,6 +33,8 @@ class AppControllers( val waitlistEntries: WaitlistEntryController, val images: ImageProcessor, val reviews: ReviewController, + val reviewReplies: ReviewReplyController = ReviewReplyController(), + val reviewReactions: ReviewReactionController = ReviewReactionController(), val places: PlaceSearch = FallbackPlaceSearch(), val notifications: NotificationController, val messages: MessageController = MessageController(users), diff --git a/code/app/src/main/java/com/example/lambda_bbb_events/controller/ReviewReactionController.kt b/code/app/src/main/java/com/example/lambda_bbb_events/controller/ReviewReactionController.kt new file mode 100644 index 00000000..796446e4 --- /dev/null +++ b/code/app/src/main/java/com/example/lambda_bbb_events/controller/ReviewReactionController.kt @@ -0,0 +1,107 @@ +package com.example.lambda_bbb_events.controller + +import com.example.lambda_bbb_events.model.repository.ReviewReactionRepository +import com.example.lambda_bbb_events.model.review.Review +import com.example.lambda_bbb_events.model.review.ReviewReaction +import com.example.lambda_bbb_events.model.user.User + +/** + * Controller for the emoji reactions to campsite reviews. + * + * @property reactionRepository The repository for [ReviewReaction]. + */ +class ReviewReactionController( + val reactionRepository: ReviewReactionRepository = ReviewReactionRepository() +) { + /** + * Checks if a user can react to reviews. Anyone who is signed in can. + * + * @param user The user, or `null` if nobody is signed in. + */ + fun canReact(user: User?): Boolean = user != null + + /** + * Counts how many users picked each emoji for a review, in the order of + * [ReviewReaction.EMOJIS]. Emojis nobody picked are left out. + * + * @param review The review. + */ + fun reactionCounts(review: Review): Map { + val reactions = reactionRepository.getReactionsFor(review.reviewId) + return ReviewReaction.EMOJIS + .associateWith { emoji -> reactions.count { it.emoji == emoji } } + .filterValues { it > 0 } + } + + /** + * Gets a user's reaction to a review. + * + * @param review The review. + * @param user The user, or `null` if nobody is signed in. + * @return The reaction, or `null` if the user has not reacted. + */ + fun reactionOf(review: Review, user: User?): ReviewReaction? { + if (user == null) { + return null + } + return reactionRepository.getCached(ReviewReaction.idFor(review.reviewId, user.deviceId)) + } + + /** + * Reacts to a review with an emoji. A user has one reaction per review, so this replaces + * any emoji they picked before. + * + * @param review The review to react to. + * @param user The user reacting, or `null` if nobody is signed in. + * @param emoji The emoji picked, one of [ReviewReaction.EMOJIS]. + * @return `true` if the reaction was saved, `false` otherwise. + */ + suspend fun react(review: Review, user: User?, emoji: String): Boolean { + if (user == null || emoji !in ReviewReaction.EMOJIS) { + return false + } + val reactionId = ReviewReaction.idFor(review.reviewId, user.deviceId) + return try { + reactionRepository.add(ReviewReaction(reactionId, review.reviewId, user.deviceId, emoji)) + true + } catch (_: Exception) { + false + } + } + + /** + * Removes a user's reaction from a review. + * + * @param review The review. + * @param user The user, or `null` if nobody is signed in. + * @return `true` if the reaction was removed, `false` otherwise. + */ + suspend fun removeReaction(review: Review, user: User?): Boolean { + if (user == null) { + return false + } + return try { + reactionRepository.delete(ReviewReaction.idFor(review.reviewId, user.deviceId)) + true + } catch (_: Exception) { + false + } + } + + /** + * Reacts to a review with an emoji, or removes the user's reaction if it is the emoji they + * already picked. + * + * @param review The review. + * @param user The user reacting, or `null` if nobody is signed in. + * @param emoji The emoji picked, one of [ReviewReaction.EMOJIS]. + * @return `true` if the reaction was saved or removed, `false` otherwise. + */ + suspend fun toggleReaction(review: Review, user: User?, emoji: String): Boolean { + return if (reactionOf(review, user)?.emoji == emoji) { + removeReaction(review, user) + } else { + react(review, user, emoji) + } + } +} diff --git a/code/app/src/main/java/com/example/lambda_bbb_events/controller/ReviewReplyController.kt b/code/app/src/main/java/com/example/lambda_bbb_events/controller/ReviewReplyController.kt new file mode 100644 index 00000000..07e2e1a3 --- /dev/null +++ b/code/app/src/main/java/com/example/lambda_bbb_events/controller/ReviewReplyController.kt @@ -0,0 +1,91 @@ +package com.example.lambda_bbb_events.controller + +import com.example.lambda_bbb_events.model.repository.ReviewReplyRepository +import com.example.lambda_bbb_events.model.review.Review +import com.example.lambda_bbb_events.model.review.ReviewReply +import com.example.lambda_bbb_events.model.user.User +import com.example.lambda_bbb_events.model.user.UserRole + +/** + * Controller for the replies under campsite reviews. + * + * @property replyRepository The repository for [ReviewReply]. + */ +class ReviewReplyController( + val replyRepository: ReviewReplyRepository = ReviewReplyRepository() +) { + /** + * Gets the replies to a review, oldest first, so they read like a conversation. + * + * @param review The review. + */ + fun getReplies(review: Review): List { + return replyRepository.getRepliesFor(review.reviewId).sortedBy { it.repliedAt } + } + + /** + * Checks if a user can reply to reviews. Anyone who is signed in can. + * + * @param user The user, or `null` if nobody is signed in. + */ + fun canReply(user: User?): Boolean = user != null + + /** + * Checks if a user can delete a reply. Users can delete their own replies, and admins can + * delete anyone's. + * + * @param reply The reply to delete. + * @param user The user, or `null` if nobody is signed in. + */ + fun canDeleteReply(reply: ReviewReply, user: User?): Boolean { + return user != null && (reply.authorId == user.deviceId || user.role == UserRole.ADMIN) + } + + /** + * Saves a reply to a review. Spaces around the text are removed. + * + * @param review The review being replied to. + * @param user The user replying, or `null` if nobody is signed in. + * @param text What the user wrote. + * @return `null` if the reply was saved. An error message otherwise. + */ + suspend fun submitReply(review: Review, user: User?, text: String): String? { + if (user == null) { + return "Sign in to reply." + } + val trimmed = text.trim() + if (trimmed.isEmpty()) { + return "Please write a reply." + } + if (trimmed.length > ReviewReply.MAX_TEXT_LENGTH) { + return "Your reply must be at most ${ReviewReply.MAX_TEXT_LENGTH} characters." + } + val reply = ReviewReply(replyRepository.newReplyId(), review.reviewId, user.deviceId, trimmed) + return try { + replyRepository.add(reply) + null + } catch (_: Exception) { + "Could not send your reply. Please try again." + } + } + + /** + * Deletes a reply. + * + * @param reply The reply to delete. + * @param user The user deleting it, or `null` if nobody is signed in. + * @return `true` if the reply was deleted, `false` if the user cannot delete it or + * deleting it failed. + */ + suspend fun deleteReply(reply: ReviewReply, user: User?): Boolean { + if (!canDeleteReply(reply, user)) { + return false + } + return try { + replyRepository.delete(reply.replyId) + true + } catch (_: Exception) { + false + } + } +} diff --git a/code/app/src/main/java/com/example/lambda_bbb_events/model/repository/ReviewReactionRepository.kt b/code/app/src/main/java/com/example/lambda_bbb_events/model/repository/ReviewReactionRepository.kt new file mode 100644 index 00000000..17d26970 --- /dev/null +++ b/code/app/src/main/java/com/example/lambda_bbb_events/model/repository/ReviewReactionRepository.kt @@ -0,0 +1,43 @@ +package com.example.lambda_bbb_events.model.repository + +import android.util.Log +import com.example.lambda_bbb_events.model.review.ReviewReaction +import com.google.firebase.Firebase +import com.google.firebase.firestore.DocumentSnapshot +import com.google.firebase.firestore.FirebaseFirestore +import com.google.firebase.firestore.FirebaseFirestoreException +import com.google.firebase.firestore.firestore + +/* + * Manages emoji reactions to campsite reviews in Firestore. + */ + +/** + * Handles the data in the Firestore database for the [ReviewReaction] class. + */ +class ReviewReactionRepository( + db: FirebaseFirestore = Firebase.firestore +) : Repository("reviewReactions", db) { + + init { + startListening() + } + + override fun idOf(item: ReviewReaction) = item.reactionId + + override fun fromDocument(document: DocumentSnapshot): ReviewReaction? = + document.toObject(ReviewReaction::class.java)?.takeIf { it.isValid() } + + override fun onListenError(error: FirebaseFirestoreException) { + Log.e("ReviewReactionRepository", "listener error", error) + } + + /** + * Gets every reaction to a review from the cache. + * + * @param reviewId The ID of the review. + * @return The reactions, in no particular order. + */ + fun getReactionsFor(reviewId: String): List = + cached.filter { it.reviewId == reviewId } +} diff --git a/code/app/src/main/java/com/example/lambda_bbb_events/model/repository/ReviewReplyRepository.kt b/code/app/src/main/java/com/example/lambda_bbb_events/model/repository/ReviewReplyRepository.kt new file mode 100644 index 00000000..8f33c938 --- /dev/null +++ b/code/app/src/main/java/com/example/lambda_bbb_events/model/repository/ReviewReplyRepository.kt @@ -0,0 +1,46 @@ +package com.example.lambda_bbb_events.model.repository + +import android.util.Log +import com.example.lambda_bbb_events.model.review.ReviewReply +import com.google.firebase.Firebase +import com.google.firebase.firestore.DocumentSnapshot +import com.google.firebase.firestore.FirebaseFirestore +import com.google.firebase.firestore.FirebaseFirestoreException +import com.google.firebase.firestore.firestore + +/* + * Manages replies to campsite reviews in Firestore. + */ + +/** + * Handles the data in the Firestore database for the [ReviewReply] class. + */ +class ReviewReplyRepository( + db: FirebaseFirestore = Firebase.firestore +) : Repository("reviewReplies", db) { + + init { + startListening() + } + + override fun idOf(item: ReviewReply) = item.replyId + + override fun fromDocument(document: DocumentSnapshot): ReviewReply? = + document.toObject(ReviewReply::class.java)?.takeIf { it.isValid() } + + override fun onListenError(error: FirebaseFirestoreException) { + Log.e("ReviewReplyRepository", "listener error", error) + } + + /** Makes a new, unused ID for a reply. */ + fun newReplyId(): String = collectionRef.document().id + + /** + * Gets every reply to a review from the cache. + * + * @param reviewId The ID of the review. + * @return The replies, in no particular order. + */ + fun getRepliesFor(reviewId: String): List = + cached.filter { it.reviewId == reviewId } +} diff --git a/code/app/src/main/java/com/example/lambda_bbb_events/model/review/ReviewReaction.kt b/code/app/src/main/java/com/example/lambda_bbb_events/model/review/ReviewReaction.kt new file mode 100644 index 00000000..b4581203 --- /dev/null +++ b/code/app/src/main/java/com/example/lambda_bbb_events/model/review/ReviewReaction.kt @@ -0,0 +1,45 @@ +package com.example.lambda_bbb_events.model.review + +import com.google.firebase.firestore.Exclude + +/* + * Defines the emoji reactions users leave on campsite reviews. + */ + +/** + * A user's emoji reaction to a [Review]. Each user has at most one reaction per review. + * + * @property reactionId The unique ID of the reaction, from [ReviewReaction.idFor]. + * @property reviewId The ID of the review reacted to. + * @property reactorId The device ID of the user who reacted. + * @property emoji The emoji the user picked, one of [EMOJIS]. + */ +data class ReviewReaction( + val reactionId: String = "", + val reviewId: String = "", + val reactorId: String = "", + val emoji: String = "" +) { + /** Whether the reaction has the right ID for its review and user, and an allowed emoji. */ + @Exclude + fun isValid(): Boolean { + return reviewId.isNotBlank() && reactorId.isNotBlank() && + reactionId == idFor(reviewId, reactorId) && emoji in EMOJIS + } + + companion object { + /** The emojis users can react with, in the order they are shown. */ + val EMOJIS = listOf("👍", "❤️", "😂", "😮", "😢", "👎") + + /** + * Gets the ID of a user's reaction to a review. It is always the same for the same + * user and review, so reacting again replaces the first reaction. + * + * @param reviewId The ID of the review. + * @param reactorId The device ID of the user. + */ + fun idFor(reviewId: String, reactorId: String): String { + return reviewId + "_" + reactorId + } + } +} diff --git a/code/app/src/main/java/com/example/lambda_bbb_events/model/review/ReviewReply.kt b/code/app/src/main/java/com/example/lambda_bbb_events/model/review/ReviewReply.kt new file mode 100644 index 00000000..5343c52f --- /dev/null +++ b/code/app/src/main/java/com/example/lambda_bbb_events/model/review/ReviewReply.kt @@ -0,0 +1,37 @@ +package com.example.lambda_bbb_events.model.review + +import com.google.firebase.firestore.Exclude +import java.util.Date + +/* + * Defines the replies users write under campsite reviews. + */ + +/** + * A reply to a [Review]. Replies are listed under the review in the order they were written. + * + * @property replyId The unique ID of the reply. + * @property reviewId The ID of the review being replied to. + * @property authorId The device ID of the user who wrote the reply. + * @property text What the user wrote. + * @property repliedAt When the reply was written. + */ +data class ReviewReply( + val replyId: String = "", + val reviewId: String = "", + val authorId: String = "", + val text: String = "", + val repliedAt: Date = Date() +) { + /** Whether the reply has its IDs, and text that is not blank or too long. */ + @Exclude + fun isValid(): Boolean { + return replyId.isNotBlank() && reviewId.isNotBlank() && authorId.isNotBlank() && + text.isNotBlank() && text.length <= MAX_TEXT_LENGTH + } + + companion object { + /** The longest reply, in characters. */ + const val MAX_TEXT_LENGTH = 300 + } +} diff --git a/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/review/ReactableReviewCard.kt b/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/review/ReactableReviewCard.kt new file mode 100644 index 00000000..ecb24316 --- /dev/null +++ b/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/review/ReactableReviewCard.kt @@ -0,0 +1,142 @@ +package com.example.lambda_bbb_events.view.ui.components.review + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.AddReaction +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.layout.onSizeChanged +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.unit.IntSize +import androidx.compose.ui.unit.dp +import com.example.lambda_bbb_events.controller.ReviewReactionController +import com.example.lambda_bbb_events.controller.ReviewReplyController +import com.example.lambda_bbb_events.model.review.Review +import com.example.lambda_bbb_events.model.user.User +import kotlinx.coroutines.launch + +/* + * Shows a campsite review with the emoji reactions around it and the replies under it. + */ + +/** + * The buttons to open the emoji tray and the reply box. + * + * @param onReact Called when the react button is tapped, or `null` to show no button. + * @param onReply Called when the reply button is tapped, or `null` to show no button. + */ +@Composable +private fun ThreadButtons(onReact: (() -> Unit)?, onReply: (() -> Unit)?) { + Row(verticalAlignment = Alignment.CenterVertically) { + if (onReact != null) { + IconButton(onClick = onReact, modifier = Modifier.testTag("addReaction")) { + Icon(Icons.Outlined.AddReaction, contentDescription = "React") + } + } + if (onReply != null) { + TextButton(onClick = onReply, modifier = Modifier.testTag("replyButton")) { + Text("Reply") + } + } + } +} + +/** + * Displays a review card with the emojis users reacted with placed around its edge, and its + * replies under it. Each emoji has its own spot, the same on every screen. Signed-in users can + * pick an emoji from the tray or tap one on the card to pick it too, and picking the emoji they + * already picked removes it. The emoji tray and the reply box stay hidden until their button is + * tapped. Updates by itself when reactions or replies change. + * + * @param review The review to show. + * @param reviewer The user who wrote it, or `null` if their account was deleted. + * @param onDelete Called when the review's delete button is tapped, or `null` to show no button. + * @param user The signed-in user, or `null` if nobody is signed in. + * @param replies Gets, sends, and deletes the replies. + * @param reactions Gets, saves, and removes the reactions. + * @param nameOf Gets a user's name from their device ID, or `null` if their account was deleted. + */ +@Composable +fun ReactableReviewCard( + review: Review, + reviewer: User?, + onDelete: (() -> Unit)?, + user: User?, + replies: ReviewReplyController, + reactions: ReviewReactionController, + nameOf: (String) -> String? +) { + val scope = rememberCoroutineScope() + var cardSize by remember { mutableStateOf(IntSize.Zero) } + var footerHeight by remember { mutableIntStateOf(0) } + var isPicking by rememberSaveable(review.reviewId) { mutableStateOf(false) } + var isReplying by rememberSaveable(review.reviewId) { mutableStateOf(false) } + var error by remember(review.reviewId) { mutableStateOf(null) } + val toggleReaction: (String) -> Unit = { emoji -> + scope.launch { error = if (reactions.toggleReaction(review, user, emoji)) null else "Could not save your reaction." } + } + + Box(modifier = Modifier.onSizeChanged { cardSize = it }) { + ReviewCard(review, reviewer, onDelete) { + Column( + modifier = Modifier + .fillMaxWidth() + .onSizeChanged { footerHeight = it.height }, + verticalArrangement = Arrangement.spacedBy(8.dp) + ) { + for (reply in replies.getReplies(review)) { + ReplyItem( + reply = reply, + authorName = nameOf(reply.authorId), + onDelete = if (replies.canDeleteReply(reply, user)) { + { scope.launch { error = if (replies.deleteReply(reply, user)) null else "Could not delete the reply." } } + } else { + null + } + ) + } + ThreadButtons( + onReact = if (reactions.canReact(user)) ({ isPicking = !isPicking }) else null, + onReply = if (replies.canReply(user)) ({ isReplying = !isReplying }) else null + ) + if (isPicking) { + EmojiTray(onPick = { emoji -> + isPicking = false + toggleReaction(emoji) + }) + } + if (isReplying) { + ReplyComposer(onSend = { text -> replies.submitReply(review, user, text) }, onSent = { isReplying = false }) + } + error?.let { + Text(text = it, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error) + } + } + } + PlacedReactions( + counts = reactions.reactionCounts(review), + mine = reactions.reactionOf(review, user)?.emoji, + spotOf = { emoji -> + spotOnCard(review.reviewId, emoji, cardSize.width.toFloat(), cardSize.height.toFloat(), footerHeight.toFloat()) + }, + onTap = if (reactions.canReact(user)) toggleReaction else null + ) + } +} diff --git a/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/review/ReactionSpots.kt b/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/review/ReactionSpots.kt new file mode 100644 index 00000000..c5480fdb --- /dev/null +++ b/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/review/ReactionSpots.kt @@ -0,0 +1,63 @@ +package com.example.lambda_bbb_events.view.ui.components.review + +import com.example.lambda_bbb_events.model.review.ReviewReaction +import kotlin.random.Random + +/* + * Works out where emoji reactions sit around the edge of a review card. + */ + +/** + * Picks a spot on the edge of a review for an emoji. Each emoji gets its own part of the edge, + * so different emojis never share a spot, and sits at a random place in it. The spots are + * random but come from the review's ID, so they are the same on every screen and every time + * the review is shown. + * + * @param reviewId The ID of the review. + * @param emoji The emoji, one of [ReviewReaction.EMOJIS]. + * @param width How wide the review is. + * @param height How tall the review is. + * @return How far across and down the review the spot is. + */ +internal fun spotAround(reviewId: String, emoji: String, width: Float, height: Float): Pair { + val random = Random(reviewId.hashCode()) + val part = ReviewReaction.EMOJIS.shuffled(random).indexOf(emoji) + val placeInPart = List(ReviewReaction.EMOJIS.size) { 0.2f + 0.6f * random.nextFloat() }[part] + val perimeter = 2 * (width + height) + return pointOnEdge((part + placeInPart) / ReviewReaction.EMOJIS.size * perimeter, width, height) +} + +/** + * Finds a spot on the edge of a review card whose bottom part grows and shrinks. Spots on the + * top and sides are worked out from the part above the bottom part, so they stay put when it + * changes size. Spots on the bottom stay on the bottom edge. + * + * @param reviewId The ID of the review. + * @param emoji The emoji, one of [ReviewReaction.EMOJIS]. + * @param width How wide the card is. + * @param height How tall the whole card is. + * @param growingHeight How tall the bottom part that grows and shrinks is. + * @return How far across and down the card the spot is. + */ +internal fun spotOnCard(reviewId: String, emoji: String, width: Float, height: Float, growingHeight: Float): Pair { + val steadyHeight = height - growingHeight + val (x, y) = spotAround(reviewId, emoji, width, steadyHeight) + return x to if (y == steadyHeight) height else y +} + +/** + * Finds the point on the edge of a rectangle reached by going clockwise from its top left + * corner. + * + * @param distance How far to go along the edge. + * @param width How wide the rectangle is. + * @param height How tall the rectangle is. + */ +private fun pointOnEdge(distance: Float, width: Float, height: Float): Pair { + return when { + distance < width -> distance to 0f + distance < width + height -> width to distance - width + distance < 2 * width + height -> 2 * width + height - distance to height + else -> 0f to 2 * (width + height) - distance + } +} diff --git a/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/review/ReviewCard.kt b/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/review/ReviewCard.kt index 6ee8f78c..259a4664 100644 --- a/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/review/ReviewCard.kt +++ b/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/review/ReviewCard.kt @@ -40,13 +40,15 @@ import java.util.Locale * @param reviewer The user who wrote it, or `null` if their account was deleted. * @param onDelete Called when the delete button is tapped, or `null` to show no button. * @param modifier Customizes the card's layout. + * @param footer Shown at the bottom of the card, such as the review's reactions and replies. */ @Composable fun ReviewCard( review: Review, reviewer: User?, onDelete: (() -> Unit)?, - modifier: Modifier = Modifier + modifier: Modifier = Modifier, + footer: @Composable () -> Unit = {} ) { Card( modifier = modifier @@ -110,6 +112,8 @@ fun ReviewCard( color = MaterialTheme.colorScheme.onSurface ) } + + footer() } } } diff --git a/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/review/ReviewReactions.kt b/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/review/ReviewReactions.kt new file mode 100644 index 00000000..a9fbe8a4 --- /dev/null +++ b/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/review/ReviewReactions.kt @@ -0,0 +1,125 @@ +package com.example.lambda_bbb_events.view.ui.components.review + +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.layout.layout +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import com.example.lambda_bbb_events.model.review.ReviewReaction +import kotlin.math.roundToInt + +/* + * Shows the emoji reactions around a campsite review, and the tray to pick one. + */ + +/** + * Places content so its center is at a point, measured from the parent's top left corner. + * + * @param center Gets how far across and down the point is. It is read while placing, so + * changes only move the content. + */ +private fun Modifier.centeredAt(center: () -> Pair): Modifier = layout { measurable, constraints -> + val placeable = measurable.measure(constraints.copy(minWidth = 0, minHeight = 0)) + layout(placeable.width, placeable.height) { + val (x, y) = center() + placeable.place(x.roundToInt() - placeable.width / 2, y.roundToInt() - placeable.height / 2) + } +} + +/** + * Displays an emoji at its spot on a review, with how many users picked it when more than one + * did. + * + * @param emoji The emoji. + * @param count How many users picked it. + * @param isMine Whether the user picked it, which highlights it. + * @param spot Gets how far across and down the review the emoji goes. + * @param onTap Called when the emoji is tapped, or `null` if it cannot be. + */ +@Composable +private fun PlacedEmoji(emoji: String, count: Int, isMine: Boolean, spot: () -> Pair, onTap: (() -> Unit)?) { + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier + .centeredAt(spot) + .then(if (isMine) Modifier.background(MaterialTheme.colorScheme.secondaryContainer, CircleShape) else Modifier) + .then(if (onTap != null) Modifier.clip(CircleShape).clickable(onClick = onTap) else Modifier) + .padding(horizontal = 2.dp) + .semantics(mergeDescendants = true) {} + .testTag("placedReaction_$emoji") + ) { + Text(text = emoji, style = MaterialTheme.typography.headlineSmall) + if (count > 1) { + Text( + text = count.toString(), + style = MaterialTheme.typography.labelMedium, + fontWeight = FontWeight.Bold, + color = MaterialTheme.colorScheme.onSurface + ) + } + } +} + +/** + * Displays the emojis users reacted to a review with, each at its own spot. Meant to be drawn + * over the review, in a box the size of the review. + * + * @param counts How many users picked each emoji. + * @param mine The emoji the user picked, or `null` if they have not reacted. + * @param spotOf Gets how far across and down the review an emoji goes. + * @param onTap Called with the emoji tapped, or `null` if they cannot be tapped. + */ +@Composable +internal fun PlacedReactions( + counts: Map, + mine: String?, + spotOf: (String) -> Pair, + onTap: ((String) -> Unit)? +) { + for ((emoji, count) in counts) { + PlacedEmoji( + emoji = emoji, + count = count, + isMine = emoji == mine, + spot = { spotOf(emoji) }, + onTap = onTap?.let { { it(emoji) } } + ) + } +} + +/** + * Displays every emoji users can react with side by side. + * + * @param onPick Called with the emoji tapped. + */ +@Composable +internal fun EmojiTray(onPick: (String) -> Unit) { + Row(modifier = Modifier.testTag("emojiTray"), horizontalArrangement = Arrangement.spacedBy(4.dp)) { + for (emoji in ReviewReaction.EMOJIS) { + Box( + contentAlignment = Alignment.Center, + modifier = Modifier + .size(40.dp) + .clip(CircleShape) + .clickable { onPick(emoji) } + .testTag("pickReaction_$emoji") + ) { + Text(emoji, style = MaterialTheme.typography.titleLarge) + } + } + } +} diff --git a/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/review/ReviewReplies.kt b/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/review/ReviewReplies.kt new file mode 100644 index 00000000..f57ffdbe --- /dev/null +++ b/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/review/ReviewReplies.kt @@ -0,0 +1,114 @@ +package com.example.lambda_bbb_events.view.ui.components.review + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.Send +import androidx.compose.material.icons.outlined.Delete +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import com.example.lambda_bbb_events.model.review.ReviewReply +import kotlinx.coroutines.launch + +/* + * Shows the replies under a campsite review, and the box to write one. + */ + +/** + * Displays one reply, indented under its review. + * + * @param reply The reply to show. + * @param authorName The name of who wrote it, or `null` if their account was deleted. + * @param onDelete Called when the delete button is tapped, or `null` to show no button. + */ +@Composable +internal fun ReplyItem(reply: ReviewReply, authorName: String?, onDelete: (() -> Unit)?) { + Row( + modifier = Modifier + .fillMaxWidth() + .padding(start = 16.dp) + .background(MaterialTheme.colorScheme.surfaceVariant, RoundedCornerShape(8.dp)) + .padding(start = 12.dp, top = 8.dp, bottom = 8.dp) + .testTag("replyItem"), + verticalAlignment = Alignment.CenterVertically + ) { + Column(modifier = Modifier.weight(1f)) { + Text( + text = authorName ?: "Deleted user", + style = MaterialTheme.typography.labelLarge, + fontWeight = FontWeight.Bold, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + Text(text = reply.text, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + if (onDelete != null) { + IconButton(onClick = onDelete, modifier = Modifier.testTag("deleteReply")) { + Icon(Icons.Outlined.Delete, contentDescription = "Delete reply", tint = MaterialTheme.colorScheme.error) + } + } + } +} + +/** + * A box to write a reply and send it. + * + * @param onSend Sends what was written. Returns `null` if it was sent, or an error message. + * @param onSent Called once the reply was sent. + */ +@Composable +internal fun ReplyComposer(onSend: suspend (String) -> String?, onSent: () -> Unit) { + var draft by rememberSaveable { mutableStateOf("") } + var isSending by remember { mutableStateOf(false) } + var error by remember { mutableStateOf(null) } + val scope = rememberCoroutineScope() + + OutlinedTextField( + value = draft, + onValueChange = { draft = it.take(ReviewReply.MAX_TEXT_LENGTH) }, + placeholder = { Text("Write a reply") }, + isError = error != null, + supportingText = error?.let { { Text(it) } }, + enabled = !isSending, + trailingIcon = { + IconButton( + onClick = { + isSending = true + scope.launch { + error = onSend(draft) + isSending = false + if (error == null) { + draft = "" + onSent() + } + } + }, + enabled = draft.isNotBlank() && !isSending, + modifier = Modifier.testTag("sendReply") + ) { + Icon(Icons.AutoMirrored.Filled.Send, contentDescription = "Send reply") + } + }, + modifier = Modifier + .fillMaxWidth() + .testTag("replyInput") + ) +} diff --git a/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/review/ReviewSection.kt b/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/review/ReviewSection.kt index 42c8cf92..07bc9064 100644 --- a/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/review/ReviewSection.kt +++ b/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/review/ReviewSection.kt @@ -128,7 +128,7 @@ fun ReviewSection( val shownReviews = if (showAll) reviews else reviews.take(REVIEWS_SHOWN_AT_FIRST) for (review in shownReviews) { - ReviewCard( + ReactableReviewCard( review = review, reviewer = controllers.users.getCachedUser(review.reviewerId), onDelete = if (controllers.reviews.canDelete(review, user)) { @@ -138,7 +138,11 @@ fun ReviewSection( } } else { null - } + }, + user = user, + replies = controllers.reviewReplies, + reactions = controllers.reviewReactions, + nameOf = { controllers.users.getCachedUser(it)?.name } ) } diff --git a/code/app/src/test/java/com/example/lambda_bbb_events/controller/ReviewReactionControllerUnitTest.kt b/code/app/src/test/java/com/example/lambda_bbb_events/controller/ReviewReactionControllerUnitTest.kt new file mode 100644 index 00000000..819305bb --- /dev/null +++ b/code/app/src/test/java/com/example/lambda_bbb_events/controller/ReviewReactionControllerUnitTest.kt @@ -0,0 +1,104 @@ +package com.example.lambda_bbb_events.controller + +import com.example.lambda_bbb_events.model.repository.ReviewReactionRepository +import com.example.lambda_bbb_events.model.review.Review +import com.example.lambda_bbb_events.model.review.ReviewReaction +import com.example.lambda_bbb_events.model.user.Entrant +import io.mockk.coEvery +import io.mockk.coVerify +import io.mockk.every +import io.mockk.just +import io.mockk.mockk +import io.mockk.runs +import io.mockk.slot +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +class ReviewReactionControllerUnitTest { + private val reactions = mockk() + private val controller = ReviewReactionController(reactions) + + private val review = Review("site-1_user-1", "site-1", "user-1", rating = 4) + private val ed = Entrant(deviceId = "user-2") + private val edsReactionId = ReviewReaction.idFor(review.reviewId, "user-2") + private val savedReaction = slot() + + private fun reaction(userId: String, emoji: String) = + ReviewReaction(ReviewReaction.idFor(review.reviewId, userId), review.reviewId, userId, emoji) + + @Before + fun setup() { + coEvery { reactions.add(capture(savedReaction)) } just runs + coEvery { reactions.delete(any()) } just runs + every { reactions.getCached(any()) } returns null + } + + @Test + fun signedOutUsersCannotReact() = runTest { + assertFalse(controller.canReact(null)) + assertFalse(controller.react(review, null, "👍")) + assertFalse(controller.removeReaction(review, null)) + } + + @Test + fun reactionCountsFollowTheEmojiOrderAndSkipUnused() { + every { reactions.getReactionsFor(review.reviewId) } returns listOf( + reaction("a", "😂"), reaction("b", "👍"), reaction("c", "😂") + ) + + assertEquals(listOf("👍" to 1, "😂" to 2), controller.reactionCounts(review).toList()) + } + + @Test + fun reactingSavesTheEmoji() = runTest { + assertTrue(controller.react(review, ed, "👍")) + + assertEquals(reaction("user-2", "👍"), savedReaction.captured) + } + + @Test + fun reactingAgainReplacesTheFirstReaction() = runTest { + every { reactions.getCached(edsReactionId) } returns reaction("user-2", "👍") + + assertTrue(controller.react(review, ed, "😂")) + + assertEquals(reaction("user-2", "😂"), savedReaction.captured) + } + + @Test + fun removingAReactionDeletesIt() = runTest { + assertTrue(controller.removeReaction(review, ed)) + + coVerify(exactly = 1) { reactions.delete(edsReactionId) } + } + + @Test + fun togglingANewEmojiSavesIt() = runTest { + every { reactions.getCached(edsReactionId) } returns reaction("user-2", "👍") + + assertTrue(controller.toggleReaction(review, ed, "😂")) + + assertEquals(reaction("user-2", "😂"), savedReaction.captured) + coVerify(exactly = 0) { reactions.delete(any()) } + } + + @Test + fun togglingTheSameEmojiRemovesIt() = runTest { + every { reactions.getCached(edsReactionId) } returns reaction("user-2", "👍") + + assertTrue(controller.toggleReaction(review, ed, "👍")) + + coVerify(exactly = 1) { reactions.delete(edsReactionId) } + coVerify(exactly = 0) { reactions.add(any()) } + } + + @Test + fun emojiOutsideTheSetIsRefused() = runTest { + assertFalse(controller.react(review, ed, "🔥")) + coVerify(exactly = 0) { reactions.add(any()) } + } +} diff --git a/code/app/src/test/java/com/example/lambda_bbb_events/controller/ReviewReplyControllerUnitTest.kt b/code/app/src/test/java/com/example/lambda_bbb_events/controller/ReviewReplyControllerUnitTest.kt new file mode 100644 index 00000000..ccee542a --- /dev/null +++ b/code/app/src/test/java/com/example/lambda_bbb_events/controller/ReviewReplyControllerUnitTest.kt @@ -0,0 +1,77 @@ +package com.example.lambda_bbb_events.controller + +import com.example.lambda_bbb_events.model.repository.ReviewReplyRepository +import com.example.lambda_bbb_events.model.review.Review +import com.example.lambda_bbb_events.model.review.ReviewReply +import com.example.lambda_bbb_events.model.user.Admin +import com.example.lambda_bbb_events.model.user.Entrant +import io.mockk.coEvery +import io.mockk.coVerify +import io.mockk.every +import io.mockk.just +import io.mockk.mockk +import io.mockk.runs +import io.mockk.slot +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import java.util.Date + +class ReviewReplyControllerUnitTest { + private val replies = mockk() + private val controller = ReviewReplyController(replies) + + private val review = Review("site-1_user-1", "site-1", "user-1", rating = 4) + private val ed = Entrant(deviceId = "user-2") + private val admin = Admin(deviceId = "admin-1") + private val savedReply = slot() + + @Before + fun setup() { + every { replies.newReplyId() } returns "reply-1" + coEvery { replies.add(capture(savedReply)) } just runs + coEvery { replies.delete(any()) } just runs + } + + @Test + fun repliesAreOldestFirst() { + val older = ReviewReply("a", review.reviewId, "user-2", "First", Date(1_000)) + val newer = ReviewReply("b", review.reviewId, "user-3", "Second", Date(2_000)) + every { replies.getRepliesFor(review.reviewId) } returns listOf(newer, older) + + assertEquals(listOf(older, newer), controller.getReplies(review)) + } + + @Test + fun replyIsTrimmedAndSaved() = runTest { + assertNull(controller.submitReply(review, ed, " Agreed! ")) + + assertEquals(ReviewReply("reply-1", review.reviewId, "user-2", "Agreed!", savedReply.captured.repliedAt), savedReply.captured) + } + + @Test + fun blankOrTooLongRepliesAreRefused() = runTest { + assertEquals("Please write a reply.", controller.submitReply(review, ed, " ")) + assertTrue(controller.submitReply(review, ed, "a".repeat(ReviewReply.MAX_TEXT_LENGTH + 1))!!.contains("at most")) + coVerify(exactly = 0) { replies.add(any()) } + } + + @Test + fun signedOutUsersCannotReply() = runTest { + assertFalse(controller.canReply(null)) + assertEquals("Sign in to reply.", controller.submitReply(review, null, "Hi")) + } + + @Test + fun onlyTheAuthorOrAnAdminCanDeleteAReply() = runTest { + val reply = ReviewReply("reply-1", review.reviewId, "user-2", "Hi") + + assertFalse(controller.deleteReply(reply, Entrant(deviceId = "someone-else"))) + assertTrue(controller.deleteReply(reply, ed)) + assertTrue(controller.deleteReply(reply, admin)) + } +} diff --git a/code/app/src/test/java/com/example/lambda_bbb_events/model/review/ReviewReactionUnitTest.kt b/code/app/src/test/java/com/example/lambda_bbb_events/model/review/ReviewReactionUnitTest.kt new file mode 100644 index 00000000..a13409ae --- /dev/null +++ b/code/app/src/test/java/com/example/lambda_bbb_events/model/review/ReviewReactionUnitTest.kt @@ -0,0 +1,33 @@ +package com.example.lambda_bbb_events.model.review + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class ReviewReactionUnitTest { + private val reaction = ReviewReaction("site-1_user-1_user-2", "site-1_user-1", "user-2", "👍") + + @Test + fun idCombinesTheReviewAndUser() { + assertEquals("site-1_user-1_user-2", ReviewReaction.idFor("site-1_user-1", "user-2")) + } + + @Test + fun everyAllowedEmojiIsValid() { + for (emoji in ReviewReaction.EMOJIS) { + assertTrue(emoji, reaction.copy(emoji = emoji).isValid()) + } + } + + @Test + fun otherEmojiIsNotValid() { + assertFalse(reaction.copy(emoji = "🔥").isValid()) + assertFalse(reaction.copy(emoji = "").isValid()) + } + + @Test + fun wrongIdIsNotValid() { + assertFalse(reaction.copy(reactionId = "other").isValid()) + } +} diff --git a/code/app/src/test/java/com/example/lambda_bbb_events/model/review/ReviewReplyUnitTest.kt b/code/app/src/test/java/com/example/lambda_bbb_events/model/review/ReviewReplyUnitTest.kt new file mode 100644 index 00000000..4433c9d6 --- /dev/null +++ b/code/app/src/test/java/com/example/lambda_bbb_events/model/review/ReviewReplyUnitTest.kt @@ -0,0 +1,32 @@ +package com.example.lambda_bbb_events.model.review + +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class ReviewReplyUnitTest { + private val reply = ReviewReply("reply-1", "site-1_user-1", "user-2", "Agreed!") + + @Test + fun completeReplyIsValid() { + assertTrue(reply.isValid()) + } + + @Test + fun blankTextIsNotValid() { + assertFalse(reply.copy(text = " ").isValid()) + } + + @Test + fun textAtTheLimitIsValidButLongerIsNot() { + assertTrue(reply.copy(text = "a".repeat(ReviewReply.MAX_TEXT_LENGTH)).isValid()) + assertFalse(reply.copy(text = "a".repeat(ReviewReply.MAX_TEXT_LENGTH + 1)).isValid()) + } + + @Test + fun missingIdsAreNotValid() { + assertFalse(reply.copy(replyId = "").isValid()) + assertFalse(reply.copy(reviewId = "").isValid()) + assertFalse(reply.copy(authorId = "").isValid()) + } +} diff --git a/code/app/src/test/java/com/example/lambda_bbb_events/view/ui/components/review/ReactionSpotsUnitTest.kt b/code/app/src/test/java/com/example/lambda_bbb_events/view/ui/components/review/ReactionSpotsUnitTest.kt new file mode 100644 index 00000000..1ef2ac87 --- /dev/null +++ b/code/app/src/test/java/com/example/lambda_bbb_events/view/ui/components/review/ReactionSpotsUnitTest.kt @@ -0,0 +1,51 @@ +package com.example.lambda_bbb_events.view.ui.components.review + +import com.example.lambda_bbb_events.model.review.ReviewReaction +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class ReactionSpotsUnitTest { + @Test + fun spotIsOnTheEdgeOfTheReview() { + for (review in 1..20) { + for (emoji in ReviewReaction.EMOJIS) { + val (x, y) = spotAround("site-$review", emoji, 300f, 200f) + assertTrue("($x, $y)", x in 0f..300f && y in 0f..200f) + assertTrue("($x, $y)", x == 0f || x == 300f || y == 0f || y == 200f) + } + } + } + + @Test + fun spotIsTheSameEveryTime() { + assertEquals(spotAround("site-1_user-1", "👍", 300f, 200f), spotAround("site-1_user-1", "👍", 300f, 200f)) + } + + @Test + fun everyEmojiHasItsOwnSpot() { + val spots = ReviewReaction.EMOJIS.map { spotAround("site-1_user-1", it, 300f, 200f) } + assertEquals(ReviewReaction.EMOJIS.size, spots.toSet().size) + } + + @Test + fun spotsChangeFromReviewToReview() { + val spots = (1..10).map { spotAround("site-$it", "👍", 300f, 200f) } + assertTrue(spots.toSet().size > 1) + } + + @Test + fun onlyBottomSpotsMoveWhenTheBottomPartGrows() { + for (review in 1..20) { + for (emoji in ReviewReaction.EMOJIS) { + val small = spotOnCard("site-$review", emoji, 300f, 200f, 40f) + val grown = spotOnCard("site-$review", emoji, 300f, 260f, 100f) + if (small.second == 200f) { + assertEquals(small.first to 260f, grown) + } else { + assertEquals(small, grown) + } + } + } + } +} diff --git a/code/firestore.rules b/code/firestore.rules index 41ddbd9f..529e3f65 100644 --- a/code/firestore.rules +++ b/code/firestore.rules @@ -109,6 +109,38 @@ service cloud.firestore { ); } + // One emoji reaction per user and review. + match /reviewReactions/{id} { + + allow read, delete: if true; + + allow create, update: + if id == request.resource.data.reviewId + + '_' + + request.resource.data.reactorId + && request.resource.data.reactionId == id + && request.resource.data.emoji in ['👍', '❤️', '😂', '😮', '😢', '👎'] + && exists( + /databases/$(database)/documents/reviews/$(request.resource.data.reviewId) + ); + } + + // Replies to reviews. + match /reviewReplies/{id} { + + allow read, delete: if true; + + allow create, update: + if request.resource.data.replyId == id + && request.resource.data.authorId is string + && request.resource.data.text is string + && request.resource.data.text.size() > 0 + && request.resource.data.text.size() <= 300 + && exists( + /databases/$(database)/documents/reviews/$(request.resource.data.reviewId) + ); + } + // Campsite management. match /campsites/{id} { allow read, write: if true; @@ -197,5 +229,15 @@ service cloud.firestore { allow delete: if false; } + + // Firebase Cloud Messaging registration tokens. + // Prevents unauthorized clients from reading, + // modifying, or deleting device registration tokens. + // + // Trusted backend services using the Firebase Admin SDK + // can still access this collection. + match /fcmTokens/{deviceId} { + allow read, write: if false; + } } }