From 36e759430dc50d3fcd0c4c4d3b5cccebb768e690 Mon Sep 17 00:00:00 2001 From: Francis Lau Date: Thu, 19 Nov 2026 10:53:26 -0500 Subject: [PATCH 1/5] Show user profile and barcode sheet on Account page Add a profile card with the user's photo, name, and email, plus a Barcode button that opens a Dining Barcode sheet (barcode rendering comes later). - Fetch the profile from POST /users/get-profile after financials load, renewing an expired GET session and retrying once on 401 - Join first/middle/last name and decode the base64 photo - Keep the profile in memory only and clear it on logout; exclude the response body from network logs, per the backend's no-cache/no-log note --- .../android/eatery/data/NetworkingApi.kt | 7 + .../android/eatery/data/models/UserProfile.kt | 57 ++++ .../data/repositories/UserRepository.kt | 33 +++ .../android/eatery/di/NetworkingModule.kt | 7 +- .../eatery/ui/components/login/AccountPage.kt | 251 +++++++++++++++++- .../eatery/ui/screens/ProfileScreen.kt | 13 +- .../eatery/ui/viewmodels/LoginViewModel.kt | 20 +- app/src/main/res/values/strings.xml | 3 + 8 files changed, 380 insertions(+), 11 deletions(-) create mode 100644 app/src/main/java/com/cornellappdev/android/eatery/data/models/UserProfile.kt diff --git a/app/src/main/java/com/cornellappdev/android/eatery/data/NetworkingApi.kt b/app/src/main/java/com/cornellappdev/android/eatery/data/NetworkingApi.kt index 81566a69..e526bcb7 100644 --- a/app/src/main/java/com/cornellappdev/android/eatery/data/NetworkingApi.kt +++ b/app/src/main/java/com/cornellappdev/android/eatery/data/NetworkingApi.kt @@ -17,6 +17,7 @@ import com.cornellappdev.android.eatery.data.models.NotificationIds import com.cornellappdev.android.eatery.data.models.RefreshRequest import com.cornellappdev.android.eatery.data.models.ReportSendBody import com.cornellappdev.android.eatery.data.models.SessionID +import com.cornellappdev.android.eatery.data.models.UserProfileResponse import com.cornellappdev.android.eatery.data.models.UserSettings import com.cornellappdev.android.eatery.data.models.UserSettingsUpdate import retrofit2.http.Body @@ -122,6 +123,12 @@ interface NetworkApi { @Body sessionId: SessionID ): BarcodeResponse + /** The user's name, email, and photo. Never cache or log the response. */ + @POST("/users/get-profile") + suspend fun getProfile( + @Body sessionId: SessionID + ): UserProfileResponse + @GET("/users/favorites/matches") suspend fun getFavoriteMatches(): List } \ No newline at end of file diff --git a/app/src/main/java/com/cornellappdev/android/eatery/data/models/UserProfile.kt b/app/src/main/java/com/cornellappdev/android/eatery/data/models/UserProfile.kt new file mode 100644 index 00000000..7cdfcfed --- /dev/null +++ b/app/src/main/java/com/cornellappdev/android/eatery/data/models/UserProfile.kt @@ -0,0 +1,57 @@ +package com.cornellappdev.android.eatery.data.models + +import android.graphics.BitmapFactory +import android.util.Base64 +import androidx.compose.ui.graphics.ImageBitmap +import androidx.compose.ui.graphics.asImageBitmap +import com.squareup.moshi.Json +import com.squareup.moshi.JsonClass + +/** + * Basic identity info for the logged-in user, displayed on the Account page. + * Any field may be null when the backend doesn't provide it. + * + * Held in memory only: the backend asks that profile data not be cached or logged. + */ +data class UserProfile( + val name: String? = null, + val email: String? = null, + val photo: ImageBitmap? = null, +) + +/** Response body of `POST /users/get-profile`. Every field may be null. */ +@JsonClass(generateAdapter = true) +data class UserProfileResponse( + @Json(name = "firstName") val firstName: String? = null, + @Json(name = "middleName") val middleName: String? = null, + @Json(name = "lastName") val lastName: String? = null, + @Json(name = "email") val email: String? = null, + @Json(name = "photo") val photo: ProfilePhoto? = null, +) + +/** A profile photo as base64-encoded image bytes of type [mimeType] (e.g. `image/jpeg`). */ +@JsonClass(generateAdapter = true) +data class ProfilePhoto( + @Json(name = "mimeType") val mimeType: String? = null, + @Json(name = "data") val data: String? = null, +) + +/** + * Converts the backend response into a [UserProfile], joining the name parts and decoding + * the photo. A photo that fails to decode is dropped rather than failing the whole profile. + */ +fun UserProfileResponse.toUserProfile(): UserProfile = UserProfile( + name = listOf(firstName, middleName, lastName) + .filterNot { it.isNullOrBlank() } + .joinToString(" ") + .ifEmpty { null }, + email = email?.takeIf { it.isNotBlank() }, + photo = photo?.toImageBitmap(), +) + +private fun ProfilePhoto.toImageBitmap(): ImageBitmap? { + if (mimeType?.startsWith("image/") == false) return null + val bytes = runCatching { Base64.decode(data ?: return null, Base64.DEFAULT) } + .getOrNull() ?: return null + return BitmapFactory.decodeByteArray(bytes, 0, bytes.size)?.asImageBitmap() +} diff --git a/app/src/main/java/com/cornellappdev/android/eatery/data/repositories/UserRepository.kt b/app/src/main/java/com/cornellappdev/android/eatery/data/repositories/UserRepository.kt index bc946b4f..7ff47fb2 100644 --- a/app/src/main/java/com/cornellappdev/android/eatery/data/repositories/UserRepository.kt +++ b/app/src/main/java/com/cornellappdev/android/eatery/data/repositories/UserRepository.kt @@ -10,13 +10,18 @@ import com.cornellappdev.android.eatery.data.models.Result import com.cornellappdev.android.eatery.data.models.SessionID import com.cornellappdev.android.eatery.data.models.Transaction import com.cornellappdev.android.eatery.data.models.User +import com.cornellappdev.android.eatery.data.models.UserProfile import com.cornellappdev.android.eatery.data.models.toTransactionAccountType +import com.cornellappdev.android.eatery.data.models.toUserProfile +import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.firstOrNull import kotlinx.coroutines.flow.update +import kotlinx.coroutines.withContext +import retrofit2.HttpException import java.time.LocalDateTime import java.time.ZonedDateTime import java.time.format.DateTimeFormatter @@ -55,6 +60,14 @@ class UserRepository @Inject constructor( /** Expose whether a user is currently logged in. Delegates to UserPreferencesRepository. */ val isLoggedInFlow: Flow = userPreferencesRepository.isLoggedInFlow + private val _userProfile: MutableStateFlow = MutableStateFlow(UserProfile()) + + /** + * The logged-in user's name, email, and profile picture. Kept in memory only, since the + * backend asks that profile data not be cached. + */ + val userProfileFlow: StateFlow = _userProfile.asStateFlow() + private val useLocalFavorites = BuildConfig.USE_LOCAL_FAVORITES suspend fun updateFavorites(): Result { @@ -205,6 +218,25 @@ class UserRepository @Inject constructor( financials } + /** + * Fetches the user's name, email, and photo. If the GET session has expired (401), gets a + * new session with the saved PIN and tries once more, like [getFinancials]. + */ + suspend fun getProfile(): Result = resultOfNetworkCall { + val response = try { + networkApi.getProfile(sessionId = SessionID(getAccountRepository.getSessionId())) + } catch (e: HttpException) { + if (e.code() != 401) throw e + val pin = getAccountRepository.getPin() ?: throw e + val refreshResult = getAccountRepository.refreshLogin(pin = pin) + if (refreshResult is Result.Error) throw IllegalStateException("refreshLogin failed") + networkApi.getProfile(sessionId = SessionID(getAccountRepository.getSessionId())) + } + val profile = withContext(Dispatchers.Default) { response.toUserProfile() } + _userProfile.value = profile + profile + } + private fun String.toLocalDateTime(): LocalDateTime? { val inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSX") return runCatching { @@ -220,6 +252,7 @@ class UserRepository @Inject constructor( getAccountRepository.clearSessionId() getAccountRepository.clearBarcodeData() getAccountRepository.setIsLoggedIn(false) + _userProfile.value = UserProfile() } suspend fun hasOnboarded(): Boolean = diff --git a/app/src/main/java/com/cornellappdev/android/eatery/di/NetworkingModule.kt b/app/src/main/java/com/cornellappdev/android/eatery/di/NetworkingModule.kt index 24aad3bd..ea19e7aa 100644 --- a/app/src/main/java/com/cornellappdev/android/eatery/di/NetworkingModule.kt +++ b/app/src/main/java/com/cornellappdev/android/eatery/di/NetworkingModule.kt @@ -28,8 +28,11 @@ import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object NetworkModule { - /** Paths whose bodies hold payment credentials, so only the method, URL and status are logged. */ - private val CREDENTIAL_PATHS = setOf("/financials/barcode") + /** + * Paths whose bodies hold payment credentials or personal info, so only the method, URL and + * status are logged. + */ + private val CREDENTIAL_PATHS = setOf("/financials/barcode", "/users/get-profile") @Singleton @Provides diff --git a/app/src/main/java/com/cornellappdev/android/eatery/ui/components/login/AccountPage.kt b/app/src/main/java/com/cornellappdev/android/eatery/ui/components/login/AccountPage.kt index 9bc777fa..a926ae7b 100644 --- a/app/src/main/java/com/cornellappdev/android/eatery/ui/components/login/AccountPage.kt +++ b/app/src/main/java/com/cornellappdev/android/eatery/ui/components/login/AccountPage.kt @@ -2,14 +2,18 @@ package com.cornellappdev.android.eatery.ui.components.login import androidx.annotation.StringRes import androidx.compose.animation.AnimatedContent +import androidx.compose.foundation.Image import androidx.compose.foundation.background +import androidx.compose.foundation.border 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.Spacer +import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.navigationBarsPadding import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.statusBarsPadding @@ -22,6 +26,7 @@ import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.filled.KeyboardArrowDown +import androidx.compose.material.icons.outlined.QrCodeScanner import androidx.compose.material.icons.outlined.Settings import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults @@ -38,22 +43,29 @@ import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.res.imageResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.vectorResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.cornellappdev.android.eatery.R import com.cornellappdev.android.eatery.data.models.AccountBalances import com.cornellappdev.android.eatery.data.models.MealSwipePlan import com.cornellappdev.android.eatery.data.models.TransactionAccountType +import com.cornellappdev.android.eatery.data.models.UserProfile import com.cornellappdev.android.eatery.ui.components.general.SearchBar import com.cornellappdev.android.eatery.ui.components.home.BottomSheetContent import com.cornellappdev.android.eatery.ui.theme.EateryBlueTypography @@ -61,6 +73,7 @@ import com.cornellappdev.android.eatery.ui.theme.currentColors import com.cornellappdev.android.eatery.ui.viewmodels.state.DisplayTransaction import com.cornellappdev.android.eatery.util.DualModePreview import com.cornellappdev.android.eatery.util.EateryPreview +import kotlinx.coroutines.launch import kotlin.math.abs @OptIn( @@ -74,10 +87,14 @@ fun AccountPage( filteredTransactions: List, filterText: String, onQueryChanged: (String) -> Unit, - updateAccountFilter: (TransactionAccountType) -> Unit + updateAccountFilter: (TransactionAccountType) -> Unit, + userProfile: UserProfile = UserProfile(), ) { val modalBottomSheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true) var showBottomSheet by remember { mutableStateOf(false) } + val barcodeSheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true) + var showBarcodeSheet by remember { mutableStateOf(false) } + val scope = rememberCoroutineScope() var sheetContent by remember { mutableStateOf(BottomSheetContent.ACCOUNT_TYPE) } AccountPageContent( onSettingsClicked, @@ -88,8 +105,30 @@ fun AccountPage( setFilterText = onQueryChanged, filteredTransactions, setSheetContent = { sheetContent = it }, + userProfile = userProfile, + onBarcodeClicked = { showBarcodeSheet = true }, ) + if (showBarcodeSheet) { + ModalBottomSheet( + onDismissRequest = { showBarcodeSheet = false }, + sheetState = barcodeSheetState, + containerColor = currentColors.backgroundDefault, + contentColor = currentColors.textPrimary, + shape = RoundedCornerShape(topStart = 12.dp, topEnd = 12.dp), + dragHandle = null + ) { + DiningBarcodeSheet( + userProfile = userProfile, + onClose = { + scope.launch { barcodeSheetState.hide() }.invokeOnCompletion { + if (!barcodeSheetState.isVisible) showBarcodeSheet = false + } + } + ) + } + } + if (showBottomSheet) { ModalBottomSheet( onDismissRequest = { showBottomSheet = false }, @@ -133,7 +172,9 @@ private fun AccountPageContent( filterText: String, setFilterText: (String) -> Unit, filteredTransactions: List, - setSheetContent: (BottomSheetContent) -> Unit + setSheetContent: (BottomSheetContent) -> Unit, + userProfile: UserProfile = UserProfile(), + onBarcodeClicked: () -> Unit = {} ) { val innerListState = rememberLazyListState() val isFirstVisible by remember { derivedStateOf { innerListState.firstVisibleItemIndex > 1 } } @@ -144,6 +185,23 @@ private fun AccountPageContent( ) { AccountPageHeader(isFirstVisible, onSettingsClicked) LazyColumn(state = innerListState) { + item { + ProfileCard( + userProfile = userProfile, + onBarcodeClicked = onBarcodeClicked, + modifier = Modifier.padding(16.dp) + ) + } + + item { + Spacer( + modifier = Modifier + .fillMaxWidth() + .height(16.dp) + .background(currentColors.accentPrimary) + ) + } + item { (Column(modifier = Modifier.padding(horizontal = 16.dp)) { Column { @@ -211,6 +269,179 @@ private fun AccountPageContent( } } +/** + * Card at the top of the Account page showing the user's profile picture, name, and email, + * plus a button to show their barcode. + */ +@Composable +private fun ProfileCard( + userProfile: UserProfile, + onBarcodeClicked: () -> Unit, + modifier: Modifier = Modifier +) { + Column( + modifier = modifier + .fillMaxWidth() + .clip(RoundedCornerShape(12.dp)) + .background(currentColors.backgroundSecondary) + .padding(16.dp) + ) { + Row(verticalAlignment = Alignment.CenterVertically) { + ProfilePicture( + photo = userProfile.photo, + modifier = Modifier.size(64.dp) + ) + Column(modifier = Modifier.padding(start = 16.dp)) { + userProfile.name?.let { + Text( + text = it, + style = EateryBlueTypography.h5, + color = currentColors.oppTextPrimary, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + } + userProfile.email?.let { + Text( + text = it, + style = EateryBlueTypography.subtitle2, + color = currentColors.oppTextPrimary, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + } + } + } + Button( + onClick = onBarcodeClicked, + modifier = Modifier + .fillMaxWidth() + .padding(top = 16.dp), + shape = RoundedCornerShape(8.dp), + colors = ButtonDefaults.buttonColors( + containerColor = currentColors.backgroundDefault, + contentColor = currentColors.textPrimary + ) + ) { + Icon( + imageVector = Icons.Outlined.QrCodeScanner, + contentDescription = null, + modifier = Modifier.size(18.dp) + ) + Text( + text = stringResource(R.string.account_barcode), + style = EateryBlueTypography.button, + modifier = Modifier.padding(start = 8.dp) + ) + } + } +} + +/** + * Bottom sheet showing the user's dining barcode beneath their name and email. + */ +@Composable +private fun DiningBarcodeSheet( + userProfile: UserProfile, + onClose: () -> Unit +) { + Column( + modifier = Modifier + .fillMaxWidth() + .navigationBarsPadding() + .padding(start = 16.dp, end = 16.dp, top = 24.dp, bottom = 32.dp) + ) { + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically + ) { + Text( + text = stringResource(R.string.account_dining_barcode), + style = EateryBlueTypography.h4, + color = currentColors.textPrimary, + modifier = Modifier.weight(1f) + ) + IconButton( + onClick = onClose, + modifier = Modifier + .size(40.dp) + .background(color = currentColors.accentPrimary, shape = CircleShape) + ) { + Icon( + Icons.Default.Close, + contentDescription = stringResource(R.string.close), + tint = currentColors.textPrimary + ) + } + } + Column( + modifier = Modifier + .padding(top = 16.dp) + .fillMaxWidth() + .clip(RoundedCornerShape(8.dp)) + .border(1.dp, currentColors.borderDefault, RoundedCornerShape(8.dp)) + ) { + Row( + modifier = Modifier + .fillMaxWidth() + .background(currentColors.backgroundSecondary) + .padding(horizontal = 12.dp, vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically + ) { + ProfilePicture( + photo = userProfile.photo, + modifier = Modifier.size(40.dp) + ) + Column(modifier = Modifier.padding(start = 12.dp)) { + userProfile.name?.let { + Text( + text = it, + style = EateryBlueTypography.h5, + color = currentColors.oppTextPrimary, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + } + userProfile.email?.let { + Text( + text = it, + style = EateryBlueTypography.subtitle2, + color = currentColors.oppTextPrimary, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + } + } + } + // TODO: render the dining barcode here. + Box( + modifier = Modifier + .fillMaxWidth() + .height(96.dp) + .background(currentColors.backgroundDefault) + ) + } + } +} + +@Composable +private fun ProfilePicture(photo: ImageBitmap?, modifier: Modifier = Modifier) { + Box( + modifier = modifier + .clip(CircleShape) + .background(currentColors.backgroundDefault) + ) { + photo?.let { + Image( + bitmap = it, + contentDescription = stringResource(R.string.a11y_profile_picture), + contentScale = ContentScale.Crop, + modifier = Modifier.fillMaxSize() + ) + } + } +} + @Composable private fun TransactionsHeader( accountFilter: TransactionAccountType, @@ -621,7 +852,21 @@ private fun AccountPagePreview() = EateryPreview { formattedDate = "2:00 PM · Monday, October 2" ) ), - setSheetContent = {} + setSheetContent = {}, + userProfile = previewUserProfile() ) } +@DualModePreview +@Composable +private fun DiningBarcodeSheetPreview() = EateryPreview { + DiningBarcodeSheet(userProfile = previewUserProfile(), onClose = {}) +} + +/** Sample profile for previews, with a bundled image standing in for the user's photo. */ +@Composable +private fun previewUserProfile() = UserProfile( + name = "Jane Doe", + email = "jd123@cornell.edu", + photo = ImageBitmap.imageResource(R.drawable.blank_eatery_square) +) diff --git a/app/src/main/java/com/cornellappdev/android/eatery/ui/screens/ProfileScreen.kt b/app/src/main/java/com/cornellappdev/android/eatery/ui/screens/ProfileScreen.kt index 13b1efd9..f5f2d440 100644 --- a/app/src/main/java/com/cornellappdev/android/eatery/ui/screens/ProfileScreen.kt +++ b/app/src/main/java/com/cornellappdev/android/eatery/ui/screens/ProfileScreen.kt @@ -9,6 +9,7 @@ import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.cornellappdev.android.eatery.data.models.AccountBalances import com.cornellappdev.android.eatery.data.models.TransactionAccountType +import com.cornellappdev.android.eatery.data.models.UserProfile import com.cornellappdev.android.eatery.ui.components.general.NetworkErrorToast import com.cornellappdev.android.eatery.ui.components.login.AccountPage import com.cornellappdev.android.eatery.ui.components.login.LoginPage @@ -48,7 +49,8 @@ fun ProfileScreen( filterText = uiState.filterText, filteredTransactions = uiState.filteredTransactions, onQueryChanged = loginViewModel::setQuery, - updateAccountFilter = loginViewModel::updateAccountFilter + updateAccountFilter = loginViewModel::updateAccountFilter, + userProfile = uiState.userProfile ) } @@ -66,7 +68,8 @@ private fun ProfileScreenContent( onSettingsClicked: () -> Unit, filteredTransactions: List, onQueryChanged: (String) -> Unit, - updateAccountFilter: (TransactionAccountType) -> Unit + updateAccountFilter: (TransactionAccountType) -> Unit, + userProfile: UserProfile = UserProfile() ) { Box( modifier = Modifier @@ -90,7 +93,8 @@ private fun ProfileScreenContent( filteredTransactions = filteredTransactions, filterText = filterText, onQueryChanged = onQueryChanged, - updateAccountFilter = updateAccountFilter + updateAccountFilter = updateAccountFilter, + userProfile = userProfile ) } } @@ -145,7 +149,8 @@ private fun ProfileScreenAccountPreview() = EateryPreview { ) ), onQueryChanged = {}, - updateAccountFilter = {} + updateAccountFilter = {}, + userProfile = UserProfile(name = "Wonjin Eum", email = "we46@cornell.edu") ) } diff --git a/app/src/main/java/com/cornellappdev/android/eatery/ui/viewmodels/LoginViewModel.kt b/app/src/main/java/com/cornellappdev/android/eatery/ui/viewmodels/LoginViewModel.kt index 731c99c6..b631319b 100644 --- a/app/src/main/java/com/cornellappdev/android/eatery/ui/viewmodels/LoginViewModel.kt +++ b/app/src/main/java/com/cornellappdev/android/eatery/ui/viewmodels/LoginViewModel.kt @@ -8,6 +8,7 @@ import com.cornellappdev.android.eatery.data.models.Result import com.cornellappdev.android.eatery.data.models.Transaction import com.cornellappdev.android.eatery.data.models.TransactionAccountType import com.cornellappdev.android.eatery.data.models.User +import com.cornellappdev.android.eatery.data.models.UserProfile import com.cornellappdev.android.eatery.data.repositories.GETAccountRepository import com.cornellappdev.android.eatery.data.repositories.UserRepository import com.cornellappdev.android.eatery.ui.viewmodels.state.DisplayTransaction @@ -37,6 +38,7 @@ class LoginViewModel @Inject constructor( val accountFilter: TransactionAccountType = TransactionAccountType.BRBS, val filterText: String = "", val filteredTransactions: List = emptyList(), + val userProfile: UserProfile = UserProfile(), val error: NetworkUiError? = null ) @@ -77,8 +79,12 @@ class LoginViewModel @Inject constructor( ) } - val uiState = combine(loginDataState, _error) { dataState, error -> - dataState.copy(error = error) + val uiState = combine( + loginDataState, + _error, + userRepository.userProfileFlow + ) { dataState, error, userProfile -> + dataState.copy(error = error, userProfile = userProfile) }.stateIn( scope = viewModelScope, started = SharingStarted.WhileSubscribed(5_000), @@ -189,6 +195,7 @@ class LoginViewModel @Inject constructor( is Result.Success -> { onNetworkSuccess() refreshBarcodeData() + refreshProfile() } is Result.Error -> onNetworkFailure(NetworkAction.GetFinancials, result.error) } @@ -201,4 +208,13 @@ class LoginViewModel @Inject constructor( private fun refreshBarcodeData() { viewModelScope.launch { getAccountRepository.refreshBarcodeData() } } + + /** + * Loads the user's name, email, and photo. Called after financials, which renews an expired + * GET session, so this doesn't race it to refresh the session. A failure leaves the profile + * card empty and shows no error, since the balances already loaded. + */ + private fun refreshProfile() { + viewModelScope.launch { userRepository.getProfile() } + } } diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index e542793f..7de8d193 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -137,6 +137,9 @@ Search for transactions… Past 30 Days Show transactions + Barcode + Dining Barcode + Profile picture Change account type Location permissions are necessary to show you eateries that are the closest to you! From 4650b80a38deccf149c3c15758b8bb92dab5c83a Mon Sep 17 00:00:00 2001 From: Francis Lau Date: Sat, 28 Nov 2026 22:22:42 -0500 Subject: [PATCH 2/5] Render the dining barcode in the barcode sheet Draw the GET barcode as a PDF417 symbol with ZXing, regenerated every 5 seconds from the cached credentials while the sheet is open, so it works offline. - Show "Barcode unavailable" when no credentials are cached - Load the profile and then refresh the barcode data one after the other, so their session renewals can't invalidate each other - Drop a late profile response if the user logged out or switched accounts while it was in flight - Switch the Account header to the compact title only once the transactions header reaches the top --- app/build.gradle | 3 + .../data/repositories/GETAccountRepository.kt | 10 ++- .../data/repositories/UserRepository.kt | 25 +++++- .../eatery/ui/components/login/AccountPage.kt | 78 +++++++++++++++++-- .../eatery/ui/screens/ProfileScreen.kt | 12 ++- .../eatery/ui/viewmodels/LoginViewModel.kt | 70 ++++++++++++++--- .../ui/viewmodels/state/BarcodeUiState.kt | 18 +++++ .../android/eatery/util/Pdf417Encoder.kt | 48 ++++++++++++ app/src/main/res/values/strings.xml | 1 + .../android/eatery/util/Pdf417EncoderTest.kt | 47 +++++++++++ gradle/libs.versions.toml | 2 + 11 files changed, 287 insertions(+), 27 deletions(-) create mode 100644 app/src/main/java/com/cornellappdev/android/eatery/ui/viewmodels/state/BarcodeUiState.kt create mode 100644 app/src/main/java/com/cornellappdev/android/eatery/util/Pdf417Encoder.kt create mode 100644 app/src/test/java/com/cornellappdev/android/eatery/util/Pdf417EncoderTest.kt diff --git a/app/build.gradle b/app/build.gradle index 4b489df7..2aa53dd0 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -126,6 +126,9 @@ dependencies { // In-app Updates implementation libs.play.app.update implementation libs.play.app.update.ktx + + // Barcode rendering + implementation libs.zxing.core } protobuf { diff --git a/app/src/main/java/com/cornellappdev/android/eatery/data/repositories/GETAccountRepository.kt b/app/src/main/java/com/cornellappdev/android/eatery/data/repositories/GETAccountRepository.kt index d44e0a53..91d00e6c 100644 --- a/app/src/main/java/com/cornellappdev/android/eatery/data/repositories/GETAccountRepository.kt +++ b/app/src/main/java/com/cornellappdev/android/eatery/data/repositories/GETAccountRepository.kt @@ -7,6 +7,7 @@ import com.cornellappdev.android.eatery.data.models.LoginRequest import com.cornellappdev.android.eatery.data.models.Result import com.cornellappdev.android.eatery.data.models.SessionID import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.firstOrNull import javax.inject.Inject import javax.inject.Singleton @@ -77,7 +78,14 @@ class GETAccountRepository @Inject constructor( * Null if they haven't been fetched for the current GET account. */ suspend fun getCachedBarcodeCredentials(): BarcodeCredentials? = - userPreferencesRepository.barcodeCredentialsFlow.firstOrNull() + barcodeCredentialsFlow.firstOrNull() + + /** + * Emits the cached barcode credentials whenever they change, or null when none are cached + * for the current GET account. Works offline. + */ + val barcodeCredentialsFlow: Flow = + userPreferencesRepository.barcodeCredentialsFlow suspend fun clearBarcodeData() = userPreferencesRepository.clearBarcodeData() diff --git a/app/src/main/java/com/cornellappdev/android/eatery/data/repositories/UserRepository.kt b/app/src/main/java/com/cornellappdev/android/eatery/data/repositories/UserRepository.kt index 7ff47fb2..9f74431d 100644 --- a/app/src/main/java/com/cornellappdev/android/eatery/data/repositories/UserRepository.kt +++ b/app/src/main/java/com/cornellappdev/android/eatery/data/repositories/UserRepository.kt @@ -20,6 +20,8 @@ import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.firstOrNull import kotlinx.coroutines.flow.update +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext import retrofit2.HttpException import java.time.LocalDateTime @@ -68,6 +70,9 @@ class UserRepository @Inject constructor( */ val userProfileFlow: StateFlow = _userProfile.asStateFlow() + /** Makes [getProfile]'s session check and write atomic with [logout]. */ + private val profileMutex = Mutex() + private val useLocalFavorites = BuildConfig.USE_LOCAL_FAVORITES suspend fun updateFavorites(): Result { @@ -221,19 +226,31 @@ class UserRepository @Inject constructor( /** * Fetches the user's name, email, and photo. If the GET session has expired (401), gets a * new session with the saved PIN and tries once more, like [getFinancials]. + * + * The profile is dropped if the user logged out or linked another account while the request + * was in flight, so a late response can't show the old account's profile, like + * [GETAccountRepository.refreshBarcodeData]. */ suspend fun getProfile(): Result = resultOfNetworkCall { + var sessionId = getAccountRepository.getSessionId() val response = try { - networkApi.getProfile(sessionId = SessionID(getAccountRepository.getSessionId())) + networkApi.getProfile(sessionId = SessionID(sessionId)) } catch (e: HttpException) { if (e.code() != 401) throw e val pin = getAccountRepository.getPin() ?: throw e val refreshResult = getAccountRepository.refreshLogin(pin = pin) if (refreshResult is Result.Error) throw IllegalStateException("refreshLogin failed") - networkApi.getProfile(sessionId = SessionID(getAccountRepository.getSessionId())) + sessionId = getAccountRepository.getSessionId() + networkApi.getProfile(sessionId = SessionID(sessionId)) } val profile = withContext(Dispatchers.Default) { response.toUserProfile() } - _userProfile.value = profile + // Under the lock, logout either already cleared the session, so the check fails, or + // hasn't started, so it resets the profile after this write. + profileMutex.withLock { + if (!sessionId.isNullOrEmpty() && getAccountRepository.getSessionId() == sessionId) { + _userProfile.value = profile + } + } profile } @@ -247,7 +264,7 @@ class UserRepository @Inject constructor( }.getOrNull() } - suspend fun logout() { + suspend fun logout() = profileMutex.withLock { _loadedUser.value = null getAccountRepository.clearSessionId() getAccountRepository.clearBarcodeData() diff --git a/app/src/main/java/com/cornellappdev/android/eatery/ui/components/login/AccountPage.kt b/app/src/main/java/com/cornellappdev/android/eatery/ui/components/login/AccountPage.kt index a926ae7b..68d1b438 100644 --- a/app/src/main/java/com/cornellappdev/android/eatery/ui/components/login/AccountPage.kt +++ b/app/src/main/java/com/cornellappdev/android/eatery/ui/components/login/AccountPage.kt @@ -49,6 +49,7 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.FilterQuality import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.layout.ContentScale @@ -61,6 +62,7 @@ import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp +import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.cornellappdev.android.eatery.R import com.cornellappdev.android.eatery.data.models.AccountBalances import com.cornellappdev.android.eatery.data.models.MealSwipePlan @@ -70,9 +72,13 @@ import com.cornellappdev.android.eatery.ui.components.general.SearchBar import com.cornellappdev.android.eatery.ui.components.home.BottomSheetContent import com.cornellappdev.android.eatery.ui.theme.EateryBlueTypography import com.cornellappdev.android.eatery.ui.theme.currentColors +import com.cornellappdev.android.eatery.ui.viewmodels.state.BarcodeUiState import com.cornellappdev.android.eatery.ui.viewmodels.state.DisplayTransaction import com.cornellappdev.android.eatery.util.DualModePreview import com.cornellappdev.android.eatery.util.EateryPreview +import com.cornellappdev.android.eatery.util.Pdf417Encoder +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.launch import kotlin.math.abs @@ -89,6 +95,7 @@ fun AccountPage( onQueryChanged: (String) -> Unit, updateAccountFilter: (TransactionAccountType) -> Unit, userProfile: UserProfile = UserProfile(), + barcodeUiState: Flow = flowOf(BarcodeUiState.Unavailable), ) { val modalBottomSheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true) var showBottomSheet by remember { mutableStateOf(false) } @@ -118,8 +125,11 @@ fun AccountPage( shape = RoundedCornerShape(topStart = 12.dp, topEnd = 12.dp), dragHandle = null ) { + // Collected only while the sheet is open, so the barcode refreshes only then. + val barcode by barcodeUiState.collectAsStateWithLifecycle(BarcodeUiState.Loading) DiningBarcodeSheet( userProfile = userProfile, + barcodeUiState = barcode, onClose = { scope.launch { barcodeSheetState.hide() }.invokeOnCompletion { if (!barcodeSheetState.isVisible) showBarcodeSheet = false @@ -163,6 +173,13 @@ fun AccountPage( } } +/** + * Position of the sticky transactions header in the account list, after the profile card, its + * spacer, the balances and their spacer. Once it reaches the top the balances have scrolled off, + * so the page header switches to the compact title. + */ +private const val TRANSACTIONS_HEADER_INDEX = 4 + @Composable private fun AccountPageContent( onSettingsClicked: () -> Unit, @@ -177,13 +194,19 @@ private fun AccountPageContent( onBarcodeClicked: () -> Unit = {} ) { val innerListState = rememberLazyListState() - val isFirstVisible by remember { derivedStateOf { innerListState.firstVisibleItemIndex > 1 } } + val isFirstVisible by remember { + derivedStateOf { + innerListState.firstVisibleItemIndex >= TRANSACTIONS_HEADER_INDEX + } + } Column( modifier = Modifier .fillMaxWidth() .background(currentColors.backgroundDefault) ) { AccountPageHeader(isFirstVisible, onSettingsClicked) + // Adding or removing an item above the transactions header? Update + // TRANSACTIONS_HEADER_INDEX. LazyColumn(state = innerListState) { item { ProfileCard( @@ -343,6 +366,7 @@ private fun ProfileCard( @Composable private fun DiningBarcodeSheet( userProfile: UserProfile, + barcodeUiState: BarcodeUiState, onClose: () -> Unit ) { Column( @@ -413,13 +437,46 @@ private fun DiningBarcodeSheet( } } } - // TODO: render the dining barcode here. - Box( - modifier = Modifier - .fillMaxWidth() - .height(96.dp) - .background(currentColors.backgroundDefault) + DiningBarcode(barcodeUiState) + } + } +} + +/** + * The dining barcode as a PDF417 symbol. Always black on white, even in dark mode, with a white + * margin around it so scanners can find its edges. + */ +@Composable +private fun DiningBarcode(barcodeUiState: BarcodeUiState) { + Box( + modifier = Modifier + .fillMaxWidth() + .height(96.dp) + .background(Color.White) + .padding(horizontal = 16.dp, vertical = 12.dp), + contentAlignment = Alignment.Center + ) { + when (barcodeUiState) { + BarcodeUiState.Loading -> Unit + BarcodeUiState.Unavailable -> Text( + text = stringResource(R.string.account_barcode_unavailable), + style = EateryBlueTypography.subtitle2, + color = Color.Black, + textAlign = TextAlign.Center ) + + is BarcodeUiState.Ready -> { + val image = remember(barcodeUiState.digits) { + Pdf417Encoder.encodeToImageBitmap(barcodeUiState.digits) + } + Image( + bitmap = image, + contentDescription = stringResource(R.string.account_dining_barcode), + modifier = Modifier.fillMaxSize(), + contentScale = ContentScale.Fit, + filterQuality = FilterQuality.None + ) + } } } } @@ -860,7 +917,12 @@ private fun AccountPagePreview() = EateryPreview { @DualModePreview @Composable private fun DiningBarcodeSheetPreview() = EateryPreview { - DiningBarcodeSheet(userProfile = previewUserProfile(), onClose = {}) + DiningBarcodeSheet( + userProfile = previewUserProfile(), + // Fake value from BarcodeGeneratorTest, not a live account. + barcodeUiState = BarcodeUiState.Ready("1700000000102731570695"), + onClose = {} + ) } /** Sample profile for previews, with a bundled image standing in for the user's photo. */ diff --git a/app/src/main/java/com/cornellappdev/android/eatery/ui/screens/ProfileScreen.kt b/app/src/main/java/com/cornellappdev/android/eatery/ui/screens/ProfileScreen.kt index f5f2d440..2624a9c0 100644 --- a/app/src/main/java/com/cornellappdev/android/eatery/ui/screens/ProfileScreen.kt +++ b/app/src/main/java/com/cornellappdev/android/eatery/ui/screens/ProfileScreen.kt @@ -15,9 +15,12 @@ import com.cornellappdev.android.eatery.ui.components.login.AccountPage import com.cornellappdev.android.eatery.ui.components.login.LoginPage import com.cornellappdev.android.eatery.ui.theme.currentColors import com.cornellappdev.android.eatery.ui.viewmodels.LoginViewModel +import com.cornellappdev.android.eatery.ui.viewmodels.state.BarcodeUiState import com.cornellappdev.android.eatery.ui.viewmodels.state.DisplayTransaction import com.cornellappdev.android.eatery.util.DualModePreview import com.cornellappdev.android.eatery.util.EateryPreview +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.flowOf @Composable @@ -50,7 +53,8 @@ fun ProfileScreen( filteredTransactions = uiState.filteredTransactions, onQueryChanged = loginViewModel::setQuery, updateAccountFilter = loginViewModel::updateAccountFilter, - userProfile = uiState.userProfile + userProfile = uiState.userProfile, + barcodeUiState = loginViewModel.barcodeUiState ) } @@ -69,7 +73,8 @@ private fun ProfileScreenContent( filteredTransactions: List, onQueryChanged: (String) -> Unit, updateAccountFilter: (TransactionAccountType) -> Unit, - userProfile: UserProfile = UserProfile() + userProfile: UserProfile = UserProfile(), + barcodeUiState: Flow = flowOf(BarcodeUiState.Unavailable) ) { Box( modifier = Modifier @@ -94,7 +99,8 @@ private fun ProfileScreenContent( filterText = filterText, onQueryChanged = onQueryChanged, updateAccountFilter = updateAccountFilter, - userProfile = userProfile + userProfile = userProfile, + barcodeUiState = barcodeUiState ) } } diff --git a/app/src/main/java/com/cornellappdev/android/eatery/ui/viewmodels/LoginViewModel.kt b/app/src/main/java/com/cornellappdev/android/eatery/ui/viewmodels/LoginViewModel.kt index b631319b..d0d027d4 100644 --- a/app/src/main/java/com/cornellappdev/android/eatery/ui/viewmodels/LoginViewModel.kt +++ b/app/src/main/java/com/cornellappdev/android/eatery/ui/viewmodels/LoginViewModel.kt @@ -3,6 +3,7 @@ package com.cornellappdev.android.eatery.ui.viewmodels import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.cornellappdev.android.eatery.data.models.AccountBalances +import com.cornellappdev.android.eatery.data.models.BarcodeCredentials import com.cornellappdev.android.eatery.data.models.NetworkError import com.cornellappdev.android.eatery.data.models.Result import com.cornellappdev.android.eatery.data.models.Transaction @@ -11,19 +12,30 @@ import com.cornellappdev.android.eatery.data.models.User import com.cornellappdev.android.eatery.data.models.UserProfile import com.cornellappdev.android.eatery.data.repositories.GETAccountRepository import com.cornellappdev.android.eatery.data.repositories.UserRepository +import com.cornellappdev.android.eatery.ui.viewmodels.state.BarcodeUiState import com.cornellappdev.android.eatery.ui.viewmodels.state.DisplayTransaction import com.cornellappdev.android.eatery.ui.viewmodels.state.NetworkAction import com.cornellappdev.android.eatery.ui.viewmodels.state.NetworkUiError +import com.cornellappdev.android.eatery.util.BarcodeGenerator import dagger.hilt.android.lifecycle.HiltViewModel +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.flatMapLatest +import kotlinx.coroutines.flow.flow +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.flow.onStart import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch +import java.time.Instant import java.time.LocalDateTime import java.time.format.DateTimeFormatter import javax.inject.Inject +import kotlin.time.Duration.Companion.seconds @HiltViewModel class LoginViewModel @Inject constructor( @@ -105,6 +117,9 @@ class LoginViewModel @Inject constructor( } companion object { + /** How often the barcode regenerates, matching iOS. Its value encodes the time. */ + private val BARCODE_REFRESH_INTERVAL = 5.seconds + private fun LocalDateTime.formatDate(): String { val outputFormatter = DateTimeFormatter.ofPattern("h:mm a · EEEE, MMMM d") return outputFormatter.format(this) @@ -194,27 +209,60 @@ class LoginViewModel @Inject constructor( when (val result = userRepository.getFinancials()) { is Result.Success -> { onNetworkSuccess() - refreshBarcodeData() - refreshProfile() + refreshProfileAndBarcodeData() } is Result.Error -> onNetworkFailure(NetworkAction.GetFinancials, result.error) } } /** - * Refreshes the cached barcode data while online so the barcode can be generated offline later. - * A failure keeps the existing cache and shows no error, since the balances already loaded. + * Loads the user's name, email, and photo, then refreshes the cached barcode data so the + * barcode can be generated offline later. Runs after financials so it doesn't hold up the + * balances. + * + * Each request renews the GET session if it has expired, so they run one after the other: + * run at once, both could renew the session and invalidate each other's new session ID. + * Failures show no error, since the balances already loaded: the profile card stays empty and + * the existing barcode cache is kept. */ - private fun refreshBarcodeData() { - viewModelScope.launch { getAccountRepository.refreshBarcodeData() } + private fun refreshProfileAndBarcodeData() { + viewModelScope.launch { + userRepository.getProfile() + getAccountRepository.refreshBarcodeData() + } } /** - * Loads the user's name, email, and photo. Called after financials, which renews an expired - * GET session, so this doesn't race it to refresh the session. A failure leaves the profile - * card empty and shows no error, since the balances already loaded. + * The dining barcode, regenerated every [BARCODE_REFRESH_INTERVAL] while collected. Cold: + * collect it only while the barcode is on screen. Uses the cached credentials, so it works + * offline, and updates when a refresh caches new ones. */ - private fun refreshProfile() { - viewModelScope.launch { userRepository.getProfile() } + @OptIn(ExperimentalCoroutinesApi::class) + val barcodeUiState: Flow = getAccountRepository.barcodeCredentialsFlow + .distinctUntilChanged() + .flatMapLatest { credentials -> + if (credentials == null) { + flowOf(BarcodeUiState.Unavailable) + } else { + flow { + while (true) { + emit(generateBarcode(credentials)) + delay(BARCODE_REFRESH_INTERVAL) + } + } + } + } + .onStart { emit(BarcodeUiState.Loading) } + + private fun generateBarcode(credentials: BarcodeCredentials): BarcodeUiState = try { + BarcodeUiState.Ready( + BarcodeGenerator.generateBarcode( + seedHex = credentials.barcodeSeed, + cashlessKey = credentials.patronId, + timestamp = Instant.now().epochSecond + ) + ) + } catch (_: IllegalArgumentException) { + BarcodeUiState.Unavailable } } diff --git a/app/src/main/java/com/cornellappdev/android/eatery/ui/viewmodels/state/BarcodeUiState.kt b/app/src/main/java/com/cornellappdev/android/eatery/ui/viewmodels/state/BarcodeUiState.kt new file mode 100644 index 00000000..aa89773a --- /dev/null +++ b/app/src/main/java/com/cornellappdev/android/eatery/ui/viewmodels/state/BarcodeUiState.kt @@ -0,0 +1,18 @@ +package com.cornellappdev.android.eatery.ui.viewmodels.state + +/** What the dining barcode sheet shows. */ +sealed interface BarcodeUiState { + /** The cached credentials haven't been read yet. */ + data object Loading : BarcodeUiState + + /** + * No barcode can be shown: the credentials haven't been fetched for this account yet, or + * they couldn't be turned into a barcode. + */ + data object Unavailable : BarcodeUiState + + /** The current barcode value. A payment credential: never log it. */ + data class Ready(val digits: String) : BarcodeUiState { + override fun toString() = "Ready(digits=)" + } +} diff --git a/app/src/main/java/com/cornellappdev/android/eatery/util/Pdf417Encoder.kt b/app/src/main/java/com/cornellappdev/android/eatery/util/Pdf417Encoder.kt new file mode 100644 index 00000000..0990f9c6 --- /dev/null +++ b/app/src/main/java/com/cornellappdev/android/eatery/util/Pdf417Encoder.kt @@ -0,0 +1,48 @@ +package com.cornellappdev.android.eatery.util + +import android.graphics.Bitmap +import androidx.compose.ui.graphics.ImageBitmap +import androidx.compose.ui.graphics.asImageBitmap +import com.google.zxing.BarcodeFormat +import com.google.zxing.EncodeHintType +import com.google.zxing.common.BitMatrix +import com.google.zxing.pdf417.PDF417Writer + +/** + * Draws the GET barcode as a PDF417 symbol, the format the dining scanners read. iOS draws the + * same symbol with `CIPDF417BarcodeGenerator`. + */ +object Pdf417Encoder { + private const val BLACK = 0xFF000000.toInt() + private const val WHITE = 0xFFFFFFFF.toInt() + + /** + * Encodes [contents] at its natural size with no quiet zone: one pixel per module across, a + * few pixels per row down. Requesting a wider-than-tall size keeps the symbol horizontal; a + * size this small is never scaled up. The caller must leave a white margin around the drawn + * symbol so scanners can find its edges. + * + * @throws com.google.zxing.WriterException if [contents] can't be encoded + */ + fun encode(contents: String): BitMatrix = PDF417Writer().encode( + contents, + BarcodeFormat.PDF_417, + /* width = */ 2, + /* height = */ 1, + mapOf(EncodeHintType.MARGIN to 0) + ) + + /** + * Returns [contents] as a black-on-white PDF417 image at its natural size. Draw it with + * `FilterQuality.None` so scaling it up keeps the edges sharp. + */ + fun encodeToImageBitmap(contents: String): ImageBitmap = + encode(contents).toBitmap().asImageBitmap() + + private fun BitMatrix.toBitmap(): Bitmap { + val pixels = IntArray(width * height) { index -> + if (get(index % width, index / width)) BLACK else WHITE + } + return Bitmap.createBitmap(pixels, width, height, Bitmap.Config.ARGB_8888) + } +} diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 7de8d193..84c01a9f 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -139,6 +139,7 @@ Show transactions Barcode Dining Barcode + Barcode unavailable. Connect to the internet and reopen your account to load it. Profile picture Change account type diff --git a/app/src/test/java/com/cornellappdev/android/eatery/util/Pdf417EncoderTest.kt b/app/src/test/java/com/cornellappdev/android/eatery/util/Pdf417EncoderTest.kt new file mode 100644 index 00000000..c354e4aa --- /dev/null +++ b/app/src/test/java/com/cornellappdev/android/eatery/util/Pdf417EncoderTest.kt @@ -0,0 +1,47 @@ +package com.cornellappdev.android.eatery.util + +import com.google.zxing.BinaryBitmap +import com.google.zxing.RGBLuminanceSource +import com.google.zxing.common.BitMatrix +import com.google.zxing.common.HybridBinarizer +import com.google.zxing.pdf417.PDF417Reader +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class Pdf417EncoderTest { + private val sampleBarcode = + BarcodeGenerator.generateBarcode("0123456789abcdef", "12345", 1_700_000_000) + + @Test + fun decodesBackToTheBarcodeDigits() { + assertEquals(sampleBarcode, decode(Pdf417Encoder.encode(sampleBarcode))) + } + + @Test + fun symbolIsWiderThanTall() { + val matrix = Pdf417Encoder.encode(sampleBarcode) + assertTrue(matrix.width > matrix.height) + } + + /** Scales [matrix] up and pads it with a white quiet zone, as the UI does, then decodes it. */ + private fun decode(matrix: BitMatrix): String { + val scale = 4 + val margin = 10 * scale + val width = matrix.width * scale + margin * 2 + val height = matrix.height * scale + margin * 2 + val pixels = IntArray(width * height) { index -> + val x = (index % width - margin) + val y = (index / width - margin) + val inside = x in 0 until matrix.width * scale && y in 0 until matrix.height * scale + if (inside && matrix.get(x / scale, y / scale)) BLACK else WHITE + } + val bitmap = BinaryBitmap(HybridBinarizer(RGBLuminanceSource(width, height, pixels))) + return PDF417Reader().decode(bitmap).text + } + + private companion object { + const val BLACK = 0xFF000000.toInt() + const val WHITE = 0xFFFFFFFF.toInt() + } +} diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index b540b962..d35efaa9 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -32,6 +32,7 @@ composeShimmer = "1.5.0" coil = "2.7.0" hiltLifecycleViewmodelCompose = "1.4.0" appUpdate = "2.1.0" +zxing = "3.5.4" [libraries] junit = { module = "junit:junit", version.ref = "junit" } @@ -90,6 +91,7 @@ coil-compose = { module = "io.coil-kt:coil-compose", version.ref = "coil" } play-app-update = { module = "com.google.android.play:app-update", version.ref = "appUpdate" } play-app-update-ktx = { module = "com.google.android.play:app-update-ktx", version.ref = "appUpdate" } +zxing-core = { module = "com.google.zxing:core", version.ref = "zxing" } [plugins] android-application = { id = "com.android.application", version.ref = "agp" } From cf5077b3725322be68fe78773f860dbf92603add Mon Sep 17 00:00:00 2001 From: Francis Lau Date: Sun, 29 Nov 2026 10:09:38 -0500 Subject: [PATCH 3/5] Fetch the profile only when it isn't loaded yet LoginViewModel is recreated on each visit to the Profile screen, but the profile stays in UserRepository until logout, so refetching it every time was wasted work. Logout clears it, so a new account still fetches its own. --- .../android/eatery/ui/viewmodels/LoginViewModel.kt | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/com/cornellappdev/android/eatery/ui/viewmodels/LoginViewModel.kt b/app/src/main/java/com/cornellappdev/android/eatery/ui/viewmodels/LoginViewModel.kt index d0d027d4..b8b20d26 100644 --- a/app/src/main/java/com/cornellappdev/android/eatery/ui/viewmodels/LoginViewModel.kt +++ b/app/src/main/java/com/cornellappdev/android/eatery/ui/viewmodels/LoginViewModel.kt @@ -216,9 +216,13 @@ class LoginViewModel @Inject constructor( } /** - * Loads the user's name, email, and photo, then refreshes the cached barcode data so the - * barcode can be generated offline later. Runs after financials so it doesn't hold up the - * balances. + * Loads the user's name, email, and photo if they aren't loaded yet, then refreshes the cached + * barcode data so the barcode can be generated offline later. Runs after financials so it + * doesn't hold up the balances. + * + * The profile stays in [UserRepository] until logout, so it's fetched once per login rather + * than on every visit to this screen. Logging out clears it, so the next account fetches its + * own. * * Each request renews the GET session if it has expired, so they run one after the other: * run at once, both could renew the session and invalidate each other's new session ID. @@ -227,7 +231,9 @@ class LoginViewModel @Inject constructor( */ private fun refreshProfileAndBarcodeData() { viewModelScope.launch { - userRepository.getProfile() + if (userRepository.userProfileFlow.value == UserProfile()) { + userRepository.getProfile() + } getAccountRepository.refreshBarcodeData() } } From e09a1a88c14ac45e149b8d13cc172f1ffbe7bdfd Mon Sep 17 00:00:00 2001 From: Francis Lau Date: Sun, 29 Nov 2026 10:09:38 -0500 Subject: [PATCH 4/5] Scale the dining barcode by a whole number ContentScale.Fit with FilterQuality.None scaled the barcode by a fractional factor, so modules came out a mix of widths (e.g. 7px and 8px). Draw it at the largest whole-number scale that fits so every module is the same number of pixels. --- .../eatery/ui/components/login/AccountPage.kt | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/com/cornellappdev/android/eatery/ui/components/login/AccountPage.kt b/app/src/main/java/com/cornellappdev/android/eatery/ui/components/login/AccountPage.kt index 68d1b438..5cb1f6e5 100644 --- a/app/src/main/java/com/cornellappdev/android/eatery/ui/components/login/AccountPage.kt +++ b/app/src/main/java/com/cornellappdev/android/eatery/ui/components/login/AccountPage.kt @@ -53,6 +53,7 @@ import androidx.compose.ui.graphics.FilterQuality import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.layout.layout import androidx.compose.ui.res.imageResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.vectorResource @@ -60,6 +61,7 @@ import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.Constraints import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.lifecycle.compose.collectAsStateWithLifecycle @@ -472,8 +474,19 @@ private fun DiningBarcode(barcodeUiState: BarcodeUiState) { Image( bitmap = image, contentDescription = stringResource(R.string.account_dining_barcode), - modifier = Modifier.fillMaxSize(), - contentScale = ContentScale.Fit, + // Scale by a whole number so every module is the same number of pixels wide; + // a fractional scale makes some bars a pixel wider than others. + modifier = Modifier.layout { measurable, constraints -> + val scale = minOf( + constraints.maxWidth / image.width, + constraints.maxHeight / image.height + ).coerceAtLeast(1) + val placeable = measurable.measure( + Constraints.fixed(image.width * scale, image.height * scale) + ) + layout(placeable.width, placeable.height) { placeable.place(0, 0) } + }, + contentScale = ContentScale.FillBounds, filterQuality = FilterQuality.None ) } From 6056a761694116e5d6107b6a8f6c8701cc3f13b4 Mon Sep 17 00:00:00 2001 From: Francis Lau Date: Sun, 29 Nov 2026 10:09:53 -0500 Subject: [PATCH 5/5] Reword the barcode unavailable message --- app/src/main/res/values/strings.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 84c01a9f..e4457b81 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -139,7 +139,7 @@ Show transactions Barcode Dining Barcode - Barcode unavailable. Connect to the internet and reopen your account to load it. + Sorry, barcode unavailable right now. Please try again later! Profile picture Change account type