diff --git a/app/src/androidTest/java/com/afternote/afternote_fe/SettingEditorSaveSignalAndroidTest.kt b/app/src/androidTest/java/com/afternote/afternote_fe/SettingEditorSaveSignalAndroidTest.kt index 670eaaf970..5fb299f9eb 100644 --- a/app/src/androidTest/java/com/afternote/afternote_fe/SettingEditorSaveSignalAndroidTest.kt +++ b/app/src/androidTest/java/com/afternote/afternote_fe/SettingEditorSaveSignalAndroidTest.kt @@ -206,7 +206,6 @@ class SettingEditorSaveSignalAndroidTest { override fun onWithdrawSuccess() = Unit }, - startWithRecipientRegistration = false, ) } } diff --git a/app/src/androidTest/java/com/afternote/afternote_fe/SettingImplementedCoverageAndroidTest.kt b/app/src/androidTest/java/com/afternote/afternote_fe/SettingImplementedCoverageAndroidTest.kt index 98eeb6aaee..0793bab2d9 100644 --- a/app/src/androidTest/java/com/afternote/afternote_fe/SettingImplementedCoverageAndroidTest.kt +++ b/app/src/androidTest/java/com/afternote/afternote_fe/SettingImplementedCoverageAndroidTest.kt @@ -27,6 +27,7 @@ import com.afternote.afternote_fe.test.FailureArtifactRule import com.afternote.core.domain.repository.UserRepository import com.afternote.core.domain.testing.FakeUserRepository import com.afternote.core.ui.Route +import com.afternote.core.ui.SettingStart import com.afternote.core.ui.navigation.FeatureNavigationCallbacks import com.afternote.core.ui.theme.AfternoteTheme import com.afternote.feature.setting.presentation.navigation.SettingExternalActions @@ -90,7 +91,7 @@ class SettingImplementedCoverageAndroidTest { override fun onWithdrawSuccess() = Unit }, - startWithRecipientRegistration = startWithRecipientRegistration, + start = if (startWithRecipientRegistration) SettingStart.RECIPIENT_REGISTRATION else SettingStart.HOME, ) } } @@ -114,7 +115,7 @@ class SettingImplementedCoverageAndroidTest { /** * 루트의 `composable` 이 entry 의 인자를 host 시작점으로 넘기는 한 줄을 실제 루트 * 그래프로 지난다. [launchHost] 는 host 를 직접 띄우므로 그 결선은 이 케이스만 본다 — 인자를 - * 흘리면(`startWithRecipientRegistration = false` 고정) 설정 홈이 첫 화면이 되어 여기서 빨개진다. + * 흘리면(`start = SettingStart.HOME` 고정) 설정 홈이 첫 화면이 되어 여기서 빨개진다. */ @Test fun appNavigation_settingRouteArgumentSelectsRegisterAsFirstScreen() { @@ -126,7 +127,7 @@ class SettingImplementedCoverageAndroidTest { activity.setContent { AfternoteTheme { AppNavigation( - startDestination = Route.Setting(startWithRecipientRegistration = true), + startDestination = Route.Setting(start = SettingStart.RECIPIENT_REGISTRATION), appState = AppState(navController), ) } diff --git a/app/src/main/java/com/afternote/afternote_fe/GlobalApplication.kt b/app/src/main/java/com/afternote/afternote_fe/GlobalApplication.kt index b4dd6a8c0e..c0b9ddfe44 100644 --- a/app/src/main/java/com/afternote/afternote_fe/GlobalApplication.kt +++ b/app/src/main/java/com/afternote/afternote_fe/GlobalApplication.kt @@ -1,13 +1,15 @@ package com.afternote.afternote_fe +import android.app.Activity import android.app.Application +import android.os.Bundle import coil3.ImageLoader import coil3.PlatformContext import coil3.SingletonImageLoader import com.afternote.afternote_fe.messaging.FcmNotificationChannel import com.afternote.afternote_fe.messaging.PushTargetSynchronizer -import com.afternote.afternote_fe.notification.DailyNotificationScheduleSynchronizer import com.afternote.afternote_fe.update.ForceUpdateGate +import com.afternote.core.common.notification.LegacyDailyNotification import com.afternote.core.network.di.CoilImageLoaderEntryPoint import dagger.hilt.android.EntryPointAccessors import dagger.hilt.android.HiltAndroidApp @@ -37,14 +39,6 @@ class GlobalApplication : @Inject lateinit var forceUpdateGate: ForceUpdateGate - /** - * 데일리 알림 예약을 로그인 상태에 맞추는 관찰의 주체 (#2146). - * - * [pushTargetSynchronizer] 와 같은 이유로 여기 있다. 세션 판정이 Hilt 그래프에 있어 Initializer 에서는 못 본다. - */ - @Inject - lateinit var dailyNotificationScheduleSynchronizer: DailyNotificationScheduleSynchronizer - /** Hilt 가 만든 [ImageLoader] 를 Coil 앱 전역 싱글톤으로 등록 — 모든 AsyncImage 가 명시적 imageLoader 없이 이걸 사용. */ override fun newImageLoader(context: PlatformContext): ImageLoader = EntryPointAccessors @@ -54,8 +48,8 @@ class GlobalApplication : override fun onCreate() { super.onCreate() FcmNotificationChannel.create(this) + LegacyDailyNotification.clear(this) startPushTargetSync() - startDailyNotificationSync() startForceUpdateCheck() // 그 밖의 기동 초기화는 startup 패키지의 Initializer 에 둔다. } @@ -73,21 +67,18 @@ class GlobalApplication : * 관찰은 앱 프로세스 수명 동안 유지돼야 해서 이 스코프는 취소하지 않는다. */ private fun startPushTargetSync() { - CoroutineScope(SupervisorJob() + Dispatchers.IO).launch { + val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + scope.launch { pushTargetSynchronizer.observeLogin() } - } - - /** - * 데일리 알림 예약을 로그인 상태에 맞춘다 (#2146). - * - * 자리가 여기인 이유는 [startPushTargetSync] 와 같다. 관찰은 앱 프로세스 수명 동안 유지돼야 해서 - * 이 스코프도 취소하지 않는다. - */ - private fun startDailyNotificationSync() { - CoroutineScope(SupervisorJob() + Dispatchers.IO).launch { - dailyNotificationScheduleSynchronizer.observeLogin() - } + // 시스템 설정에서 알림을 끄거나 켜고 돌아오는 순간을 잡는다 (#2321). 권한이 그대로면 서버 호출이 없다. + registerActivityLifecycleCallbacks( + object : ActivityResumedCallbacks { + override fun onActivityResumed(activity: Activity) { + scope.launch { pushTargetSynchronizer.onForeground() } + } + }, + ) } /** @@ -107,3 +98,24 @@ class GlobalApplication : } } } + +/** [Application.ActivityLifecycleCallbacks] 중 재개만 쓰려고 나머지를 비워 둔다. */ +private interface ActivityResumedCallbacks : Application.ActivityLifecycleCallbacks { + override fun onActivityCreated( + activity: Activity, + savedInstanceState: Bundle?, + ) = Unit + + override fun onActivityStarted(activity: Activity) = Unit + + override fun onActivityPaused(activity: Activity) = Unit + + override fun onActivityStopped(activity: Activity) = Unit + + override fun onActivitySaveInstanceState( + activity: Activity, + outState: Bundle, + ) = Unit + + override fun onActivityDestroyed(activity: Activity) = Unit +} diff --git a/app/src/main/java/com/afternote/afternote_fe/MainViewModel.kt b/app/src/main/java/com/afternote/afternote_fe/MainViewModel.kt index 498cf863d7..629b02900a 100644 --- a/app/src/main/java/com/afternote/afternote_fe/MainViewModel.kt +++ b/app/src/main/java/com/afternote/afternote_fe/MainViewModel.kt @@ -4,8 +4,13 @@ import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.afternote.afternote_fe.notification.NotificationEntryRequest +import com.afternote.afternote_fe.notification.NotificationEntryResolution +import com.afternote.afternote_fe.notification.NotificationNavigation +import com.afternote.afternote_fe.notification.ServerNotificationDestination import com.afternote.core.domain.repository.PendingReceiverInvitationStore import com.afternote.core.domain.repository.auth.AuthRepository +import com.afternote.core.domain.repository.notification.NotificationEntry +import com.afternote.core.domain.repository.notification.NotificationRepository import com.afternote.core.ui.Route import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableStateFlow @@ -13,9 +18,11 @@ import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch +import kotlinx.coroutines.withTimeoutOrNull import javax.inject.Inject @HiltViewModel @@ -24,10 +31,19 @@ class MainViewModel constructor( authRepository: AuthRepository, private val pendingInvitationStore: PendingReceiverInvitationStore, + private val notificationRepository: NotificationRepository, private val savedStateHandle: SavedStateHandle, ) : ViewModel() { private val pendingNotificationEntryState = MutableStateFlow(null) + private val entryNoticeState = MutableStateFlow(null) + + /** + * 앱 진입 보고가 돌려준, 사용자에게 보여 줄 것(쉬운 질문·절차 취소 안내). 보여 줄 게 없으면 null. + * 앱 셸이 보여 주고 [consumeEntryNotice] 로 비운다. + */ + internal val entryNotice: StateFlow = entryNoticeState.asStateFlow() + /** 아직 후속 목적지 adapter가 소비하지 않은 최신 알림 진입 이벤트. */ internal val pendingNotificationEntry: StateFlow = pendingNotificationEntryState.asStateFlow() @@ -94,6 +110,37 @@ class MainViewModel initialValue = null, ) + init { + reportEntryOnLogin(authRepository) + } + + /** + * 로그인이 확정될 때마다(이미 로그인된 채 켜진 경우 포함) 서버에 앱 진입을 한 번 알린다 (#2321). + * + * 이 ViewModel 은 Activity 재생성을 넘어 살아남으므로 회전마다 다시 보내지 않는다. 서버는 이걸로 + * 활동 시각을 갱신해 오래 비운 사용자의 보관 확인 절차를 취소하므로, 실패해도 다음 실행에 다시 + * 보낼 뿐 화면을 막지 않는다. + */ + private fun reportEntryOnLogin(authRepository: AuthRepository) { + viewModelScope.launch { + authRepository.isLoggedIn.distinctUntilChanged().collect { loggedIn -> + if (!loggedIn) { + entryNoticeState.value = null + return@collect + } + notificationRepository + .reportEntry() + .onSuccess { entry -> + if (entry.easyQuestions.isNotEmpty() || entry.procedureCancelled) entryNoticeState.value = entry + } + } + } + } + + internal fun consumeEntryNotice() { + entryNoticeState.value = null + } + /** 스킴 Intent 에서 뽑은 토큰을 보관한다. 같은 Intent 가 재생성으로 다시 와도 같은 값이라 무해하다. */ internal fun enqueueInvitationToken(token: String) { viewModelScope.launch { pendingInvitationStore.save(token) } @@ -130,7 +177,40 @@ class MainViewModel pendingNotificationEntryState.value = null } + /** + * 알림 진입이 지금 열어야 할 곳을 정한다 (#2321). + * + * 서버 알림이면 탭한 시점의 목적지를 서버에 다시 묻는다 — 대상이 지워졌거나 이미 답한 질문일 수 + * 있다. 묻지 못하면(네트워크·시간 초과·오류) 알림이 싣고 온 목적지로 연다. 알림을 눌렀는데 아무 + * 데도 안 가는 편이 더 나쁘다. 읽음 처리는 이동을 기다리게 하지 않는다. + */ + internal suspend fun resolveNotificationEntry(request: NotificationEntryRequest): NotificationEntryResolution { + val fallback = + NotificationEntryResolution( + navigation = + if (request.serverData.isEmpty()) { + NotificationNavigation.Tab(request.destination) + } else { + ServerNotificationDestination.resolve(request.serverData) + }, + ) + val notificationId = request.serverNotificationId ?: return fallback + + viewModelScope.launch { notificationRepository.markRead(notificationId) } + val target = + withTimeoutOrNull(NOTIFICATION_TARGET_TIMEOUT_MILLIS) { + notificationRepository.target(notificationId).getOrNull() + } ?: return fallback + + return NotificationEntryResolution( + navigation = ServerNotificationDestination.resolve(target.data), + deleted = target.deleted, + serverMessage = target.toast, + ) + } + private companion object { + const val NOTIFICATION_TARGET_TIMEOUT_MILLIS = 3_000L const val CONSUMED_NOTIFICATION_IDENTITY_KEY = "consumed_notification_entry_identity" const val SETTLED_INVITATION_TOKEN_KEY = "settled_receiver_invitation_token" const val INVITATION_AWAITING_LOGIN_KEY = "receiver_invitation_awaiting_login" diff --git a/app/src/main/java/com/afternote/afternote_fe/messaging/AfternoteFirebaseMessagingService.kt b/app/src/main/java/com/afternote/afternote_fe/messaging/AfternoteFirebaseMessagingService.kt index 56671eec8c..62c840327c 100644 --- a/app/src/main/java/com/afternote/afternote_fe/messaging/AfternoteFirebaseMessagingService.kt +++ b/app/src/main/java/com/afternote/afternote_fe/messaging/AfternoteFirebaseMessagingService.kt @@ -8,6 +8,8 @@ import androidx.core.app.ActivityCompat import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import com.afternote.afternote_fe.R +import com.afternote.afternote_fe.notification.NotificationIntentContract +import com.afternote.afternote_fe.notification.ServerNotificationDestination import com.afternote.core.common.notification.NotificationDestination import com.afternote.core.common.notification.NotificationPendingIntentFactory import com.google.firebase.messaging.FirebaseMessagingService @@ -53,6 +55,11 @@ class AfternoteFirebaseMessagingService : FirebaseMessagingService() { Log.d(TAG, "FCM installation unregistered") } + /** + * 서버는 Android 로 notification 블록 없이 data-only 로 보낸다 (BE `NOTIFICATION_CONTRACT.md`). + * 그래서 백그라운드·종료 상태에서도 이 콜백이 불리고 앱이 알림을 직접 그린다 — 그래야 탭이 + * [NotificationPendingIntentFactory] 를 거쳐 목적지로 이어진다. + */ override fun onMessageReceived(message: RemoteMessage) { val content = FcmNotificationContentResolver.resolve( @@ -62,7 +69,11 @@ class AfternoteFirebaseMessagingService : FirebaseMessagingService() { fallbackTitle = getString(R.string.fcm_notification_fallback_title), ) ?: return - val occurrenceId = FcmNotificationIdentity.occurrenceId(message.messageId) + val occurrenceId = + FcmNotificationIdentity.occurrenceId( + serverNotificationId = content.serverNotificationId, + messageId = message.messageId, + ) showNotification( content = content, @@ -95,16 +106,14 @@ class AfternoteFirebaseMessagingService : FirebaseMessagingService() { setContentText(body) setStyle(NotificationCompat.BigTextStyle().bigText(body)) } - // 목적지 data 키 계약(Afternote/Afternote-BE#261)이 서기 전까지 FCM 은 홈을 - // 명시한다. 키를 추측해 두면 BE 가 다른 이름을 고르는 순간 조용히 죽는 분기가 - // 남는다 — 계약이 확정되면 여기서 data 를 읽어 NotificationDestination 으로 - // 옮긴다. NotificationPendingIntentFactory .create( context = this@AfternoteFirebaseMessagingService, source = NOTIFICATION_SOURCE, occurrenceId = occurrenceId, - destination = NotificationDestination.HOME, + destination = content.destination, + serverNotificationId = content.serverNotificationId, + serverData = content.serverData, )?.let(::setContentIntent) }.build() @@ -123,18 +132,37 @@ class AfternoteFirebaseMessagingService : FirebaseMessagingService() { private data class FcmNotificationContent( val title: String, val body: String?, + val destination: NotificationDestination, + val serverNotificationId: Long?, + val serverData: Map, ) private object FcmNotificationIdentity { - fun occurrenceId(messageId: String?): String = - messageId - ?.takeIf(String::isNotBlank) + /** + * 서버 알림 ID 가 있으면 그것이 발생 식별자다 — FCM 이 같은 알림을 두 번 넘겨도 트레이에 한 장만 + * 남고, 탭 소비 판정도 서버 알림 하나에 한 번이 된다. 없으면 FCM message id, 그것도 없으면 새 UUID. + */ + fun occurrenceId( + serverNotificationId: Long?, + messageId: String?, + ): String = + serverNotificationId?.let { "notification:$it" } + ?: messageId?.takeIf(String::isNotBlank) ?: UUID.randomUUID().toString() /** NotificationManager의 `(tag, id)` identity를 프로세스 재시작 뒤에도 occurrence별로 유지한다. */ fun notificationTag(occurrenceId: String): String = "fcm:$occurrenceId" } +/** + * FCM data v1 계약(BE `PushPayload`)을 읽는다. 모든 값은 문자열이다. + * + * 제목·본문은 notification 블록이 있으면 그쪽이 우선이다 — 서버는 이제 data 로만 보내지만, 콘솔에서 보낸 + * 시험 메시지처럼 notification 블록을 단 메시지도 그대로 보여 준다. + * + * 목적지는 `schemaVersion` 이 이 앱이 아는 값일 때만 따른다. 모르는 판이면 키 뜻이 바뀌었을 수 있어 + * 홈으로 연다. 알림 자체는 보여 준다 — 사용자에게 안 보이는 쪽이 더 나쁘다. + */ private object FcmNotificationContentResolver { fun resolve( notificationTitle: String?, @@ -146,9 +174,21 @@ private object FcmNotificationContentResolver { val body = notificationBody.nonBlankOrNull() ?: data[KEY_BODY].nonBlankOrNull() if (title == null && body == null) return null + val schemaVersion = data[KEY_SCHEMA_VERSION].nonBlankOrNull() + val knownSchema = schemaVersion == null || schemaVersion == SUPPORTED_SCHEMA_VERSION + val serverData = + if (knownSchema) data.filterKeys(NotificationIntentContract.SERVER_DATA_KEYS::contains) else emptyMap() + return FcmNotificationContent( title = title ?: fallbackTitle, body = body, + destination = ServerNotificationDestination.resolve(serverData).tab, + serverData = serverData, + serverNotificationId = + data[KEY_NOTIFICATION_ID] + .nonBlankOrNull() + ?.toLongOrNull() + ?.takeIf { it > 0L }, ) } @@ -156,4 +196,7 @@ private object FcmNotificationContentResolver { private const val KEY_TITLE = "title" private const val KEY_BODY = "body" + private const val KEY_SCHEMA_VERSION = "schemaVersion" + private const val KEY_NOTIFICATION_ID = "notificationId" + private const val SUPPORTED_SCHEMA_VERSION = "1" } diff --git a/app/src/main/java/com/afternote/afternote_fe/messaging/FirebaseDevicePushTargetProvider.kt b/app/src/main/java/com/afternote/afternote_fe/messaging/FirebaseDevicePushTargetProvider.kt index 9828819856..d811816660 100644 --- a/app/src/main/java/com/afternote/afternote_fe/messaging/FirebaseDevicePushTargetProvider.kt +++ b/app/src/main/java/com/afternote/afternote_fe/messaging/FirebaseDevicePushTargetProvider.kt @@ -42,6 +42,17 @@ class FirebaseDevicePushTargetProvider override suspend fun existingTargetId(): String? = foldFailure(stage = STAGE_INSTALLATION_ID) { installationId() } + /** + * FID 를 지우고 등록 시퀀스를 다시 돌려 새 FID 를 받는다 (#2321). 지운 뒤의 `register()` 가 새 FID 를 + * 만들고, 그 회전은 `onRegistered` 로도 한 번 더 통보된다 — 동기화기가 같은 값 재전송을 거른다. + */ + override suspend fun resetTargetId(): String? = + foldFailure(stage = STAGE_RESET) { + FirebaseInstallations.getInstance().delete().awaitOrNull(stage = STAGE_RESET) + FirebaseMessaging.getInstance().register().awaitOrNull(stage = STAGE_REGISTER) + installationId() + } + private suspend fun installationId(): String? = FirebaseInstallations.getInstance().id.awaitOrNull(stage = STAGE_INSTALLATION_ID) /** @@ -76,3 +87,4 @@ class FirebaseDevicePushTargetProvider private const val STAGE_REGISTER = "fcm_register" private const val STAGE_INSTALLATION_ID = "fcm_installation_id" +private const val STAGE_RESET = "fcm_reset" diff --git a/app/src/main/java/com/afternote/afternote_fe/messaging/PushInstallationIdStore.kt b/app/src/main/java/com/afternote/afternote_fe/messaging/PushInstallationIdStore.kt new file mode 100644 index 0000000000..de922021ca --- /dev/null +++ b/app/src/main/java/com/afternote/afternote_fe/messaging/PushInstallationIdStore.kt @@ -0,0 +1,46 @@ +package com.afternote.afternote_fe.messaging + +import androidx.datastore.core.DataStore +import androidx.datastore.preferences.core.Preferences +import androidx.datastore.preferences.core.edit +import androidx.datastore.preferences.core.stringPreferencesKey +import com.afternote.afternote_fe.messaging.di.PushInstallationDataStore +import kotlinx.coroutines.flow.first +import java.util.UUID +import javax.inject.Inject +import javax.inject.Singleton + +/** + * 이 앱 설치를 가리키는 UUID 를 한 번 만들어 보관한다 (#2321). + * + * 서버는 이 값으로 같은 설치의 권한 보고(`push-installations`)와 토큰 등록(`push-tokens`)을 묶는다. + * FID 는 UUID 형식이 아니고 회전도 하므로 그 자리를 대신하지 못한다. + * + * 수명은 [com.afternote.core.datastore.StoreScope.DEVICE] 다. 계정이 아니라 설치에 붙는 값이라 + * 로그아웃으로 지워지면 같은 기기가 서버에 새 설치로 쌓인다. 백업에서는 빠진다 — `datastore/` + * 디렉터리 전체가 백업 제외라(#1876) 새 기기로 복원돼도 옛 설치를 사칭하지 않는다. + */ +interface PushInstallationIdStore { + suspend fun installationId(): String +} + +@Singleton +class DataStorePushInstallationIdStore + @Inject + constructor( + @param:PushInstallationDataStore private val dataStore: DataStore, + ) : PushInstallationIdStore { + override suspend fun installationId(): String { + dataStore.data.first()[INSTALLATION_ID]?.let { return it } + // edit 은 원자적이라 두 호출이 동시에 들어와도 먼저 쓴 값 하나만 남는다. + return dataStore + .edit { prefs -> + if (prefs[INSTALLATION_ID] == null) prefs[INSTALLATION_ID] = UUID.randomUUID().toString() + }[INSTALLATION_ID] + .let(::checkNotNull) + } + + private companion object { + val INSTALLATION_ID = stringPreferencesKey("installation_id") + } + } diff --git a/app/src/main/java/com/afternote/afternote_fe/messaging/PushPermissionReader.kt b/app/src/main/java/com/afternote/afternote_fe/messaging/PushPermissionReader.kt new file mode 100644 index 0000000000..0ccfd68629 --- /dev/null +++ b/app/src/main/java/com/afternote/afternote_fe/messaging/PushPermissionReader.kt @@ -0,0 +1,32 @@ +package com.afternote.afternote_fe.messaging + +import android.content.Context +import androidx.core.app.NotificationManagerCompat +import com.afternote.core.domain.push.PushPermission +import dagger.hilt.android.qualifiers.ApplicationContext +import javax.inject.Inject +import javax.inject.Singleton + +/** 지금 이 앱의 알림이 사용자에게 보이는지 읽는다 (#2321). */ +interface PushPermissionReader { + fun current(): PushPermission +} + +/** + * `POST_NOTIFICATIONS` 런타임 권한이 아니라 [NotificationManagerCompat.areNotificationsEnabled] 를 본다. + * API 33 미만에는 런타임 권한이 없지만 사용자가 시스템 설정에서 앱 알림을 끌 수 있고, 33 이상에서는 + * 이 값이 런타임 권한 거부까지 함께 반영한다. 서버가 알고 싶은 것은 「알림이 보이는가」 하나다. + */ +@Singleton +class SystemPushPermissionReader + @Inject + constructor( + @param:ApplicationContext private val context: Context, + ) : PushPermissionReader { + override fun current(): PushPermission = + if (NotificationManagerCompat.from(context).areNotificationsEnabled()) { + PushPermission.GRANTED + } else { + PushPermission.DENIED + } + } diff --git a/app/src/main/java/com/afternote/afternote_fe/messaging/PushTargetSynchronizer.kt b/app/src/main/java/com/afternote/afternote_fe/messaging/PushTargetSynchronizer.kt index 50883c9336..cd2579b9fe 100644 --- a/app/src/main/java/com/afternote/afternote_fe/messaging/PushTargetSynchronizer.kt +++ b/app/src/main/java/com/afternote/afternote_fe/messaging/PushTargetSynchronizer.kt @@ -2,6 +2,7 @@ package com.afternote.afternote_fe.messaging import com.afternote.core.common.reporting.ErrorReporter import com.afternote.core.domain.push.DevicePushTargetProvider +import com.afternote.core.domain.push.PushPermission import com.afternote.core.domain.repository.auth.AuthRepository import com.afternote.core.domain.repository.push.PushTargetRepository import com.afternote.core.domain.result.runCatchingCancellable @@ -28,6 +29,19 @@ import javax.inject.Singleton * 해제(로그아웃)는 여기가 아니라 `AuthRepositoryImpl.logout()` 이 맡는다 — 세션이 아직 살아 있는 * 그 시점에만 서버 호출이 통하기 때문이다. 여기서는 로그아웃을 보면 캐시만 비워, 다음 로그인이 * 다시 등록하도록 한다. + * + * ### 알림 권한 (#2321) + * + * 서버는 OS 권한을 읽지 못해 앱이 보고한 값으로 권한 거부 기기의 푸시를 건너뛴다. 그래서 로그인 + * 확정과 [onForeground] 때 권한을 읽어, 직전에 보고한 값과 다르면 `push-installations` 로 보고하고 + * 알고 있는 식별자를 새 권한으로 다시 등록한다. 사용자가 시스템 설정에서 알림을 끄고 돌아오는 경로가 + * 이 [onForeground] 다. 등록 중복 판정도 (식별자, 권한) 쌍으로 한다 — 권한만 바뀐 재등록은 보내야 한다. + * + * ### 무효 식별자 (#2321) + * + * 서버가 등록 응답에 `requiresReset` 을 실으면 그 식별자로 보낸 발송이 FCM 에서 UNREGISTERED 로 + * 거절됐다는 뜻이다. 같은 값을 다시 보내도 풀리지 않으므로 프로세스당 한 번 새 식별자를 발급받아 + * 등록한다. 발급은 FCM 을 기다리므로 반드시 [mutex] 밖에서 한다(위 교착 근거). */ @Singleton class PushTargetSynchronizer @@ -36,11 +50,22 @@ class PushTargetSynchronizer private val authRepository: AuthRepository, private val devicePushTargetProvider: DevicePushTargetProvider, private val pushTargetRepository: PushTargetRepository, + private val installationIdStore: PushInstallationIdStore, + private val permissionReader: PushPermissionReader, private val errorReporter: ErrorReporter, ) { private val mutex = Mutex() - private var lastRegistered: String? = null + /** 서버가 받아 준 마지막 등록. 같은 쌍은 다시 보내지 않는다. */ + private var lastRegistered: Registration? = null + + /** 등록을 시도한 마지막 식별자. 등록이 실패했어도 남겨 [onForeground] 가 다시 시도한다. */ + private var knownTargetId: String? = null + + private var lastReportedPermission: PushPermission? = null + + /** 이 프로세스에서 이미 새 식별자 발급을 시도했다. 서버가 계속 무효라 해도 무한히 돌지 않는다. */ + private var resetAttempted = false /** * 로그인 상태를 계속 지켜본다. 앱 프로세스가 사는 동안 돈다. @@ -55,9 +80,14 @@ class PushTargetSynchronizer .collect { isLoggedIn -> runCatchingCancellable { if (isLoggedIn) { + syncPermission() registerCurrentTargetId() } else { - mutex.withLock { lastRegistered = null } + mutex.withLock { + lastRegistered = null + knownTargetId = null + lastReportedPermission = null + } } }.onFailure { error -> errorReporter.recordFailure(error, mapOf("stage" to STAGE_OBSERVE_LOGIN)) @@ -80,6 +110,35 @@ class PushTargetSynchronizer } } + /** + * 앱이 앞으로 나올 때. 그사이 시스템 설정에서 알림 권한이 바뀌었으면 보고하고 다시 등록한다. + * 로그인 상태가 아니면 아무것도 하지 않는다. 권한이 그대로면 서버 호출도 없다. + */ + suspend fun onForeground() { + runCatchingCancellable { + if (isLoggedIn()) syncPermission() + }.onFailure { error -> + errorReporter.recordFailure(error, mapOf("stage" to STAGE_FOREGROUND)) + } + } + + private suspend fun syncPermission() { + mutex + .withLock { + val permission = permissionReader.current() + val installationId = installationIdStore.installationId() + if (lastReportedPermission != permission) { + pushTargetRepository + .reportPermission(installationId, permission) + .onSuccess { lastReportedPermission = permission } + .onFailure { error -> + errorReporter.recordFailure(error, mapOf("stage" to STAGE_REPORT_PERMISSION)) + } + } + knownTargetId?.let { targetId -> registerLocked(targetId, installationId, permission) } ?: false + }.let { needsReset -> if (needsReset) resetTargetId() } + } + /** * 기기 식별자 조회는 Firebase SDK 를 그대로 타므로 **동기 예외**로 실패할 수 있다 * (`FirebaseApp` 미초기화 등). 그 갈래를 여기서 닫아 두면 위 `collect` 는 관찰만 이어 간다. @@ -93,19 +152,61 @@ class PushTargetSynchronizer registerOnce(targetId) } - /** 같은 값을 연달아 보내지 않는다 — 서버 동시 upsert 가 500 을 내기 때문이다. */ private suspend fun registerOnce(targetId: String) { - mutex.withLock { - if (lastRegistered == targetId) return@withLock - pushTargetRepository - .register(targetId) - .onSuccess { lastRegistered = targetId } + val needsReset = + mutex.withLock { + registerLocked( + targetId = targetId, + installationId = installationIdStore.installationId(), + permission = permissionReader.current(), + ) + } + if (needsReset) resetTargetId() + } + + /** 새 식별자를 받아 등록한다. FCM 을 기다리므로 [mutex] 밖에서만 부른다. */ + private suspend fun resetTargetId() { + val newTargetId = + runCatchingCancellable { devicePushTargetProvider.resetTargetId() } .onFailure { error -> - errorReporter.recordFailure(error, mapOf("stage" to STAGE_REGISTER)) + errorReporter.recordFailure(error, mapOf("stage" to STAGE_RESET)) + }.getOrNull() ?: return + registerOnce(newTargetId) + } + + /** + * 같은 값을 연달아 보내지 않는다 — 서버 동시 upsert 가 500 을 내기 때문이다. [mutex] 안에서만 부른다. + * + * @return 서버가 이 식별자를 무효라 했고 이 프로세스에서 아직 새로 발급받아 보지 않았으면 true. + */ + private suspend fun registerLocked( + targetId: String, + installationId: String, + permission: PushPermission, + ): Boolean { + knownTargetId = targetId + val registration = Registration(targetId, permission) + if (lastRegistered == registration) return false + var needsReset = false + pushTargetRepository + .register(targetId, installationId, permission) + .onSuccess { result -> + lastRegistered = registration + if (result.requiresReset && !resetAttempted) { + resetAttempted = true + needsReset = true } - } + }.onFailure { error -> + errorReporter.recordFailure(error, mapOf("stage" to STAGE_REGISTER)) + } + return needsReset } + private data class Registration( + val targetId: String, + val permission: PushPermission, + ) + private suspend fun isLoggedIn(): Boolean = runCatchingCancellable { authRepository.getAccessToken().getOrNull() != null @@ -116,3 +217,6 @@ private const val STAGE_REGISTER = "push_target_register" private const val STAGE_DEVICE_ID = "push_target_device_id" private const val STAGE_OBSERVE_LOGIN = "push_target_observe_login" private const val STAGE_TARGET_ROTATED = "push_target_rotated" +private const val STAGE_REPORT_PERMISSION = "push_permission_report" +private const val STAGE_FOREGROUND = "push_target_foreground" +private const val STAGE_RESET = "push_target_reset" diff --git a/app/src/main/java/com/afternote/afternote_fe/messaging/di/PushTargetModule.kt b/app/src/main/java/com/afternote/afternote_fe/messaging/di/PushTargetModule.kt index 340f01b7bf..3057257d8a 100644 --- a/app/src/main/java/com/afternote/afternote_fe/messaging/di/PushTargetModule.kt +++ b/app/src/main/java/com/afternote/afternote_fe/messaging/di/PushTargetModule.kt @@ -1,13 +1,27 @@ package com.afternote.afternote_fe.messaging.di +import androidx.datastore.core.DataStore +import androidx.datastore.preferences.core.Preferences +import com.afternote.afternote_fe.messaging.DataStorePushInstallationIdStore import com.afternote.afternote_fe.messaging.FirebaseDevicePushTargetProvider +import com.afternote.afternote_fe.messaging.PushInstallationIdStore +import com.afternote.afternote_fe.messaging.PushPermissionReader +import com.afternote.afternote_fe.messaging.SystemPushPermissionReader +import com.afternote.core.datastore.LocalStoreRegistry +import com.afternote.core.datastore.StoreScope import com.afternote.core.domain.push.DevicePushTargetProvider import dagger.Binds import dagger.Module +import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent +import javax.inject.Qualifier import javax.inject.Singleton +@Qualifier +@Retention(AnnotationRetention.BINARY) +annotation class PushInstallationDataStore + /** * 식별자 발급 수단(Firebase)은 `app` 에만 있으므로 코어 계약의 구현도 여기서 바인딩한다 (#1493). */ @@ -17,4 +31,23 @@ internal abstract class PushTargetModule { @Binds @Singleton abstract fun bindDevicePushTargetProvider(impl: FirebaseDevicePushTargetProvider): DevicePushTargetProvider + + @Binds + @Singleton + abstract fun bindPushInstallationIdStore(impl: DataStorePushInstallationIdStore): PushInstallationIdStore + + @Binds + @Singleton + abstract fun bindPushPermissionReader(impl: SystemPushPermissionReader): PushPermissionReader +} + +@Module +@InstallIn(SingletonComponent::class) +internal object PushInstallationDataStoreModule { + @Provides + @Singleton + @PushInstallationDataStore + fun providePushInstallationDataStore(registry: LocalStoreRegistry): DataStore = + // name 은 저장 파일명 계약 — 바꾸면 같은 기기가 서버에 새 설치로 쌓인다 (#912 필수 주의). + registry.store(name = "PushInstallation", scope = StoreScope.DEVICE) } diff --git a/app/src/main/java/com/afternote/afternote_fe/navigation/AppNavigation.kt b/app/src/main/java/com/afternote/afternote_fe/navigation/AppNavigation.kt index f2b8dcd1b4..3fccd0d0e1 100644 --- a/app/src/main/java/com/afternote/afternote_fe/navigation/AppNavigation.kt +++ b/app/src/main/java/com/afternote/afternote_fe/navigation/AppNavigation.kt @@ -3,6 +3,8 @@ package com.afternote.afternote_fe.navigation import android.app.Activity import android.content.Context import android.content.ContextWrapper +import android.content.Intent +import android.provider.Settings import androidx.compose.animation.ContentTransform import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.WindowInsetsSides @@ -27,6 +29,7 @@ import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext +import androidx.core.app.NotificationManagerCompat import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel import androidx.lifecycle.Lifecycle import androidx.lifecycle.compose.LifecycleEventEffect @@ -38,6 +41,7 @@ import androidx.navigation.compose.currentBackStackEntryAsState import androidx.navigation.compose.rememberNavController import androidx.navigation3.runtime.entryProvider import com.afternote.afternote_fe.MainViewModel +import com.afternote.afternote_fe.notification.NotificationEntryRequest import com.afternote.afternote_fe.notification.NotificationPermissionEffect import com.afternote.core.ui.Route import com.afternote.core.ui.bottombar.BottomBar @@ -50,6 +54,8 @@ import com.afternote.feature.afternote.presentation.navigation.AfternoteNavHost import com.afternote.feature.afternote.presentation.receiver.navigation.ReceivedAfternoteNavHost import com.afternote.feature.home.presentation.HomeTabScreen import com.afternote.feature.home.presentation.HomeTabViewModel +import com.afternote.feature.home.presentation.notification.NotificationInboxScreen +import com.afternote.feature.home.presentation.notification.rememberHasUnreadNotification import com.afternote.feature.home.presentation.receiver.ReceiverHomeEntry import com.afternote.feature.mindrecord.presentation.navigation.MindRecordNavActions import com.afternote.feature.mindrecord.presentation.navigation.mindRecordNavGraph @@ -163,8 +169,27 @@ fun AppNavigation( } } + val pendingTimeLetterDestinations = appState.pendingTimeLetterDestinations + LaunchedEffect(pendingTimeLetterDestinations, timeLetterEntry) { + val destinations = pendingTimeLetterDestinations ?: return@LaunchedEffect + if (timeLetterEntry != null) { + timeLetterController.popBackStack(TimeLetterRoute.TimeLetterHomeRoute, inclusive = false) + destinations.forEach { destination -> timeLetterController.navigate(destination) } + appState.consumeTimeLetterDestinations(destinations) + } + } + NotificationPermissionEffect(snackbarHostState = snackbarHostState) - NotificationEntryEffect(appState = appState, mainViewModel = mainViewModel) + NotificationEntryEffect( + appState = appState, + mainViewModel = mainViewModel, + snackbarHostState = snackbarHostState, + ) + EntryNoticeEffect( + appState = appState, + mainViewModel = mainViewModel, + snackbarHostState = snackbarHostState, + ) Scaffold( modifier = modifier, @@ -207,10 +232,29 @@ fun AppNavigation( onRetryLoad = { viewModel.loadHomeSummary(isRefresh = true) }, ) var isFirstResume by rememberSaveable { mutableStateOf(true) } + var areNotificationsEnabled by remember { mutableStateOf(true) } LifecycleEventEffect(Lifecycle.Event.ON_RESUME) { if (isFirstResume) isFirstResume = false else viewModel.refreshOnReturn() + areNotificationsEnabled = NotificationManagerCompat.from(context).areNotificationsEnabled() } - HomeTabScreen(uiState = uiState, actions = actions) + HomeTabScreen( + uiState = uiState, + actions = actions, + onNotificationClick = { appState.navigate(Route.NotificationInbox) }, + hasUnreadNotification = rememberHasUnreadNotification(), + onTurnOnNotificationClick = + if (areNotificationsEnabled) null else ({ context.openAppNotificationSettings() }), + ) + } + entry { + NotificationInboxScreen( + onBack = { appState.exitCurrentEntry() }, + onItemClick = { notificationId, data -> + mainViewModel.enqueueNotificationEntry( + NotificationEntryRequest.fromInbox(notificationId = notificationId, data = data), + ) + }, + ) } entry { DisposableEffect(Unit) { onDispose { mindRecordHostGeneration++ } } @@ -251,7 +295,8 @@ fun AppNavigation( SettingNavHost( navigationCallbacks = rootNavigationCallbacks, externalActions = settingExternalActions, - startWithRecipientRegistration = route.startWithRecipientRegistration, + start = route.start, + receiverId = route.receiverId, ) } }, @@ -285,6 +330,15 @@ private fun rememberRootNavigationCallbacks( } } +/** 이 앱의 시스템 알림 설정을 연다. 열 수 없는 기기면 아무것도 하지 않는다. */ +private fun Context.openAppNotificationSettings() { + runCatching { + startActivity( + Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS).putExtra(Settings.EXTRA_APP_PACKAGE, packageName), + ) + } +} + private fun Context.findActivity(): Activity? = when (this) { is Activity -> this diff --git a/app/src/main/java/com/afternote/afternote_fe/navigation/AppNavigationActions.kt b/app/src/main/java/com/afternote/afternote_fe/navigation/AppNavigationActions.kt index d49475a012..f0c658cb14 100644 --- a/app/src/main/java/com/afternote/afternote_fe/navigation/AppNavigationActions.kt +++ b/app/src/main/java/com/afternote/afternote_fe/navigation/AppNavigationActions.kt @@ -6,6 +6,7 @@ import androidx.compose.runtime.remember import androidx.compose.runtime.rememberUpdatedState import androidx.navigation.NavController import com.afternote.core.ui.Route +import com.afternote.core.ui.SettingStart import com.afternote.core.ui.bottombar.BottomNavTab import com.afternote.feature.afternote.presentation.navigation.AfternoteExternalActions import com.afternote.feature.home.presentation.HomeTabActions @@ -179,7 +180,7 @@ fun rememberHomeTabActions( // // 목적지가 등록인지 목록인지는 기획 확정 전이다 (#506) — docs/qa/assumptions.md 참고. // 등록 화면은 설정 로컬 스택 안에 있어 host 에 시작점으로 알린다 (#1695). - appState.navigate(Route.Setting(startWithRecipientRegistration = true)) + appState.navigate(Route.Setting(start = SettingStart.RECIPIENT_REGISTRATION)) } override fun onAnswerClick() { diff --git a/app/src/main/java/com/afternote/afternote_fe/navigation/AppState.kt b/app/src/main/java/com/afternote/afternote_fe/navigation/AppState.kt index 78cbda181b..006a887e48 100644 --- a/app/src/main/java/com/afternote/afternote_fe/navigation/AppState.kt +++ b/app/src/main/java/com/afternote/afternote_fe/navigation/AppState.kt @@ -35,6 +35,10 @@ class AppState( var pendingMindRecordDestination: Any? by mutableStateOf(null) private set + /** 타임레터 탭 NavHost 가 붙은 뒤 탭 홈 위에 차례로 쌓을 화면들 (#2321). */ + var pendingTimeLetterDestinations: List? by mutableStateOf(null) + private set + val backStack: NavBackStack get() = when (activeStack) { @@ -85,6 +89,20 @@ class AppState( if (pendingMindRecordDestination == destination) pendingMindRecordDestination = null } + /** + * 타임레터 탭으로 옮기고 탭 홈 위에 [destinations] 를 쌓게 한다. 탭 NavHost 는 탭이 보일 때 붙으므로 + * 실제 이동은 앱 셸이 컨트롤러를 얻은 뒤 한다 — 마음의 기록 탭과 같은 방식이다. + */ + fun navigateToTimeLetterDestinations(destinations: List) { + pendingTimeLetterDestinations = destinations + activeStack = AppStack.TIMELETTER + timeLetterBackStack.popUpTo(Route.TimeLetter) + } + + fun consumeTimeLetterDestinations(destinations: List) { + if (pendingTimeLetterDestinations == destinations) pendingTimeLetterDestinations = null + } + internal fun initializeLegacyStartDestination(route: Route) { if (startDestinationInitialized) return startDestinationInitialized = true @@ -145,6 +163,7 @@ class AppState( homeBackStack.clear() homeBackStack.add(Route.Home) pendingMindRecordDestination = null + pendingTimeLetterDestinations = null activeStack = AppStack.HOME } @@ -160,6 +179,7 @@ class AppState( afternoteBackStack.clear() afternoteBackStack.add(Route.Afternote) pendingMindRecordDestination = null + pendingTimeLetterDestinations = null activeStack = AppStack.FLOW } diff --git a/app/src/main/java/com/afternote/afternote_fe/navigation/EntryNoticeEffect.kt b/app/src/main/java/com/afternote/afternote_fe/navigation/EntryNoticeEffect.kt new file mode 100644 index 0000000000..9ae078a415 --- /dev/null +++ b/app/src/main/java/com/afternote/afternote_fe/navigation/EntryNoticeEffect.kt @@ -0,0 +1,129 @@ +package com.afternote.afternote_fe.navigation + +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Spacer +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.material3.ExperimentalMaterial3Api +import androidx.compose.material3.ModalBottomSheet +import androidx.compose.material3.SnackbarHostState +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import com.afternote.afternote_fe.MainViewModel +import com.afternote.afternote_fe.R +import com.afternote.core.ui.Route +import com.afternote.core.ui.modifierextention.bottomBorder +import com.afternote.core.ui.theme.AfternoteDesign +import com.afternote.feature.mindrecord.presentation.navigation.MindRecordRoute +import kotlinx.coroutines.launch + +/** + * 앱 진입 보고(#2321)가 돌려준 것을 사용자에게 한 번 보여 준다. + * + * - 보관 확인 절차가 취소됐으면 그 사실을 스낵바로 알린다. 앱을 연 것만으로 취소되는 절차라, 사용자가 + * 따로 할 일은 없다. + * - 오래 비웠다 돌아왔으면 쉬운 질문 셋을 시트로 띄운다. 고르면 그 질문을 제목으로 일기를 연다. + * + * 알림 진입이 큐에 남아 있는 동안은 띄우지 않는다 — 알림을 눌러 들어온 사용자는 그 목적지가 먼저다. + * 홈 바텀바 스택에 올라선 뒤에만 띄워, 온보딩 위에 시트가 뜨지 않게 한다. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +internal fun EntryNoticeEffect( + appState: AppState, + mainViewModel: MainViewModel, + snackbarHostState: SnackbarHostState, +) { + val notice by mainViewModel.entryNotice.collectAsStateWithLifecycle() + val pendingNotificationEntry by mainViewModel.pendingNotificationEntry.collectAsStateWithLifecycle() + val authenticatedStartRoute by mainViewModel.startRoute.collectAsStateWithLifecycle() + val isReady = + authenticatedStartRoute == Route.Home && appState.activeStack != AppStack.FLOW && pendingNotificationEntry == null + val current = notice?.takeIf { isReady } ?: return + + val cancelledMessage = stringResource(R.string.entry_notice_procedure_cancelled) + val snackbarScope = rememberCoroutineScope() + LaunchedEffect(current) { + if (current.procedureCancelled) snackbarScope.launch { snackbarHostState.showSnackbar(cancelledMessage) } + if (current.easyQuestions.isEmpty()) mainViewModel.consumeEntryNotice() + } + if (current.easyQuestions.isEmpty()) return + + ModalBottomSheet( + onDismissRequest = mainViewModel::consumeEntryNotice, + containerColor = AfternoteDesign.colors.gray1, + ) { + EasyQuestionsContent( + questions = current.easyQuestions, + onQuestionClick = { question -> + mainViewModel.consumeEntryNotice() + appState.navigateToMindRecordDestination(MindRecordRoute.DiaryWriteRoute(prefillTitle = question)) + }, + onDismiss = mainViewModel::consumeEntryNotice, + ) + } +} + +@Composable +internal fun EasyQuestionsContent( + questions: List, + onQuestionClick: (String) -> Unit, + onDismiss: () -> Unit, +) { + Column( + modifier = + Modifier + .fillMaxWidth() + .navigationBarsPadding() + .padding(horizontal = 20.dp), + ) { + Text( + text = stringResource(R.string.entry_notice_easy_questions_title), + style = AfternoteDesign.typography.bodyLargeB, + color = AfternoteDesign.colors.gray9, + ) + Spacer(Modifier.height(4.dp)) + Text( + text = stringResource(R.string.entry_notice_easy_questions_subtitle), + style = AfternoteDesign.typography.captionLargeR, + color = AfternoteDesign.colors.gray6, + ) + Spacer(Modifier.height(12.dp)) + questions.forEach { question -> + Text( + text = question, + style = AfternoteDesign.typography.bodyBase, + color = AfternoteDesign.colors.gray9, + modifier = + Modifier + .fillMaxWidth() + .clickable(role = Role.Button) { onQuestionClick(question) } + .bottomBorder(color = AfternoteDesign.colors.gray3, width = 1.dp) + .padding(vertical = 16.dp), + ) + } + TextButton( + onClick = onDismiss, + modifier = Modifier.align(Alignment.CenterHorizontally).padding(vertical = 8.dp), + ) { + Text( + text = stringResource(R.string.entry_notice_easy_questions_later), + style = AfternoteDesign.typography.captionLargeR, + color = AfternoteDesign.colors.gray6, + ) + } + } +} diff --git a/app/src/main/java/com/afternote/afternote_fe/navigation/NotificationEntryEffect.kt b/app/src/main/java/com/afternote/afternote_fe/navigation/NotificationEntryEffect.kt index 4bdfdf8697..a246f6fbb2 100644 --- a/app/src/main/java/com/afternote/afternote_fe/navigation/NotificationEntryEffect.kt +++ b/app/src/main/java/com/afternote/afternote_fe/navigation/NotificationEntryEffect.kt @@ -1,35 +1,78 @@ package com.afternote.afternote_fe.navigation +import androidx.compose.material3.SnackbarHostState import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.ui.res.stringResource import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.afternote.afternote_fe.MainViewModel +import com.afternote.afternote_fe.R +import com.afternote.afternote_fe.notification.NotificationNavigation import com.afternote.core.common.notification.NotificationDestination import com.afternote.core.ui.Route +import kotlinx.coroutines.launch /** - * Activity 가 큐에 넣은 알림 진입을 앱 셸이 소비해 목적지 탭으로 옮긴다. + * Activity 가 큐에 넣은 알림 진입을 앱 셸이 소비해 목적지로 옮긴다. * * 로그인이 확정되고 앱 셸이 바텀바 스택 위에 있을 때만 소비한다. 로그아웃(온보딩 FLOW 스택)이면 * 큐에 남겨 두어 알림이 인증 관문을 건너뛰는 통로가 되지 않게 하고, 로그인이 끝나 스택이 - * 바뀌는 순간 효과가 다시 돌아 그 목적지로 이어진다. 이동은 바텀바 탭을 누른 것과 같은 - * [AppState.navigateToBottomBarRoute] 를 재사용해 백스택 규약을 한 벌로 유지한다. + * 바뀌는 순간 효과가 다시 돌아 그 목적지로 이어진다. + * + * 이동은 바텀바 탭을 누르거나 홈 카드를 누른 것과 같은 [AppState] 경로를 재사용해 백스택 규약을 한 벌로 + * 유지한다. 서버가 요구하는 「뒤로가기는 홈」 도 그 규약이 지킨다 — 탭 안쪽 화면은 탭 홈 위에, 설정은 홈 + * 위에 쌓이고, 탭 홈에서의 back 은 홈으로 간다. + * + * 서버 알림이면 이동 전에 현재 목적지를 서버에 묻는다(#2321). 대상이 지워졌으면 그 목록으로 가서 + * 안내를 띄운다. 안내는 [rememberCoroutineScope] 로 띄운다 — 소비하는 순간 이 효과의 키가 바뀌어 + * 효과 안에서 띄운 스낵바는 바로 취소된다. */ @Composable internal fun NotificationEntryEffect( appState: AppState, mainViewModel: MainViewModel, + snackbarHostState: SnackbarHostState, ) { val pendingEntry by mainViewModel.pendingNotificationEntry.collectAsStateWithLifecycle() val authenticatedStartRoute by mainViewModel.startRoute.collectAsStateWithLifecycle() val isReadyForDestination = authenticatedStartRoute == Route.Home && appState.activeStack != AppStack.FLOW + val noticeScope = rememberCoroutineScope() + val deletedMessage = stringResource(R.string.notification_target_deleted_message) val entry = pendingEntry LaunchedEffect(entry?.identityKey, isReadyForDestination) { if (entry == null || !isReadyForDestination) return@LaunchedEffect - appState.navigateToBottomBarRoute(entry.destination.toBottomBarRoute()) + val resolution = mainViewModel.resolveNotificationEntry(entry) + appState.navigateTo(resolution.navigation) mainViewModel.consumeNotificationEntry(entry.identityKey) + if (resolution.deleted) { + noticeScope.launch { + snackbarHostState.showSnackbar(resolution.serverMessage ?: deletedMessage) + } + } + } +} + +private fun AppState.navigateTo(navigation: NotificationNavigation) { + when (navigation) { + is NotificationNavigation.Tab -> { + navigateToBottomBarRoute(navigation.tab.toBottomBarRoute()) + } + + is NotificationNavigation.MindRecord -> { + navigateToMindRecordDestination(navigation.route) + } + + is NotificationNavigation.TimeLetter -> { + navigateToTimeLetterDestinations(navigation.routes) + } + + is NotificationNavigation.Setting -> { + navigateToBottomBarRoute(Route.Home) + navigate(navigation.route) + } } } diff --git a/app/src/main/java/com/afternote/afternote_fe/notification/DailyNotificationScheduleSynchronizer.kt b/app/src/main/java/com/afternote/afternote_fe/notification/DailyNotificationScheduleSynchronizer.kt deleted file mode 100644 index b66e776848..0000000000 --- a/app/src/main/java/com/afternote/afternote_fe/notification/DailyNotificationScheduleSynchronizer.kt +++ /dev/null @@ -1,74 +0,0 @@ -package com.afternote.afternote_fe.notification - -import android.content.Context -import com.afternote.core.common.notification.NotificationScheduler -import com.afternote.core.common.reporting.ErrorReporter -import com.afternote.core.domain.repository.auth.AuthRepository -import com.afternote.core.domain.result.runCatchingCancellable -import dagger.hilt.android.qualifiers.ApplicationContext -import kotlinx.coroutines.flow.distinctUntilChanged -import javax.inject.Inject -import javax.inject.Singleton - -/** - * 데일리 알림(매일 09:00 로컬 알림) 예약을 로그인 상태에 맞춘다 (#2146). - * - * 알림 문구가 계정의 기록을 재촉하는 말이라, 기록할 계정이 없는 기기에는 예약을 두지 않는다. - * 로그인이 확정되면 예약하고 로그아웃되면 지운다. 로그아웃, 탈퇴, 세션 강제 만료는 모두 토큰 - * 저장소를 비워 [AuthRepository.isLoggedIn] 을 false 로 바꾸므로 이 관찰 하나가 세 경로를 다 받는다. - * 로그아웃 상태로 앱을 켜면 첫 방출이 false 라, 이전 빌드가 세션 없이 넣어 둔 예약도 여기서 지워진다. - * - * 예약은 `ExistingPeriodicWorkPolicy.KEEP` 이다. 로그인한 채 앱을 켤 때마다 다시 불러도 다음 발화 - * 시각은 밀리지 않는다. - * - * ### 왜 App Startup Initializer 가 아닌가 - * - * 전에는 `DailyNotificationInitializer` 가 세션을 보지 않고 예약했다. 세션은 Hilt 로 만든 저장소에 - * 있고 Initializer 는 Hilt 에 닿으면 안 되므로(`StartupInitializerHiltKonsistTest`) 판정 자리를 - * `GlobalApplication.onCreate` 로 옮겼다. - * - * 옛 Initializer 는 Application.onCreate 에서 부르면 WorkManager 가 먼저 준비된다는 보장이 없다며 - * `WorkManagerInitializer` 를 선행 의존으로 걸었다. 그 보장은 이 자리에서도 선다. work-runtime 라이브러리 - * 매니페스트가 `WorkManagerInitializer` 를 앱의 `InitializationProvider` 에 병합해 두고, ContentProvider 는 - * Application.onCreate 보다 먼저 초기화된다. - */ -@Singleton -class DailyNotificationScheduleSynchronizer - @Inject - constructor( - @param:ApplicationContext private val context: Context, - private val authRepository: AuthRepository, - private val errorReporter: ErrorReporter, - ) { - /** - * 로그인 상태를 계속 지켜본다. 앱 프로세스가 사는 동안 돈다. - * - * 방출 하나를 처리하다 난 예외는 기록만 하고 관찰은 이어 간다. 여기서 `collect` 가 끝나면 - * 그 프로세스에서는 이후 로그아웃이 예약을 지우지 못한다. - */ - suspend fun observeLogin() { - authRepository.isLoggedIn - .distinctUntilChanged() - .collect { isLoggedIn -> - runCatchingCancellable { - if (isLoggedIn) { - NotificationScheduler.scheduleDailyNotification( - context, - hour = DAILY_HOUR, - minute = DAILY_MINUTE, - ) - } else { - NotificationScheduler.cancelDailyNotification(context) - } - }.onFailure { error -> - errorReporter.recordFailure(error, mapOf("stage" to STAGE_SYNC)) - } - } - } - } - -// TODO: 설정(DataStore 등)에서 시·분 읽기. 알림 시각은 PM 알림 문서가 정한다(0920 회의 기준 미정). -private const val DAILY_HOUR = 9 -private const val DAILY_MINUTE = 0 - -private const val STAGE_SYNC = "daily_notification_sync" diff --git a/app/src/main/java/com/afternote/afternote_fe/notification/NotificationIntentContract.kt b/app/src/main/java/com/afternote/afternote_fe/notification/NotificationIntentContract.kt index 90bd81c398..ddd67762cd 100644 --- a/app/src/main/java/com/afternote/afternote_fe/notification/NotificationIntentContract.kt +++ b/app/src/main/java/com/afternote/afternote_fe/notification/NotificationIntentContract.kt @@ -1,15 +1,21 @@ package com.afternote.afternote_fe.notification import android.content.Intent +import android.os.Bundle import com.afternote.core.common.notification.NotificationDestination import com.afternote.core.common.notification.NotificationPendingIntentFactory +import java.util.UUID /** 앱이 직접 생성하는 알림 진입 출처. BE FCM data key와는 별개의 내부 계약이다. */ internal enum class NotificationEntrySource( val contractValue: String, ) { + /** 앱이 직접 울리던 데일리 알림(#2321 에서 제거). 이미 트레이에 떠 있는 알림을 위해 남겨 둔다. */ DAILY("daily"), FCM("fcm"), + + /** 앱 안 알림함에서 누른 알림. Intent 를 거치지 않고 큐에 바로 들어간다. */ + INBOX("inbox"), ; companion object { @@ -25,18 +31,53 @@ internal enum class NotificationEntrySource( * [destination]은 화면 이동의 목적지이지 이벤트의 식별자가 아니다. 그래서 [identityKey]에는 * 들어가지 않는다 — 같은 발생을 다시 게시하며 목적지만 바뀌어도 「이미 소비한 알림」이라는 * 판정은 유지돼야 한다. + * + * [serverNotificationId]가 있으면 서버가 만든 알림이다. [destination]·[serverData]는 발송 시점의 + * 목적지라 탭한 시점의 목적지는 이 ID로 서버에 다시 묻는다 (#2321). 묻지 못하면 [serverData]로 + * 안쪽 화면까지, 그것도 없으면 [destination] 탭으로 연다. */ internal data class NotificationEntryRequest( val source: NotificationEntrySource, val occurrenceId: String, val destination: NotificationDestination, + val serverNotificationId: Long? = null, + val serverData: Map = emptyMap(), ) { /** 서로 다른 source가 같은 occurrence 문자열을 사용해도 소비 상태가 충돌하지 않는 내부 키. */ val identityKey: String = "${source.contractValue.length}:${source.contractValue}:" + "${occurrenceId.length}:$occurrenceId" + + companion object { + /** + * 알림함에서 누른 알림. 같은 알림을 두 번 눌러도 두 번 이동해야 하므로 누를 때마다 새 발생으로 만든다 — + * 푸시 탭은 같은 Intent 가 다시 오는 것을 막아야 하지만, 알림함은 사용자가 매번 새로 누른다. + */ + fun fromInbox( + notificationId: Long, + data: Map, + ): NotificationEntryRequest = + NotificationEntryRequest( + source = NotificationEntrySource.INBOX, + occurrenceId = "notification:$notificationId:${UUID.randomUUID()}", + destination = ServerNotificationDestination.resolve(data).tab, + serverNotificationId = notificationId, + serverData = data.filterKeys(NotificationIntentContract.SERVER_DATA_KEYS::contains), + ) + } } +/** + * 알림 진입을 처리한 결과 — 열 화면과, 대상이 지워졌을 때의 안내. + * + * @property serverMessage 서버가 정한 안내 문구. [deleted]인데 이 값이 없으면 앱 기본 문구를 쓴다. + */ +internal data class NotificationEntryResolution( + val navigation: NotificationNavigation, + val deleted: Boolean = false, + val serverMessage: String? = null, +) + /** [NotificationPendingIntentFactory]가 표시한 앱 직접 생성 알림 진입만 해석한다. */ internal object NotificationIntentContract { fun fromIntent(intent: Intent): NotificationEntryRequest? = @@ -57,6 +98,16 @@ internal object NotificationIntentContract { runCatching { intent.getStringExtra(EXTRA_NOTIFICATION_DESTINATION) }.getOrNull(), + serverNotificationId = + runCatching { + intent.getLongExtra(EXTRA_NOTIFICATION_SERVER_ID, 0L) + }.getOrNull() + ?.takeIf { it > 0L }, + serverData = + runCatching { + intent.getBundleExtra(EXTRA_NOTIFICATION_SERVER_DATA)?.toServerData() + }.getOrNull() + .orEmpty(), ) /** @@ -70,6 +121,8 @@ internal object NotificationIntentContract { rawSource: String?, occurrenceId: String?, rawDestination: String?, + serverNotificationId: Long?, + serverData: Map, ): NotificationEntryRequest? { if (!isNotificationEntry) return null @@ -86,9 +139,21 @@ internal object NotificationIntentContract { destination = NotificationDestination.fromContractValue(rawDestination) ?: FALLBACK_DESTINATION, + serverNotificationId = serverNotificationId, + serverData = serverData, ) } + /** 목적지 해석에 쓰는 키만 문자열로 남긴다. 알림 Intent 는 앱 밖에서도 만들 수 있는 입력이다. */ + private fun Bundle.toServerData(): Map = + SERVER_DATA_KEYS + .mapNotNull { key -> getString(key)?.let { value -> key to value } } + .toMap() + + /** [ServerNotificationDestination] 이 읽는 키. */ + val SERVER_DATA_KEYS = + setOf("destination", "action", "recordId", "recordType", "questionId", "timeLetterId", "receiverId", "invitationId") + /** 목적지 키가 없거나 계약 밖 값일 때 여는 화면. */ private val FALLBACK_DESTINATION = NotificationDestination.HOME @@ -100,4 +165,8 @@ internal object NotificationIntentContract { NotificationPendingIntentFactory.EXTRA_NOTIFICATION_OCCURRENCE_TOKEN private const val EXTRA_NOTIFICATION_DESTINATION = NotificationPendingIntentFactory.EXTRA_NOTIFICATION_DESTINATION + private const val EXTRA_NOTIFICATION_SERVER_ID = + NotificationPendingIntentFactory.EXTRA_NOTIFICATION_SERVER_ID + private const val EXTRA_NOTIFICATION_SERVER_DATA = + NotificationPendingIntentFactory.EXTRA_NOTIFICATION_SERVER_DATA } diff --git a/app/src/main/java/com/afternote/afternote_fe/notification/ServerNotificationDestination.kt b/app/src/main/java/com/afternote/afternote_fe/notification/ServerNotificationDestination.kt new file mode 100644 index 0000000000..be94ef46a0 --- /dev/null +++ b/app/src/main/java/com/afternote/afternote_fe/notification/ServerNotificationDestination.kt @@ -0,0 +1,126 @@ +package com.afternote.afternote_fe.notification + +import com.afternote.core.common.notification.NotificationDestination +import com.afternote.core.ui.Route +import com.afternote.core.ui.SettingStart +import com.afternote.feature.mindrecord.presentation.navigation.MindRecordRoute +import com.afternote.feature.timeletter.presentation.navigation.TimeLetterRoute + +/** + * 알림이 열 화면. 탭 하나이거나, 탭 안쪽 화면이거나, 설정 안쪽 화면이다. + * + * [tab] 은 그 화면을 품은 최상위 목적지다. 안쪽 화면을 열 수 없을 때(이전 빌드가 게시한 알림의 + * 탭 extra 등) 이리로 떨어진다. + */ +internal sealed interface NotificationNavigation { + val tab: NotificationDestination + + data class Tab( + override val tab: NotificationDestination, + ) : NotificationNavigation + + /** 마음의 기록 탭 위에 [route] 를 연다. */ + data class MindRecord( + val route: MindRecordRoute, + ) : NotificationNavigation { + override val tab = NotificationDestination.MIND_RECORD + } + + /** 타임레터 탭 위에 [routes] 를 차례로 쌓는다. 뒤로 가면 쌓은 역순으로 탭까지 돌아온다. */ + data class TimeLetter( + val routes: List, + ) : NotificationNavigation { + override val tab = NotificationDestination.TIME_LETTER + } + + /** 설정을 [route] 의 시작 화면으로 연다. 바텀바 탭이 아니라 홈 위에 쌓인다. */ + data class Setting( + val route: Route.Setting, + ) : NotificationNavigation { + override val tab = NotificationDestination.HOME + } +} + +/** + * 서버 알림 data(BE `PushPayload`·`users/notifications/{id}/target`)를 앱이 열 화면으로 옮긴다 (#2321). + * + * 필수 ID 가 없거나 숫자가 아니면 그 목적지를 품은 탭으로 접는다 — 알림을 눌렀는데 아무 데도 안 가는 + * 편이 더 나쁘다. 앱에 화면이 없거나 앱 화면이 아닌 목적지(보관 확인·대리인 웹 확인·초대 랜딩·결제)는 + * 홈이다. 보관 확인은 앱을 연 것 자체가 확인이라 홈이 맞다 — 진입 보고가 절차를 취소한다. + * + * 일기·깊은 생각 상세는 아직 열지 않는다. 상세 화면이 일기를 «달» 로 찾는데 payload 에 그 달이 없어서, + * 열면 작년 기록이 「없음」 으로 뜬다. 탭으로 보낸다. + */ +internal object ServerNotificationDestination { + fun resolve(data: Map): NotificationNavigation { + val action = data[KEY_ACTION] + return when (data[KEY_DESTINATION]?.trim()) { + "RECORD_LIST", "WEEKLY_REPORT", "EASY_QUESTIONS" -> { + NotificationNavigation.Tab(NotificationDestination.MIND_RECORD) + } + + "RECORD_DETAIL" -> { + val recordId = data.positiveId(KEY_RECORD_ID) + if (recordId != null && data[KEY_RECORD_TYPE] == RECORD_TYPE_DAILY_QUESTION) { + NotificationNavigation.MindRecord(MindRecordRoute.RecordDetailRoute(recordId = recordId, isDiary = false)) + } else { + NotificationNavigation.Tab(NotificationDestination.MIND_RECORD) + } + } + + // 오늘 질문 작성. 이미 답한 질문이면 서버 목적지 확인이 기록 상세로 바꿔 준다. + "DAILY_QUESTION" -> { + NotificationNavigation.MindRecord(MindRecordRoute.DailyQuestionWriteRoute()) + } + + "TIME_LETTER_LIST" -> { + NotificationNavigation.Tab(NotificationDestination.TIME_LETTER) + } + + "TIME_LETTER_DETAIL" -> { + data.positiveId(KEY_TIME_LETTER_ID)?.let { id -> + val detail = TimeLetterRoute.TimeLetterDetailRoute(id) + // 「지금이면 수정할 수 있어요」 — 상세 위에 수정 화면을 바로 연다. 상세에는 수정 버튼이 없다. + val routes = if (action == ACTION_EDIT) listOf(detail, TimeLetterRoute.TimeLetterWriteRoute(id)) else listOf(detail) + NotificationNavigation.TimeLetter(routes) + } ?: NotificationNavigation.Tab(NotificationDestination.TIME_LETTER) + } + + "TIME_LETTER_COMPOSE" -> { + NotificationNavigation.TimeLetter( + listOf(TimeLetterRoute.TimeLetterWriteRoute(prefillReceiverId = data.positiveId(KEY_RECEIVER_ID))), + ) + } + + // 발신자용 초대 상세 화면은 아직 없다. 초대 상태는 수신인 목록에서 본다. + "RECEIVER_LIST", "INVITATION_DETAIL" -> { + NotificationNavigation.Setting(Route.Setting(start = SettingStart.RECIPIENT_LIST)) + } + + "RECEIVER_DETAIL" -> { + NotificationNavigation.Setting( + Route.Setting(start = SettingStart.RECIPIENT_EDIT, receiverId = data.positiveId(KEY_RECEIVER_ID)), + ) + } + + "AGENT_SETTINGS" -> { + NotificationNavigation.Setting(Route.Setting(start = SettingStart.DELEGATE)) + } + + else -> { + NotificationNavigation.Tab(NotificationDestination.HOME) + } + } + } + + private fun Map.positiveId(key: String): Long? = this[key]?.trim()?.toLongOrNull()?.takeIf { it > 0L } + + private const val KEY_DESTINATION = "destination" + private const val KEY_ACTION = "action" + private const val KEY_RECORD_ID = "recordId" + private const val KEY_RECORD_TYPE = "recordType" + private const val KEY_TIME_LETTER_ID = "timeLetterId" + private const val KEY_RECEIVER_ID = "receiverId" + private const val RECORD_TYPE_DAILY_QUESTION = "DAILY_QUESTION" + private const val ACTION_EDIT = "EDIT" +} diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 4d991dc2ba..c06d69af11 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -3,6 +3,11 @@ afternote_fcm 애프터노트 알림 AFTERNOTE + 삭제된 항목이에요 + 앱을 열어 주셔서 보관 확인 절차를 취소했어요 + 다시 오셨네요 + 가볍게 하나 골라 적어 볼까요? + 다음에 할게요 알림이 꺼져 있어 새로운 소식을 받을 수 없어요 설정 새로운 버전이 나왔어요.\n업데이트 후 이용해 주세요. diff --git a/app/src/test/java/com/afternote/afternote_fe/MainViewModelInvitationTest.kt b/app/src/test/java/com/afternote/afternote_fe/MainViewModelInvitationTest.kt index 757ae68d6c..127f57e44d 100644 --- a/app/src/test/java/com/afternote/afternote_fe/MainViewModelInvitationTest.kt +++ b/app/src/test/java/com/afternote/afternote_fe/MainViewModelInvitationTest.kt @@ -1,6 +1,10 @@ package com.afternote.afternote_fe import androidx.lifecycle.SavedStateHandle +import com.afternote.core.domain.repository.notification.NotificationEntry +import com.afternote.core.domain.repository.notification.NotificationInbox +import com.afternote.core.domain.repository.notification.NotificationRepository +import com.afternote.core.domain.repository.notification.NotificationTarget import com.afternote.core.domain.testing.FakeAuthRepository import com.afternote.core.domain.testing.FakePendingReceiverInvitationStore import kotlinx.coroutines.Dispatchers @@ -112,6 +116,7 @@ class MainViewModelInvitationTest { MainViewModel( authRepository = auth, pendingInvitationStore = store, + notificationRepository = UnusedNotificationRepository, savedStateHandle = savedStateHandle, ) @@ -125,3 +130,15 @@ class MainViewModelInvitationTest { const val TOKEN = "abcDEF123_-token" } } + +/** 초대 경로는 알림 목적지를 묻지 않는다. 불리면 그 자체가 회귀다. */ +private object UnusedNotificationRepository : NotificationRepository { + override suspend fun target(notificationId: Long): Result = error("target 은 이 테스트에서 호출되면 안 됨") + + override suspend fun markRead(notificationId: Long): Result = error("markRead 는 이 테스트에서 호출되면 안 됨") + + override suspend fun inbox(): Result = error("inbox 는 이 테스트에서 호출되면 안 됨") + + // 로그인 상태로 만든 픽스처는 진입 보고를 한 번 보낸다. 초대 경로와 무관하므로 비어 있는 결과를 준다. + override suspend fun reportEntry(): Result = Result.success(NotificationEntry(emptyList(), false)) +} diff --git a/app/src/test/java/com/afternote/afternote_fe/MainViewModelNotificationTest.kt b/app/src/test/java/com/afternote/afternote_fe/MainViewModelNotificationTest.kt index 6348b75661..8a40f8d5c6 100644 --- a/app/src/test/java/com/afternote/afternote_fe/MainViewModelNotificationTest.kt +++ b/app/src/test/java/com/afternote/afternote_fe/MainViewModelNotificationTest.kt @@ -3,17 +3,29 @@ package com.afternote.afternote_fe import androidx.lifecycle.SavedStateHandle import com.afternote.afternote_fe.notification.NotificationEntryRequest import com.afternote.afternote_fe.notification.NotificationEntrySource +import com.afternote.afternote_fe.notification.NotificationNavigation import com.afternote.core.common.notification.NotificationDestination +import com.afternote.core.domain.repository.notification.NotificationEntry +import com.afternote.core.domain.repository.notification.NotificationInbox +import com.afternote.core.domain.repository.notification.NotificationRepository +import com.afternote.core.domain.repository.notification.NotificationTarget import com.afternote.core.domain.testing.FakeAuthRepository import com.afternote.core.domain.testing.FakePendingReceiverInvitationStore +import com.afternote.feature.mindrecord.presentation.navigation.MindRecordRoute +import com.afternote.feature.timeletter.presentation.navigation.TimeLetterRoute import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.advanceUntilIdle import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.runTest import kotlinx.coroutines.test.setMain import org.junit.After 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 @@ -87,10 +99,155 @@ class MainViewModelNotificationTest { assertEquals(fcm, viewModel.pendingNotificationEntry.value) } - private fun viewModel(savedStateHandle: SavedStateHandle): MainViewModel = + @Test + fun `서버 ID가 없는 알림은 서버에 묻지 않고 실어 온 목적지로 연다`() = + runTest(dispatcher) { + val repository = FakeNotificationRepository() + val viewModel = viewModel(SavedStateHandle(), repository) + + val resolution = + viewModel.resolveNotificationEntry( + request("occurrence-1", destination = NotificationDestination.TIME_LETTER), + ) + advanceUntilIdle() + + assertEquals(NotificationNavigation.Tab(NotificationDestination.TIME_LETTER), resolution.navigation) + assertTrue(repository.targetRequests.isEmpty()) + assertTrue(repository.readRequests.isEmpty()) + } + + @Test + fun `서버 알림은 탭한 시점의 목적지로 열고 읽음 처리한다`() = + runTest(dispatcher) { + val repository = + FakeNotificationRepository( + target = { + Result.success( + NotificationTarget( + data = mapOf("destination" to "RECORD_DETAIL", "recordType" to "DAILY_QUESTION", "recordId" to "9"), + deleted = false, + toast = null, + ), + ) + }, + ) + val viewModel = viewModel(SavedStateHandle(), repository) + + val resolution = + viewModel.resolveNotificationEntry( + request( + "notification:42", + serverNotificationId = 42L, + serverData = mapOf("destination" to "DAILY_QUESTION", "questionId" to "9"), + ), + ) + advanceUntilIdle() + + assertEquals( + NotificationNavigation.MindRecord(MindRecordRoute.RecordDetailRoute(recordId = 9L, isDiary = false)), + resolution.navigation, + ) + assertFalse(resolution.deleted) + assertEquals(listOf(42L), repository.targetRequests) + assertEquals(listOf(42L), repository.readRequests) + } + + @Test + fun `지워진 대상은 서버가 준 목록과 안내 문구를 돌려준다`() = + runTest(dispatcher) { + val repository = + FakeNotificationRepository( + target = { + Result.success( + NotificationTarget(data = mapOf("destination" to "TIME_LETTER_LIST"), deleted = true, toast = "삭제된 항목이에요"), + ) + }, + ) + val viewModel = viewModel(SavedStateHandle(), repository) + + val resolution = viewModel.resolveNotificationEntry(request("notification:7", serverNotificationId = 7L)) + + assertEquals(NotificationNavigation.Tab(NotificationDestination.TIME_LETTER), resolution.navigation) + assertTrue(resolution.deleted) + assertEquals("삭제된 항목이에요", resolution.serverMessage) + } + + @Test + fun `목적지 조회가 실패하면 알림이 실어 온 data로 안쪽 화면까지 연다`() = + runTest(dispatcher) { + val repository = FakeNotificationRepository(target = { Result.failure(IllegalStateException("offline")) }) + val viewModel = viewModel(SavedStateHandle(), repository) + + val resolution = + viewModel.resolveNotificationEntry( + request( + "notification:1", + NotificationEntrySource.FCM, + NotificationDestination.TIME_LETTER, + 1L, + serverData = mapOf("destination" to "TIME_LETTER_DETAIL", "timeLetterId" to "5"), + ), + ) + advanceUntilIdle() + + assertEquals( + NotificationNavigation.TimeLetter(listOf(TimeLetterRoute.TimeLetterDetailRoute(5L))), + resolution.navigation, + ) + assertFalse(resolution.deleted) + assertEquals(listOf(1L), repository.readRequests) + } + + @Test + fun `목적지 조회가 응답하지 않으면 기다리지 않고 실어 온 목적지로 연다`() = + runTest(dispatcher) { + val repository = FakeNotificationRepository(target = { awaitCancellation() }) + val viewModel = viewModel(SavedStateHandle(), repository) + + val resolution = + viewModel.resolveNotificationEntry( + request("notification:1", NotificationEntrySource.FCM, NotificationDestination.MIND_RECORD, 1L), + ) + + assertEquals(NotificationNavigation.Tab(NotificationDestination.MIND_RECORD), resolution.navigation) + } + + @Test + fun `로그인 상태로 시작하면 진입을 보고하고 보여 줄 쉬운 질문을 남긴다`() = + runTest(dispatcher) { + val entry = NotificationEntry(easyQuestions = listOf("오늘 가장 오래 생각한 사람은?"), procedureCancelled = false) + val viewModel = + viewModel( + SavedStateHandle(), + FakeNotificationRepository(entry = { Result.success(entry) }), + loggedIn = true, + ) + advanceUntilIdle() + + assertEquals(entry, viewModel.entryNotice.value) + + viewModel.consumeEntryNotice() + assertNull(viewModel.entryNotice.value) + } + + @Test + fun `보여 줄 것이 없는 진입 보고는 남기지 않는다`() = + runTest(dispatcher) { + val viewModel = viewModel(SavedStateHandle(), FakeNotificationRepository(), loggedIn = true) + advanceUntilIdle() + + assertNull(viewModel.entryNotice.value) + } + + private fun viewModel( + savedStateHandle: SavedStateHandle, + notificationRepository: NotificationRepository = FakeNotificationRepository(), + loggedIn: Boolean = false, + ): MainViewModel = MainViewModel( - authRepository = FakeAuthRepository(loggedIn = false), + authRepository = FakeAuthRepository(loggedIn = loggedIn), pendingInvitationStore = FakePendingReceiverInvitationStore(), + notificationRepository = notificationRepository, savedStateHandle = savedStateHandle, ) @@ -98,10 +255,36 @@ class MainViewModelNotificationTest { occurrenceId: String, source: NotificationEntrySource = NotificationEntrySource.FCM, destination: NotificationDestination = NotificationDestination.HOME, + serverNotificationId: Long? = null, + serverData: Map = emptyMap(), ): NotificationEntryRequest = NotificationEntryRequest( source = source, occurrenceId = occurrenceId, destination = destination, + serverNotificationId = serverNotificationId, + serverData = serverData, ) + + private class FakeNotificationRepository( + private val target: suspend () -> Result = { error("target 은 이 테스트에서 호출되면 안 됨") }, + private val entry: suspend () -> Result = { Result.success(NotificationEntry(emptyList(), false)) }, + ) : NotificationRepository { + val targetRequests = mutableListOf() + val readRequests = mutableListOf() + + override suspend fun target(notificationId: Long): Result { + targetRequests += notificationId + return target() + } + + override suspend fun markRead(notificationId: Long): Result { + readRequests += notificationId + return Result.success(Unit) + } + + override suspend fun inbox(): Result = error("inbox 는 이 테스트에서 호출되면 안 됨") + + override suspend fun reportEntry(): Result = entry() + } } diff --git a/app/src/test/java/com/afternote/afternote_fe/messaging/AfternoteFirebaseMessagingServiceTest.kt b/app/src/test/java/com/afternote/afternote_fe/messaging/AfternoteFirebaseMessagingServiceTest.kt index 7a863ba1d9..6f9697cecf 100644 --- a/app/src/test/java/com/afternote/afternote_fe/messaging/AfternoteFirebaseMessagingServiceTest.kt +++ b/app/src/test/java/com/afternote/afternote_fe/messaging/AfternoteFirebaseMessagingServiceTest.kt @@ -4,7 +4,9 @@ import android.Manifest import android.app.Application import android.app.Notification import android.app.NotificationManager +import android.content.Intent import android.os.Bundle +import com.afternote.core.common.notification.NotificationPendingIntentFactory import com.google.firebase.messaging.RemoteMessage import org.junit.Assert.assertEquals import org.junit.Before @@ -108,6 +110,62 @@ class AfternoteFirebaseMessagingServiceTest { assertEquals(2, postedNotifications().size) } + @Test + fun `서버 data-only 알림은 목적지와 서버 알림 ID를 탭 Intent에 싣는다`() { + service.onMessageReceived( + remoteMessage( + data = + mapOf( + "schemaVersion" to "1", + "title" to "AfterNote", + "body" to "예약하신 편지가 곧 전달돼요", + "destination" to "TIME_LETTER_DETAIL", + "timeLetterId" to "123", + "action" to "EDIT", + "notificationId" to "42", + ), + ), + ) + + assertEquals("AfterNote", contentTitleOfSingleNotification()) + val intent = contentIntentOfSingleNotification() + assertEquals("time_letter", intent.getStringExtra(NotificationPendingIntentFactory.EXTRA_NOTIFICATION_DESTINATION)) + assertEquals(42L, intent.getLongExtra(NotificationPendingIntentFactory.EXTRA_NOTIFICATION_SERVER_ID, 0L)) + val serverData = intent.getBundleExtra(NotificationPendingIntentFactory.EXTRA_NOTIFICATION_SERVER_DATA)!! + assertEquals("TIME_LETTER_DETAIL", serverData.getString("destination")) + assertEquals("123", serverData.getString("timeLetterId")) + assertEquals("EDIT", serverData.getString("action")) + // 제목·본문처럼 목적지 해석에 쓰지 않는 키는 Intent 에 싣지 않는다. + assertEquals(null, serverData.getString("body")) + } + + @Test + fun `모르는 schemaVersion이면 알림은 보이되 홈으로 연다`() { + service.onMessageReceived( + remoteMessage( + data = mapOf("schemaVersion" to "2", "title" to "제목", "destination" to "TIME_LETTER_DETAIL"), + ), + ) + + val intent = contentIntentOfSingleNotification() + assertEquals("home", intent.getStringExtra(NotificationPendingIntentFactory.EXTRA_NOTIFICATION_DESTINATION)) + } + + @Test + fun `같은 서버 알림 ID는 message id가 달라도 하나로 합쳐진다`() { + service.onMessageReceived( + remoteMessage(messageId = "message-1", data = mapOf("title" to "첫 번째", "notificationId" to "42")), + ) + service.onMessageReceived( + remoteMessage(messageId = "message-2", data = mapOf("title" to "재전송", "notificationId" to "42")), + ) + + assertEquals(1, postedNotifications().size) + assertEquals("재전송", contentTitleOfSingleNotification()) + } + + private fun contentIntentOfSingleNotification(): Intent = shadowOf(singleNotification().contentIntent).savedIntent + private fun postedNotifications(): List { val manager = RuntimeEnvironment.getApplication().getSystemService(NotificationManager::class.java) return shadowOf(manager).allNotifications diff --git a/app/src/test/java/com/afternote/afternote_fe/messaging/PushTargetSynchronizerTest.kt b/app/src/test/java/com/afternote/afternote_fe/messaging/PushTargetSynchronizerTest.kt index a9350c288d..8c6b10092e 100644 --- a/app/src/test/java/com/afternote/afternote_fe/messaging/PushTargetSynchronizerTest.kt +++ b/app/src/test/java/com/afternote/afternote_fe/messaging/PushTargetSynchronizerTest.kt @@ -2,6 +2,8 @@ package com.afternote.afternote_fe.messaging import com.afternote.core.common.reporting.ErrorReporter import com.afternote.core.domain.push.DevicePushTargetProvider +import com.afternote.core.domain.push.PushPermission +import com.afternote.core.domain.push.PushRegistration import com.afternote.core.domain.repository.push.PushTargetRepository import com.afternote.core.domain.testing.FakeAuthRepository import kotlinx.coroutines.ExperimentalCoroutinesApi @@ -211,16 +213,142 @@ class PushTargetSynchronizerTest { assertEquals("push_target_rotated", errorReporter.failures.single()["stage"]) } + @Test + fun `로그인하면 설치 ID와 권한을 보고하고 등록에도 같은 값을 싣는다`() = + runTest(dispatcher) { + val pushTargetRepository = RecordingPushTargetRepository() + val synchronizer = + synchronizer( + FakeAuthRepository(loggedIn = true, accessToken = "access"), + pushTargetRepository, + deviceTargetId = "fid-1", + permissionReader = FakePushPermissionReader(PushPermission.DENIED), + ) + + backgroundScope.launch { synchronizer.observeLogin() } + advanceUntilIdle() + + assertEquals(listOf(INSTALLATION_ID to PushPermission.DENIED), pushTargetRepository.reports) + assertEquals( + listOf(Triple("fid-1", INSTALLATION_ID, PushPermission.DENIED)), + pushTargetRepository.registrations, + ) + } + + @Test + fun `앞으로 나왔을 때 권한이 바뀌었으면 다시 보고하고 다시 등록한다`() = + runTest(dispatcher) { + val pushTargetRepository = RecordingPushTargetRepository() + val permissionReader = FakePushPermissionReader(PushPermission.DENIED) + val synchronizer = + synchronizer( + FakeAuthRepository(loggedIn = true, accessToken = "access"), + pushTargetRepository, + deviceTargetId = "fid-1", + permissionReader = permissionReader, + ) + backgroundScope.launch { synchronizer.observeLogin() } + advanceUntilIdle() + + permissionReader.permission = PushPermission.GRANTED + synchronizer.onForeground() + + assertEquals( + listOf(INSTALLATION_ID to PushPermission.DENIED, INSTALLATION_ID to PushPermission.GRANTED), + pushTargetRepository.reports, + ) + assertEquals( + listOf(PushPermission.DENIED, PushPermission.GRANTED), + pushTargetRepository.registrations.map { it.third }, + ) + } + + @Test + fun `앞으로 나왔을 때 권한이 그대로면 서버를 부르지 않는다`() = + runTest(dispatcher) { + val pushTargetRepository = RecordingPushTargetRepository() + val synchronizer = + synchronizer( + FakeAuthRepository(loggedIn = true, accessToken = "access"), + pushTargetRepository, + deviceTargetId = "fid-1", + ) + backgroundScope.launch { synchronizer.observeLogin() } + advanceUntilIdle() + + synchronizer.onForeground() + + assertEquals(1, pushTargetRepository.reports.size) + assertEquals(listOf("fid-1"), pushTargetRepository.registered) + } + + @Test + fun `로그아웃 상태에서 앞으로 나와도 보고하지 않는다`() = + runTest(dispatcher) { + val pushTargetRepository = RecordingPushTargetRepository() + val synchronizer = + synchronizer( + FakeAuthRepository(loggedIn = false, accessToken = null), + pushTargetRepository, + deviceTargetId = "fid-1", + ) + + synchronizer.onForeground() + + assertTrue(pushTargetRepository.reports.isEmpty()) + } + + @Test + fun `등록이 실패한 식별자는 앞으로 나올 때 다시 시도한다`() = + runTest(dispatcher) { + val pushTargetRepository = RecordingPushTargetRepository(failRegistrations = 1) + val permissionReader = FakePushPermissionReader(PushPermission.GRANTED) + val synchronizer = + synchronizer( + FakeAuthRepository(loggedIn = true, accessToken = "access"), + pushTargetRepository, + deviceTargetId = "fid-1", + permissionReader = permissionReader, + ) + backgroundScope.launch { synchronizer.observeLogin() } + advanceUntilIdle() + + synchronizer.onForeground() + + assertEquals(listOf("fid-1", "fid-1"), pushTargetRepository.registered) + } + + @Test + fun `서버가 식별자를 무효라 하면 새로 발급받아 한 번만 다시 등록한다`() = + runTest(dispatcher) { + val pushTargetRepository = RecordingPushTargetRepository(invalidTargetIds = setOf("fid-dead", "fid-new")) + val provider = FakeDevicePushTargetProvider(resetTo = "fid-new") { "fid-dead" } + val synchronizer = + synchronizer( + authRepository = FakeAuthRepository(loggedIn = true, accessToken = "access"), + pushTargetRepository = pushTargetRepository, + devicePushTargetProvider = provider, + ) + + backgroundScope.launch { synchronizer.observeLogin() } + advanceUntilIdle() + + assertEquals(listOf("fid-dead", "fid-new"), pushTargetRepository.registered) + assertEquals(1, provider.resetCalls) + } + private fun synchronizer( authRepository: FakeAuthRepository, pushTargetRepository: PushTargetRepository, deviceTargetId: String?, errorReporter: ErrorReporter = RecordingErrorReporter(), + permissionReader: PushPermissionReader = FakePushPermissionReader(PushPermission.GRANTED), ) = synchronizer( authRepository = authRepository, pushTargetRepository = pushTargetRepository, devicePushTargetProvider = FakeDevicePushTargetProvider { deviceTargetId }, errorReporter = errorReporter, + permissionReader = permissionReader, ) private fun synchronizer( @@ -228,20 +356,41 @@ class PushTargetSynchronizerTest { pushTargetRepository: PushTargetRepository, devicePushTargetProvider: DevicePushTargetProvider, errorReporter: ErrorReporter = RecordingErrorReporter(), + permissionReader: PushPermissionReader = FakePushPermissionReader(PushPermission.GRANTED), ) = PushTargetSynchronizer( authRepository = authRepository, devicePushTargetProvider = devicePushTargetProvider, pushTargetRepository = pushTargetRepository, + installationIdStore = FixedPushInstallationIdStore, + permissionReader = permissionReader, errorReporter = errorReporter, ) + private object FixedPushInstallationIdStore : PushInstallationIdStore { + override suspend fun installationId(): String = INSTALLATION_ID + } + + private class FakePushPermissionReader( + var permission: PushPermission, + ) : PushPermissionReader { + override fun current(): PushPermission = permission + } + /** 등록·해제 두 경로가 같은 값을 본다. 던지게 만들려면 [targetId] 가 던지면 된다. */ private class FakeDevicePushTargetProvider( + private val resetTo: String? = null, private val targetId: () -> String?, ) : DevicePushTargetProvider { + var resetCalls = 0 + override suspend fun currentTargetId(): String? = targetId() override suspend fun existingTargetId(): String? = targetId() + + override suspend fun resetTargetId(): String? { + resetCalls++ + return resetTo + } } // recordFailure 는 문구 유출을 막으려 예외를 redact 한 사본으로 바꾸고 원래 타입은 @@ -261,23 +410,58 @@ class PushTargetSynchronizerTest { } private class ThrowingPushTargetRepository : PushTargetRepository { - override suspend fun register(targetId: String): Result = throw IllegalStateException("boom") + override suspend fun register( + targetId: String, + installationId: String, + permission: PushPermission, + ): Result = throw IllegalStateException("boom") override suspend fun unregister(targetId: String): Result = throw IllegalStateException("boom") + + override suspend fun reportPermission( + installationId: String, + permission: PushPermission, + ): Result = Result.success(Unit) } - private class RecordingPushTargetRepository : PushTargetRepository { - val registered = mutableListOf() + private class RecordingPushTargetRepository( + private var failRegistrations: Int = 0, + private val invalidTargetIds: Set = emptySet(), + ) : PushTargetRepository { + val registrations = mutableListOf>() + val registered: List + get() = registrations.map { it.first } val unregistered = mutableListOf() - - override suspend fun register(targetId: String): Result { - registered += targetId - return Result.success(Unit) + val reports = mutableListOf>() + + override suspend fun register( + targetId: String, + installationId: String, + permission: PushPermission, + ): Result { + registrations += Triple(targetId, installationId, permission) + if (failRegistrations > 0) { + failRegistrations-- + return Result.failure(IllegalStateException("등록 실패")) + } + return Result.success(PushRegistration(requiresReset = targetId in invalidTargetIds)) } override suspend fun unregister(targetId: String): Result { unregistered += targetId return Result.success(Unit) } + + override suspend fun reportPermission( + installationId: String, + permission: PushPermission, + ): Result { + reports += installationId to permission + return Result.success(Unit) + } + } + + private companion object { + const val INSTALLATION_ID = "d92560f1-ad73-4bfb-8759-017c61ad5168" } } diff --git a/app/src/test/java/com/afternote/afternote_fe/navigation/RecipientChipDestinationTest.kt b/app/src/test/java/com/afternote/afternote_fe/navigation/RecipientChipDestinationTest.kt index 6e8c891107..bdc6a1f7e4 100644 --- a/app/src/test/java/com/afternote/afternote_fe/navigation/RecipientChipDestinationTest.kt +++ b/app/src/test/java/com/afternote/afternote_fe/navigation/RecipientChipDestinationTest.kt @@ -3,6 +3,7 @@ package com.afternote.afternote_fe.navigation import android.app.Application import androidx.compose.ui.test.junit4.v2.createComposeRule import com.afternote.core.ui.Route +import com.afternote.core.ui.SettingStart import org.junit.Assert.assertEquals import org.junit.Rule import org.junit.Test @@ -16,7 +17,7 @@ import org.robolectric.annotation.GraphicsMode * * Nav2 시절엔 칩이 `SettingRoute.RecipientRegisterRoute` 를 루트에 직접 찍어 백스택 이름만으로 * 목적지가 보였다. 설정이 로컬 스택이 된 뒤로는 루트에 [Route.Setting] 한 칸만 쌓이고 등록 화면 - * 진입은 그 인자([Route.Setting.startWithRecipientRegistration])가 나른다 — 인자를 버리는 + * 진입은 그 인자([Route.Setting.start])가 나른다 — 인자를 버리는 * [backStackRouteNames] 로는 설정 홈 진입과 구분되지 않으므로 [toRoute] 로 값까지 꺼내 단언한다. * 그 인자로 host 가 실제 첫 화면을 고르는 몫은 `SettingImplementedCoverageAndroidTest` 가 본다. */ @@ -48,7 +49,7 @@ class RecipientChipDestinationTest { listOf("NavHostRoot", "Home", "Setting"), composeRule.runOnIdle { harness.navController.backStackRouteNames() }, ) - assertEquals(true, currentSetting().startWithRecipientRegistration) + assertEquals(SettingStart.RECIPIENT_REGISTRATION, currentSetting().start) } @Test @@ -57,6 +58,6 @@ class RecipientChipDestinationTest { composeRule.runOnIdle { harness.homeActions.onSettingClick() } - assertEquals(false, currentSetting().startWithRecipientRegistration) + assertEquals(SettingStart.HOME, currentSetting().start) } } diff --git a/app/src/test/java/com/afternote/afternote_fe/notification/DailyNotificationScheduleSynchronizerTest.kt b/app/src/test/java/com/afternote/afternote_fe/notification/DailyNotificationScheduleSynchronizerTest.kt deleted file mode 100644 index 2d507cbf14..0000000000 --- a/app/src/test/java/com/afternote/afternote_fe/notification/DailyNotificationScheduleSynchronizerTest.kt +++ /dev/null @@ -1,149 +0,0 @@ -package com.afternote.afternote_fe.notification - -import android.app.Application -import android.content.Context -import androidx.work.Configuration -import androidx.work.WorkInfo -import androidx.work.WorkManager -import androidx.work.testing.SynchronousExecutor -import androidx.work.testing.WorkManagerTestInitHelper -import com.afternote.core.common.notification.DailyNotificationWorker -import com.afternote.core.common.notification.NotificationScheduler -import com.afternote.core.common.reporting.ErrorReporter -import com.afternote.core.domain.testing.FakeAuthRepository -import kotlinx.coroutines.ExperimentalCoroutinesApi -import kotlinx.coroutines.launch -import kotlinx.coroutines.test.UnconfinedTestDispatcher -import kotlinx.coroutines.test.advanceUntilIdle -import kotlinx.coroutines.test.runTest -import org.junit.Assert.assertEquals -import org.junit.Assert.assertTrue -import org.junit.Before -import org.junit.Test -import org.junit.runner.RunWith -import org.robolectric.RobolectricTestRunner -import org.robolectric.RuntimeEnvironment -import org.robolectric.annotation.Config - -/** - * 데일리 알림 예약이 로그인 상태를 따라가는지의 회귀 기준 (#2146). - * - * 대역을 두지 않고 실제 WorkManager 에 넣고 지운 예약을 읽는다. 보는 것은 unique work 의 상태다. - * 로그인 상태에서만 ENQUEUED 이고, 로그아웃되면 CANCELLED 가 된다. - * - * `application` 을 `Application` 으로 둔 것은 `GlobalApplication` 이 Hilt 진입점이라 주입이 먼저 - * 돌기 때문이다. 이 테스트는 관찰자를 직접 만든다. - */ -@OptIn(ExperimentalCoroutinesApi::class) -@RunWith(RobolectricTestRunner::class) -@Config(sdk = [35], application = Application::class) -class DailyNotificationScheduleSynchronizerTest { - // PushTargetSynchronizerTest 와 같은 이유다. StandardTestDispatcher 로는 backgroundScope 의 collect 가 시작되지 않는다. - private val dispatcher = UnconfinedTestDispatcher() - - private lateinit var context: Context - - @Before - fun setUp() { - context = RuntimeEnvironment.getApplication() - WorkManagerTestInitHelper.initializeTestWorkManager( - context, - Configuration - .Builder() - .setExecutor(SynchronousExecutor()) - .setTaskExecutor(SynchronousExecutor()) - .build(), - ) - } - - @Test - fun `로그아웃 상태로 시작하면 데일리 알림을 예약하지 않는다`() = - runTest(dispatcher) { - backgroundScope.launch { synchronizer(FakeAuthRepository(loggedIn = false)).observeLogin() } - advanceUntilIdle() - - assertTrue(dailyWork().isEmpty()) - } - - @Test - fun `로그아웃 상태로 켜지면 세션 없이 넣어 둔 예약을 지운다`() = - runTest(dispatcher) { - // 이전 빌드의 Initializer 가 세션을 보지 않고 넣어 둔 예약. - NotificationScheduler.scheduleDailyNotification(context, hour = 9, minute = 0) - assertEquals(WorkInfo.State.ENQUEUED, dailyState()) - - backgroundScope.launch { synchronizer(FakeAuthRepository(loggedIn = false)).observeLogin() } - advanceUntilIdle() - - assertEquals(WorkInfo.State.CANCELLED, dailyState()) - } - - @Test - fun `로그인하면 예약하고 로그아웃하면 지운다`() = - runTest(dispatcher) { - val authRepository = FakeAuthRepository(loggedIn = false) - backgroundScope.launch { synchronizer(authRepository).observeLogin() } - advanceUntilIdle() - - authRepository.loggedIn = true - advanceUntilIdle() - assertEquals(WorkInfo.State.ENQUEUED, dailyState()) - - authRepository.loggedIn = false - advanceUntilIdle() - assertEquals(WorkInfo.State.CANCELLED, dailyState()) - } - - @Test - fun `로그아웃 뒤 다시 로그인하면 새로 예약한다`() = - runTest(dispatcher) { - val authRepository = FakeAuthRepository(loggedIn = true) - backgroundScope.launch { synchronizer(authRepository).observeLogin() } - advanceUntilIdle() - - authRepository.loggedIn = false - advanceUntilIdle() - authRepository.loggedIn = true - advanceUntilIdle() - - assertEquals(WorkInfo.State.ENQUEUED, dailyState()) - } - - @Test - fun `로그인한 채 켜지면 이미 있는 예약을 갈아 끼우지 않는다`() = - runTest(dispatcher) { - // 갈아 끼우면 다음 발화 시각이 새 initialDelay 로 밀린다. 알림 시각 전에 앱을 켜는 사용자는 알림을 영영 못 받는다. - NotificationScheduler.scheduleDailyNotification(context, hour = 9, minute = 0) - val existing = dailyWork().single().id - - backgroundScope.launch { synchronizer(FakeAuthRepository(loggedIn = true)).observeLogin() } - advanceUntilIdle() - - val current = dailyWork().single() - assertEquals(existing, current.id) - assertEquals(WorkInfo.State.ENQUEUED, current.state) - } - - private fun synchronizer(authRepository: FakeAuthRepository) = - DailyNotificationScheduleSynchronizer( - context = context, - authRepository = authRepository, - errorReporter = FailingErrorReporter(), - ) - - private fun dailyWork(): List = - WorkManager - .getInstance(context) - .getWorkInfosForUniqueWork(DailyNotificationWorker.UNIQUE_WORK_NAME) - .get() - - private fun dailyState(): WorkInfo.State = dailyWork().single().state - - /** 이 테스트의 경로에서는 실패가 없어야 한다. 기록되면 그 자리에서 드러낸다. */ - private class FailingErrorReporter : ErrorReporter { - override fun writeFailure( - throwable: Throwable, - attributes: Map, - ): Unit = throw AssertionError("예상하지 못한 실패 기록: $attributes", throwable) - } -} diff --git a/app/src/test/java/com/afternote/afternote_fe/notification/LegacyDailyNotificationTest.kt b/app/src/test/java/com/afternote/afternote_fe/notification/LegacyDailyNotificationTest.kt new file mode 100644 index 0000000000..afc82ac146 --- /dev/null +++ b/app/src/test/java/com/afternote/afternote_fe/notification/LegacyDailyNotificationTest.kt @@ -0,0 +1,90 @@ +package com.afternote.afternote_fe.notification + +import android.app.Application +import android.app.NotificationChannel +import android.app.NotificationManager +import android.content.Context +import androidx.work.Configuration +import androidx.work.ExistingPeriodicWorkPolicy +import androidx.work.PeriodicWorkRequestBuilder +import androidx.work.WorkInfo +import androidx.work.WorkManager +import androidx.work.Worker +import androidx.work.WorkerParameters +import androidx.work.testing.SynchronousExecutor +import androidx.work.testing.WorkManagerTestInitHelper +import com.afternote.core.common.notification.LegacyDailyNotification +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config +import java.util.concurrent.TimeUnit + +/** + * 이전 빌드가 남긴 데일리 알림 예약과 채널이 지워지는지의 회귀 기준 (#2321). + * + * 이전 빌드의 Worker 클래스는 지웠으므로, 같은 unique 이름으로 아무 Worker 나 넣어 업데이트 직후의 + * 기기 상태를 흉내 낸다. WorkManager 는 예약을 클래스가 아니라 이름으로 지운다. + */ +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [35], application = Application::class) +class LegacyDailyNotificationTest { + private lateinit var context: Context + + @Before + fun setUp() { + context = RuntimeEnvironment.getApplication() + WorkManagerTestInitHelper.initializeTestWorkManager( + context, + Configuration + .Builder() + .setExecutor(SynchronousExecutor()) + .setTaskExecutor(SynchronousExecutor()) + .build(), + ) + } + + @Test + fun `이전 빌드의 데일리 예약과 알림 채널을 지운다`() { + WorkManager.getInstance(context).enqueueUniquePeriodicWork( + LegacyDailyNotification.UNIQUE_WORK_NAME, + ExistingPeriodicWorkPolicy.KEEP, + PeriodicWorkRequestBuilder(24, TimeUnit.HOURS).build(), + ) + notificationManager().createNotificationChannel( + NotificationChannel(LegacyDailyNotification.CHANNEL_ID, "Daily reminders", NotificationManager.IMPORTANCE_DEFAULT), + ) + + LegacyDailyNotification.clear(context) + + assertEquals(listOf(WorkInfo.State.CANCELLED), dailyWorkStates()) + assertNull(notificationManager().getNotificationChannel(LegacyDailyNotification.CHANNEL_ID)) + } + + @Test + fun `지울 것이 없어도 실패하지 않는다`() { + LegacyDailyNotification.clear(context) + + assertEquals(emptyList(), dailyWorkStates()) + } + + private fun dailyWorkStates(): List = + WorkManager + .getInstance(context) + .getWorkInfosForUniqueWork(LegacyDailyNotification.UNIQUE_WORK_NAME) + .get() + .map(WorkInfo::state) + + private fun notificationManager(): NotificationManager = context.getSystemService(NotificationManager::class.java) + + class NoopWorker( + context: Context, + params: WorkerParameters, + ) : Worker(context, params) { + override fun doWork(): Result = Result.success() + } +} diff --git a/app/src/test/java/com/afternote/afternote_fe/notification/NotificationIntentContractTest.kt b/app/src/test/java/com/afternote/afternote_fe/notification/NotificationIntentContractTest.kt index 2c2aa80423..533c92f204 100644 --- a/app/src/test/java/com/afternote/afternote_fe/notification/NotificationIntentContractTest.kt +++ b/app/src/test/java/com/afternote/afternote_fe/notification/NotificationIntentContractTest.kt @@ -5,6 +5,7 @@ import android.content.Intent import com.afternote.core.common.notification.NotificationDestination import com.afternote.core.common.notification.NotificationPendingIntentFactory import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotEquals import org.junit.Assert.assertNotNull import org.junit.Assert.assertNull import org.junit.Test @@ -83,6 +84,63 @@ class NotificationIntentContractTest { assertEquals("occurrence-1", request?.occurrenceId) } + @Test + fun `서버 알림 ID를 PendingIntent 왕복으로 되읽는다`() { + val pendingIntent = + NotificationPendingIntentFactory.create( + context = RuntimeEnvironment.getApplication(), + source = NotificationEntrySource.FCM.contractValue, + occurrenceId = "notification:42", + destination = NotificationDestination.TIME_LETTER, + serverNotificationId = 42L, + ) + + val request = NotificationIntentContract.fromIntent(shadowOf(pendingIntent!!).savedIntent) + + assertEquals(42L, request?.serverNotificationId) + assertEquals(NotificationDestination.TIME_LETTER, request?.destination) + } + + @Test + fun `서버 data 는 목적지 키만 되읽는다`() { + val pendingIntent = + NotificationPendingIntentFactory.create( + context = RuntimeEnvironment.getApplication(), + source = NotificationEntrySource.FCM.contractValue, + occurrenceId = "notification:42", + destination = NotificationDestination.TIME_LETTER, + serverNotificationId = 42L, + serverData = mapOf("destination" to "TIME_LETTER_DETAIL", "timeLetterId" to "12", "unexpected" to "x"), + ) + + val request = NotificationIntentContract.fromIntent(shadowOf(pendingIntent!!).savedIntent) + + assertEquals(mapOf("destination" to "TIME_LETTER_DETAIL", "timeLetterId" to "12"), request?.serverData) + } + + @Test + fun `알림함 진입은 누를 때마다 새 발생이다`() { + val data = mapOf("destination" to "RECEIVER_LIST") + val first = NotificationEntryRequest.fromInbox(notificationId = 7L, data = data) + val second = NotificationEntryRequest.fromInbox(notificationId = 7L, data = data) + + assertEquals(NotificationEntrySource.INBOX, first.source) + assertEquals(7L, first.serverNotificationId) + assertNotEquals(first.identityKey, second.identityKey) + } + + @Test + fun `서버 알림 ID가 없거나 양수가 아니면 앱 알림으로 본다`() { + listOf(null, 0L, -1L).forEach { serverId -> + val intent = + notificationIntent().apply { + serverId?.let { putExtra(NotificationPendingIntentFactory.EXTRA_NOTIFICATION_SERVER_ID, it) } + } + + assertNull("server id '$serverId'", NotificationIntentContract.fromIntent(intent)?.serverNotificationId) + } + } + private fun notificationIntent( isNotificationEntry: Boolean = true, source: String? = NotificationEntrySource.FCM.contractValue, diff --git a/app/src/test/java/com/afternote/afternote_fe/notification/ServerNotificationDestinationTest.kt b/app/src/test/java/com/afternote/afternote_fe/notification/ServerNotificationDestinationTest.kt new file mode 100644 index 0000000000..b8102aa438 --- /dev/null +++ b/app/src/test/java/com/afternote/afternote_fe/notification/ServerNotificationDestinationTest.kt @@ -0,0 +1,99 @@ +package com.afternote.afternote_fe.notification + +import com.afternote.core.common.notification.NotificationDestination +import com.afternote.core.ui.Route +import com.afternote.core.ui.SettingStart +import com.afternote.feature.mindrecord.presentation.navigation.MindRecordRoute +import com.afternote.feature.timeletter.presentation.navigation.TimeLetterRoute +import org.junit.Assert.assertEquals +import org.junit.Test + +/** + * 서버 목적지 계약(BE `PushPayload` whitelist)을 앱 화면으로 옮기는 규칙의 회귀 기준 (#2321). + * + * 서버 목적지 하나하나가 어디로 가는지와, 필수 ID 가 깨졌을 때 그 목적지를 품은 탭으로 접히는지를 본다. + */ +class ServerNotificationDestinationTest { + @Test + fun `서버 whitelist 의 모든 목적지가 열 화면으로 옮겨진다`() { + val expected = + mapOf( + mapOf("destination" to "HOME") to tab(NotificationDestination.HOME), + mapOf("destination" to "RECORD_LIST") to tab(NotificationDestination.MIND_RECORD), + mapOf("destination" to "WEEKLY_REPORT") to tab(NotificationDestination.MIND_RECORD), + mapOf("destination" to "EASY_QUESTIONS") to tab(NotificationDestination.MIND_RECORD), + mapOf("destination" to "RECORD_DETAIL", "recordType" to "DAILY_QUESTION", "recordId" to "3") to + NotificationNavigation.MindRecord(MindRecordRoute.RecordDetailRoute(recordId = 3L, isDiary = false)), + mapOf("destination" to "DAILY_QUESTION", "questionId" to "8") to + NotificationNavigation.MindRecord(MindRecordRoute.DailyQuestionWriteRoute()), + mapOf("destination" to "TIME_LETTER_LIST") to tab(NotificationDestination.TIME_LETTER), + mapOf("destination" to "TIME_LETTER_DETAIL", "timeLetterId" to "12") to + NotificationNavigation.TimeLetter(listOf(TimeLetterRoute.TimeLetterDetailRoute(12L))), + mapOf("destination" to "TIME_LETTER_COMPOSE", "receiverId" to "4") to + NotificationNavigation.TimeLetter(listOf(TimeLetterRoute.TimeLetterWriteRoute(prefillReceiverId = 4L))), + mapOf("destination" to "RECEIVER_LIST") to setting(Route.Setting(start = SettingStart.RECIPIENT_LIST)), + mapOf("destination" to "INVITATION_DETAIL", "invitationId" to "6") to + setting(Route.Setting(start = SettingStart.RECIPIENT_LIST)), + mapOf("destination" to "RECEIVER_DETAIL", "receiverId" to "4") to + setting(Route.Setting(start = SettingStart.RECIPIENT_EDIT, receiverId = 4L)), + mapOf("destination" to "AGENT_SETTINGS") to setting(Route.Setting(start = SettingStart.DELEGATE)), + mapOf("destination" to "RETENTION_CONFIRMATION") to tab(NotificationDestination.HOME), + mapOf("destination" to "AGENT_CONFIRMATION", "linkId" to "x") to tab(NotificationDestination.HOME), + mapOf("destination" to "INVITATION", "linkId" to "x") to tab(NotificationDestination.HOME), + mapOf("destination" to "RECEIVER_HOME") to tab(NotificationDestination.HOME), + mapOf("destination" to "PLAN") to tab(NotificationDestination.HOME), + mapOf("destination" to "SUBSCRIPTION_MANAGEMENT") to tab(NotificationDestination.HOME), + ) + + expected.forEach { (data, navigation) -> + assertEquals("$data", navigation, ServerNotificationDestination.resolve(data)) + } + } + + @Test + fun `수정 강조 알림은 편지 상세 위에 수정 화면을 쌓는다`() { + assertEquals( + NotificationNavigation.TimeLetter( + listOf(TimeLetterRoute.TimeLetterDetailRoute(12L), TimeLetterRoute.TimeLetterWriteRoute(12L)), + ), + ServerNotificationDestination.resolve(mapOf("destination" to "TIME_LETTER_DETAIL", "timeLetterId" to "12", "action" to "EDIT")), + ) + } + + @Test + fun `필수 ID 가 없거나 숫자가 아니면 그 목적지를 품은 탭으로 접는다`() { + assertEquals( + tab(NotificationDestination.TIME_LETTER), + ServerNotificationDestination.resolve(mapOf("destination" to "TIME_LETTER_DETAIL", "timeLetterId" to "abc")), + ) + assertEquals( + tab(NotificationDestination.MIND_RECORD), + ServerNotificationDestination.resolve(mapOf("destination" to "RECORD_DETAIL", "recordType" to "DAILY_QUESTION")), + ) + assertEquals( + setting(Route.Setting(start = SettingStart.RECIPIENT_EDIT, receiverId = null)), + ServerNotificationDestination.resolve(mapOf("destination" to "RECEIVER_DETAIL", "receiverId" to "-1")), + ) + } + + @Test + fun `일기 상세는 찾을 달을 몰라 기록 탭으로 연다`() { + listOf("DIARY", "DEEP_THOUGHT").forEach { type -> + assertEquals( + tab(NotificationDestination.MIND_RECORD), + ServerNotificationDestination.resolve(mapOf("destination" to "RECORD_DETAIL", "recordType" to type, "recordId" to "3")), + ) + } + } + + @Test + fun `목적지가 없거나 모르는 값이면 홈이다`() { + listOf(emptyMap(), mapOf("destination" to "UNKNOWN"), mapOf("destination" to " ")).forEach { data -> + assertEquals(tab(NotificationDestination.HOME), ServerNotificationDestination.resolve(data)) + } + } + + private fun tab(destination: NotificationDestination) = NotificationNavigation.Tab(destination) + + private fun setting(route: Route.Setting) = NotificationNavigation.Setting(route) +} diff --git a/core/common/src/main/kotlin/com/afternote/core/common/notification/DailyNotificationWorker.kt b/core/common/src/main/kotlin/com/afternote/core/common/notification/DailyNotificationWorker.kt deleted file mode 100644 index 00eb76e80f..0000000000 --- a/core/common/src/main/kotlin/com/afternote/core/common/notification/DailyNotificationWorker.kt +++ /dev/null @@ -1,82 +0,0 @@ -package com.afternote.core.common.notification - -import android.Manifest -import android.annotation.SuppressLint -import android.app.NotificationChannel -import android.app.NotificationManager -import android.content.Context -import android.content.pm.PackageManager -import androidx.core.app.ActivityCompat -import androidx.core.app.NotificationCompat -import androidx.core.app.NotificationManagerCompat -import androidx.work.CoroutineWorker -import androidx.work.WorkerParameters -import com.afternote.core.common.R -import java.util.UUID - -class DailyNotificationWorker( - context: Context, - workerParams: WorkerParameters, -) : CoroutineWorker(context, workerParams) { - override suspend fun doWork(): Result { - createNotificationChannel() - showNotification() - return Result.success() - } - - @SuppressLint("MissingPermission") - private fun showNotification() { - val pendingIntent = - NotificationPendingIntentFactory.create( - context = applicationContext, - source = NOTIFICATION_SOURCE, - occurrenceId = UUID.randomUUID().toString(), - destination = NOTIFICATION_DESTINATION, - ) - - val notification = - NotificationCompat - .Builder(applicationContext, CHANNEL_ID) - .setSmallIcon(R.drawable.core_common_logo) - .setContentTitle(applicationContext.getString(R.string.core_common_notification_daily_title)) - .setContentText(applicationContext.getString(R.string.core_common_notification_daily_text)) - .setPriority(NotificationCompat.PRIORITY_DEFAULT) - .setAutoCancel(true) - .apply { - pendingIntent?.let { setContentIntent(it) } - }.build() - - // 런타임에서 POST_NOTIFICATIONS를 확인하므로 MissingPermission Lint는 억제해도 안전함. - if (ActivityCompat.checkSelfPermission( - applicationContext, - Manifest.permission.POST_NOTIFICATIONS, - ) == PackageManager.PERMISSION_GRANTED - ) { - NotificationManagerCompat.from(applicationContext).notify(NOTIFICATION_ID, notification) - } - } - - private fun createNotificationChannel() { - val name = applicationContext.getString(R.string.core_common_notification_daily_channel_name) - val importance = NotificationManager.IMPORTANCE_DEFAULT - val channel = NotificationChannel(CHANNEL_ID, name, importance) - val notificationManager = applicationContext.getSystemService(NotificationManager::class.java) - notificationManager?.createNotificationChannel(channel) - } - - companion object { - /** WorkManager unique work 이름 및 태그 ([NotificationScheduler]와 동일 값 유지). */ - const val UNIQUE_WORK_NAME = "daily_notification_work" - - private const val CHANNEL_ID = "DAILY_CHANNEL_ID" - private const val NOTIFICATION_ID = 1001 - private const val NOTIFICATION_SOURCE = "daily" - - /** - * 일일 알림 문구(`core_common_notification_daily_text` — 「오늘 하루 누구한테 가장 - * 고마웠나요?」)는 데일리 질문 답변을 재촉하는 말이다. 그 화면을 품은 탭이 마음의 기록이라 - * 탭 자체를 목적지로 둔다. 개별 질문 화면은 인자가 필요해 BE·FE 양쪽 계약이 더 서야 한다. - */ - private val NOTIFICATION_DESTINATION = NotificationDestination.MIND_RECORD - } -} diff --git a/core/common/src/main/kotlin/com/afternote/core/common/notification/LegacyDailyNotification.kt b/core/common/src/main/kotlin/com/afternote/core/common/notification/LegacyDailyNotification.kt new file mode 100644 index 0000000000..0dd9c6aa2e --- /dev/null +++ b/core/common/src/main/kotlin/com/afternote/core/common/notification/LegacyDailyNotification.kt @@ -0,0 +1,24 @@ +package com.afternote.core.common.notification + +import android.content.Context +import androidx.core.app.NotificationManagerCompat +import androidx.work.WorkManager + +/** + * 앱이 직접 예약하던 매일 09:00 데일리 알림의 흔적을 지운다 (#2321). + * + * 기록 재촉 알림은 이제 서버가 보낸다(BE 알림 B). 서버는 사용자가 고른 시각·요일에 맞추고, 하루 일반 + * 알림 1건 상한과 22~08시 이월을 다른 알림과 함께 판정한다. 앱이 따로 울리면 같은 재촉이 두 번 오고 + * 그 정책을 앱이 깬다. 그래서 예약을 그만두고, 이전 빌드가 남긴 WorkManager 예약과 알림 채널을 지운다. + * + * 둘 다 없는 것을 지워도 아무 일이 없어 실행마다 불러도 된다. 이름은 이전 빌드가 쓰던 값 그대로다. + */ +object LegacyDailyNotification { + fun clear(context: Context) { + WorkManager.getInstance(context).cancelUniqueWork(UNIQUE_WORK_NAME) + NotificationManagerCompat.from(context).deleteNotificationChannel(CHANNEL_ID) + } + + const val UNIQUE_WORK_NAME = "daily_notification_work" + const val CHANNEL_ID = "DAILY_CHANNEL_ID" +} diff --git a/core/common/src/main/kotlin/com/afternote/core/common/notification/NotificationPendingIntentFactory.kt b/core/common/src/main/kotlin/com/afternote/core/common/notification/NotificationPendingIntentFactory.kt index c41b97f70b..282ec3b84a 100644 --- a/core/common/src/main/kotlin/com/afternote/core/common/notification/NotificationPendingIntentFactory.kt +++ b/core/common/src/main/kotlin/com/afternote/core/common/notification/NotificationPendingIntentFactory.kt @@ -3,6 +3,7 @@ package com.afternote.core.common.notification import android.app.PendingIntent import android.content.Context import android.content.Intent +import android.os.Bundle /** * 앱 알림의 content [PendingIntent]를 동일한 Android 계약으로 생성한다. @@ -25,6 +26,10 @@ import android.content.Intent * @param occurrenceId 같은 출처 안에서 알림 발생을 구분하는 식별자 * @param destination 탭했을 때 열 최상위 화면. 생산자가 반드시 정한다 — 기본값을 두면 목적지 * 배선을 빠뜨린 알림이 조용히 홈으로만 떨어진다. + * @param serverNotificationId 서버가 만든 알림이면 그 ID. 탭한 뒤 현재 목적지 확인과 읽음 처리에 쓴다. + * 앱이 스스로 만든 알림은 null 이다. + * @param serverData 서버 알림의 목적지 data(`destination`·ID·`action`). 현재 목적지를 묻지 못할 때 이걸로 + * 안쪽 화면까지 연다. 거르는 것은 읽는 쪽 몫이다 — 여기서는 받은 문자열을 그대로 싣는다. */ object NotificationPendingIntentFactory { const val EXTRA_NOTIFICATION_ENTRY = "com.afternote.notification.ENTRY" @@ -37,12 +42,16 @@ object NotificationPendingIntentFactory { */ const val EXTRA_NOTIFICATION_OCCURRENCE_TOKEN = "com.afternote.notification.OCCURRENCE_TOKEN" const val EXTRA_NOTIFICATION_DESTINATION = "com.afternote.notification.DESTINATION" + const val EXTRA_NOTIFICATION_SERVER_ID = "com.afternote.notification.SERVER_ID" + const val EXTRA_NOTIFICATION_SERVER_DATA = "com.afternote.notification.SERVER_DATA" fun create( context: Context, source: String, occurrenceId: String, destination: NotificationDestination, + serverNotificationId: Long? = null, + serverData: Map = emptyMap(), ): PendingIntent? { val action = notificationAction(source = source, occurrenceId = occurrenceId) val launchIntent = @@ -53,6 +62,13 @@ object NotificationPendingIntentFactory { putExtra(EXTRA_NOTIFICATION_SOURCE, source) putExtra(EXTRA_NOTIFICATION_OCCURRENCE_TOKEN, occurrenceId) putExtra(EXTRA_NOTIFICATION_DESTINATION, destination.contractValue) + serverNotificationId?.let { putExtra(EXTRA_NOTIFICATION_SERVER_ID, it) } + if (serverData.isNotEmpty()) { + putExtra( + EXTRA_NOTIFICATION_SERVER_DATA, + Bundle().apply { serverData.forEach { (key, value) -> putString(key, value) } }, + ) + } this.action = action addFlags( Intent.FLAG_ACTIVITY_NEW_TASK or diff --git a/core/common/src/main/kotlin/com/afternote/core/common/notification/NotificationScheduler.kt b/core/common/src/main/kotlin/com/afternote/core/common/notification/NotificationScheduler.kt deleted file mode 100644 index 488af0b1aa..0000000000 --- a/core/common/src/main/kotlin/com/afternote/core/common/notification/NotificationScheduler.kt +++ /dev/null @@ -1,63 +0,0 @@ -package com.afternote.core.common.notification - -import android.content.Context -import androidx.work.Constraints -import androidx.work.ExistingPeriodicWorkPolicy -import androidx.work.PeriodicWorkRequest -import androidx.work.PeriodicWorkRequestBuilder -import androidx.work.WorkManager -import java.time.Duration -import java.time.LocalDateTime -import java.util.concurrent.TimeUnit - -/** - * 일 단위 알림을 WorkManager로 예약한다. - * - * **주의:** [PeriodicWorkRequest]는 배터리·Doze 등으로 지정 시각에 정확히 맞추지 못하고 시간이 밀릴 수 있다(Drift). - * 사용자 설정 시각에 정확히 울려야 하면 `AlarmManager.setExactAndAllowWhileIdle` 등으로 전환해야 한다. - */ -object NotificationScheduler { - fun scheduleDailyNotification( - context: Context, - hour: Int, - minute: Int, - ) { - val workManager = WorkManager.getInstance(context) - - val now = LocalDateTime.now() - var targetTime = - now - .withHour(hour) - .withMinute(minute) - .withSecond(0) - .withNano(0) - - if (targetTime.isBefore(now)) { - targetTime = targetTime.plusDays(1) - } - - val initialDelay = Duration.between(now, targetTime).toMillis() - - val dailyWorkRequest: PeriodicWorkRequest = - PeriodicWorkRequestBuilder( - 24, - TimeUnit.HOURS, - ).setInitialDelay(initialDelay, TimeUnit.MILLISECONDS) - .setConstraints(Constraints.Builder().setRequiresBatteryNotLow(true).build()) - .build() - - // 앱 콜드스타트마다 호출되므로 KEEP 으로 두지 않으면 매번 next trigger 가 새 initialDelay 로 갱신돼 - // 사용자가 알림 시각 전에 앱을 켜면 알림이 영원히 미뤄질 수 있다. - // 시간 변경 등 명시적 재예약이 필요할 때는 별도 API(예: reschedule) 로 CANCEL_AND_REENQUEUE 적용. - workManager.enqueueUniquePeriodicWork( - DailyNotificationWorker.UNIQUE_WORK_NAME, - ExistingPeriodicWorkPolicy.KEEP, - dailyWorkRequest, - ) - } - - /** [scheduleDailyNotification] 이 넣은 예약을 지운다. 예약이 없으면 아무 일도 하지 않는다. */ - fun cancelDailyNotification(context: Context) { - WorkManager.getInstance(context).cancelUniqueWork(DailyNotificationWorker.UNIQUE_WORK_NAME) - } -} diff --git a/core/common/src/main/res/values/strings.xml b/core/common/src/main/res/values/strings.xml deleted file mode 100644 index 701827bb21..0000000000 --- a/core/common/src/main/res/values/strings.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - Daily reminders - AFTERNOTE - 오늘 하루 누구한테 가장 고마웠나요? - diff --git a/core/data/src/main/java/com/afternote/core/data/di/CoreNotificationRepositoryModule.kt b/core/data/src/main/java/com/afternote/core/data/di/CoreNotificationRepositoryModule.kt new file mode 100644 index 0000000000..6dcd8108db --- /dev/null +++ b/core/data/src/main/java/com/afternote/core/data/di/CoreNotificationRepositoryModule.kt @@ -0,0 +1,17 @@ +package com.afternote.core.data.di + +import com.afternote.core.data.repoimpl.notification.NotificationRepositoryImpl +import com.afternote.core.domain.repository.notification.NotificationRepository +import dagger.Binds +import dagger.Module +import dagger.hilt.InstallIn +import dagger.hilt.components.SingletonComponent +import javax.inject.Singleton + +@Module +@InstallIn(SingletonComponent::class) +internal abstract class CoreNotificationRepositoryModule { + @Binds + @Singleton + abstract fun bindNotificationRepository(impl: NotificationRepositoryImpl): NotificationRepository +} diff --git a/core/data/src/main/java/com/afternote/core/data/repoimpl/notification/NotificationRepositoryImpl.kt b/core/data/src/main/java/com/afternote/core/data/repoimpl/notification/NotificationRepositoryImpl.kt new file mode 100644 index 0000000000..c55566dbfb --- /dev/null +++ b/core/data/src/main/java/com/afternote/core/data/repoimpl/notification/NotificationRepositoryImpl.kt @@ -0,0 +1,66 @@ +package com.afternote.core.data.repoimpl.notification + +import com.afternote.core.domain.repository.notification.NotificationEntry +import com.afternote.core.domain.repository.notification.NotificationInbox +import com.afternote.core.domain.repository.notification.NotificationInboxItem +import com.afternote.core.domain.repository.notification.NotificationRepository +import com.afternote.core.domain.repository.notification.NotificationTarget +import com.afternote.core.domain.result.runCatchingCancellable +import com.afternote.core.network.model.requireData +import com.afternote.core.network.model.requireStatus +import com.afternote.core.network.service.NotificationApiService +import javax.inject.Inject + +internal class NotificationRepositoryImpl + @Inject + constructor( + private val notificationApiService: NotificationApiService, + ) : NotificationRepository { + override suspend fun target(notificationId: Long): Result = + runCatchingCancellable { + val dto = notificationApiService.getTarget(notificationId).requireData() + NotificationTarget( + data = dto.data, + deleted = dto.deleted, + toast = dto.toast?.takeIf(String::isNotBlank), + ) + } + + override suspend fun markRead(notificationId: Long): Result = + runCatchingCancellable { + notificationApiService.markRead(notificationId).requireStatus() + } + + override suspend fun inbox(): Result = + runCatchingCancellable { + val dto = notificationApiService.getInbox(page = FIRST_PAGE).requireData() + NotificationInbox( + unreadCount = dto.unreadCount, + items = + dto.items.map { item -> + NotificationInboxItem( + id = item.id, + title = item.title, + body = item.body, + data = item.data, + isRead = item.readAt != null, + ) + }, + ) + } + + override suspend fun reportEntry(): Result = + runCatchingCancellable { + val dto = notificationApiService.reportEntry().requireData() + NotificationEntry( + // 서버가 「보여 주지 마라」 고 한 문구는 들고 다니지 않는다. + easyQuestions = + if (dto.showEasyQuestions) dto.easyQuestions.filter(String::isNotBlank) else emptyList(), + procedureCancelled = dto.procedureCancelled, + ) + } + + private companion object { + const val FIRST_PAGE = 0 + } + } diff --git a/core/data/src/main/java/com/afternote/core/data/repoimpl/push/PushTargetRepositoryImpl.kt b/core/data/src/main/java/com/afternote/core/data/repoimpl/push/PushTargetRepositoryImpl.kt index 22a963b140..1dd0659ab8 100644 --- a/core/data/src/main/java/com/afternote/core/data/repoimpl/push/PushTargetRepositoryImpl.kt +++ b/core/data/src/main/java/com/afternote/core/data/repoimpl/push/PushTargetRepositoryImpl.kt @@ -1,9 +1,13 @@ package com.afternote.core.data.repoimpl.push +import com.afternote.core.domain.push.PushPermission +import com.afternote.core.domain.push.PushRegistration import com.afternote.core.domain.repository.push.PushTargetRepository import com.afternote.core.domain.result.runCatchingCancellable import com.afternote.core.network.dto.DeletePushTokenRequestDto +import com.afternote.core.network.dto.PushInstallationRequestDto import com.afternote.core.network.dto.RegisterPushTokenRequestDto +import com.afternote.core.network.model.requireData import com.afternote.core.network.model.requireStatus import com.afternote.core.network.service.UserApiService import javax.inject.Inject @@ -19,12 +23,23 @@ internal class PushTargetRepositoryImpl constructor( private val userApiService: UserApiService, ) : PushTargetRepository { - override suspend fun register(targetId: String): Result = + override suspend fun register( + targetId: String, + installationId: String, + permission: PushPermission, + ): Result = runCatchingCancellable { - userApiService - .registerPushToken( - RegisterPushTokenRequestDto(token = targetId, platform = ANDROID_PLATFORM), - ).requireStatus() + val response = + userApiService + .registerPushToken( + RegisterPushTokenRequestDto( + token = targetId, + platform = ANDROID_PLATFORM, + installationId = installationId, + notificationPermission = permission.name, + ), + ).requireData() + PushRegistration(requiresReset = response.requiresReset == true) } override suspend fun unregister(targetId: String): Result = @@ -34,6 +49,17 @@ internal class PushTargetRepositoryImpl .requireStatus() } + override suspend fun reportPermission( + installationId: String, + permission: PushPermission, + ): Result = + runCatchingCancellable { + userApiService + .reportPushInstallation( + PushInstallationRequestDto(installationId = installationId, permission = permission.name), + ).requireStatus() + } + private companion object { /** 서버 `PushPlatform` enum 의 이름 그대로 보낸다. */ const val ANDROID_PLATFORM = "ANDROID" diff --git a/core/data/src/test/java/com/afternote/core/data/repoimpl/ReceiverListStateFlowTest.kt b/core/data/src/test/java/com/afternote/core/data/repoimpl/ReceiverListStateFlowTest.kt index 4e4bb7e4cd..cd9071a37b 100644 --- a/core/data/src/test/java/com/afternote/core/data/repoimpl/ReceiverListStateFlowTest.kt +++ b/core/data/src/test/java/com/afternote/core/data/repoimpl/ReceiverListStateFlowTest.kt @@ -5,6 +5,8 @@ import com.afternote.core.domain.model.ReceiverListState import com.afternote.core.domain.repository.UserReceiverRepository import com.afternote.core.model.user.Receiver import com.afternote.core.network.dto.DeletePushTokenRequestDto +import com.afternote.core.network.dto.PushInstallationDto +import com.afternote.core.network.dto.PushInstallationRequestDto import com.afternote.core.network.dto.PushTokenDto import com.afternote.core.network.dto.ReceiverDetailDto import com.afternote.core.network.dto.ReceiverListDto @@ -435,6 +437,9 @@ class ReceiverListStateFlowTest { override suspend fun deletePushToken(request: DeletePushTokenRequestDto): BaseResponse = TODO("이 테스트 미사용") + override suspend fun reportPushInstallation(request: PushInstallationRequestDto): BaseResponse = + TODO("이 테스트 미사용") + override suspend fun getMyPushSettings(): BaseResponse = TODO("이 테스트 미사용") override suspend fun updateMyPushSettings(request: UserUpdatePushSettingRequestDto): BaseResponse = diff --git a/core/data/src/test/java/com/afternote/core/data/repoimpl/ReceiverRequestFailureTest.kt b/core/data/src/test/java/com/afternote/core/data/repoimpl/ReceiverRequestFailureTest.kt index 7f3fddcd6f..b4340da650 100644 --- a/core/data/src/test/java/com/afternote/core/data/repoimpl/ReceiverRequestFailureTest.kt +++ b/core/data/src/test/java/com/afternote/core/data/repoimpl/ReceiverRequestFailureTest.kt @@ -3,6 +3,8 @@ package com.afternote.core.data.repoimpl import com.afternote.core.common.reporting.ErrorReporter import com.afternote.core.domain.error.ReceiverRequestRejectedException import com.afternote.core.network.dto.DeletePushTokenRequestDto +import com.afternote.core.network.dto.PushInstallationDto +import com.afternote.core.network.dto.PushInstallationRequestDto import com.afternote.core.network.dto.PushTokenDto import com.afternote.core.network.dto.ReceiverDetailDto import com.afternote.core.network.dto.ReceiverListDto @@ -202,6 +204,8 @@ private class CreateReceiverThrowingApiService( override suspend fun deletePushToken(request: DeletePushTokenRequestDto): BaseResponse = TODO("이 테스트 미사용") + override suspend fun reportPushInstallation(request: PushInstallationRequestDto): BaseResponse = TODO("이 테스트 미사용") + override suspend fun getMyPushSettings(): BaseResponse = TODO("이 테스트 미사용") override suspend fun updateMyPushSettings(request: UserUpdatePushSettingRequestDto): BaseResponse = diff --git a/core/data/src/test/java/com/afternote/core/data/repoimpl/ReceiverSessionBoundaryRaceTest.kt b/core/data/src/test/java/com/afternote/core/data/repoimpl/ReceiverSessionBoundaryRaceTest.kt index daee7b0188..94f87a4a77 100644 --- a/core/data/src/test/java/com/afternote/core/data/repoimpl/ReceiverSessionBoundaryRaceTest.kt +++ b/core/data/src/test/java/com/afternote/core/data/repoimpl/ReceiverSessionBoundaryRaceTest.kt @@ -5,6 +5,8 @@ import com.afternote.core.data.repoimpl.auth.AuthRepositoryImpl import com.afternote.core.datastore.LocalStoreRegistry import com.afternote.core.datastore.StoreScope import com.afternote.core.domain.push.DevicePushTargetProvider +import com.afternote.core.domain.push.PushPermission +import com.afternote.core.domain.push.PushRegistration import com.afternote.core.domain.repository.auth.AuthRepository import com.afternote.core.domain.repository.push.PushTargetRepository import com.afternote.core.model.user.Receiver @@ -12,6 +14,8 @@ import com.afternote.core.network.dto.DeletePushTokenRequestDto import com.afternote.core.network.dto.LoginDto import com.afternote.core.network.dto.LoginRequestDto import com.afternote.core.network.dto.LogoutRequestDto +import com.afternote.core.network.dto.PushInstallationDto +import com.afternote.core.network.dto.PushInstallationRequestDto import com.afternote.core.network.dto.PushTokenDto import com.afternote.core.network.dto.ReceiverDetailDto import com.afternote.core.network.dto.ReceiverListDto @@ -507,15 +511,26 @@ class ReceiverSessionBoundaryRaceTest { }, pushTargetRepository = object : PushTargetRepository { - override suspend fun register(targetId: String): Result = error("register 는 이 테스트에서 호출되면 안 됨") + override suspend fun register( + targetId: String, + installationId: String, + permission: PushPermission, + ): Result = error("register 는 이 테스트에서 호출되면 안 됨") override suspend fun unregister(targetId: String): Result = Result.success(Unit) + + override suspend fun reportPermission( + installationId: String, + permission: PushPermission, + ): Result = Result.success(Unit) }, devicePushTargetProvider = object : DevicePushTargetProvider { override suspend fun currentTargetId(): String? = error("currentTargetId 는 이 테스트에서 호출되면 안 됨") override suspend fun existingTargetId(): String? = null + + override suspend fun resetTargetId(): String? = error("resetTargetId 는 이 테스트에서 호출되면 안 됨") }, ) @@ -584,6 +599,9 @@ class ReceiverSessionBoundaryRaceTest { override suspend fun deletePushToken(request: DeletePushTokenRequestDto): BaseResponse = TODO("이 테스트 미사용") + override suspend fun reportPushInstallation(request: PushInstallationRequestDto): BaseResponse = + TODO("이 테스트 미사용") + override suspend fun getReceiverDetail(receiverId: Long): BaseResponse = TODO("이 테스트 미사용") override suspend fun updateReceiver( diff --git a/core/data/src/test/java/com/afternote/core/data/repoimpl/ReceiverUpdateRefreshTest.kt b/core/data/src/test/java/com/afternote/core/data/repoimpl/ReceiverUpdateRefreshTest.kt index f5f97a197a..a4316198d5 100644 --- a/core/data/src/test/java/com/afternote/core/data/repoimpl/ReceiverUpdateRefreshTest.kt +++ b/core/data/src/test/java/com/afternote/core/data/repoimpl/ReceiverUpdateRefreshTest.kt @@ -4,6 +4,8 @@ import com.afternote.core.common.reporting.ErrorReporter import com.afternote.core.domain.repository.UserReceiverRepository import com.afternote.core.model.user.Receiver import com.afternote.core.network.dto.DeletePushTokenRequestDto +import com.afternote.core.network.dto.PushInstallationDto +import com.afternote.core.network.dto.PushInstallationRequestDto import com.afternote.core.network.dto.PushTokenDto import com.afternote.core.network.dto.ReceiverDetailDto import com.afternote.core.network.dto.ReceiverListDto @@ -254,6 +256,8 @@ private class MutableReceiverApiService( override suspend fun deletePushToken(request: DeletePushTokenRequestDto): BaseResponse = TODO("이 테스트 미사용") + override suspend fun reportPushInstallation(request: PushInstallationRequestDto): BaseResponse = TODO("이 테스트 미사용") + override suspend fun getMyPushSettings(): BaseResponse = TODO("이 테스트 미사용") override suspend fun updateMyPushSettings(request: UserUpdatePushSettingRequestDto): BaseResponse = diff --git a/core/data/src/test/java/com/afternote/core/data/repoimpl/UserRepositoryImplTest.kt b/core/data/src/test/java/com/afternote/core/data/repoimpl/UserRepositoryImplTest.kt index aa6f503ab3..051bfe9905 100644 --- a/core/data/src/test/java/com/afternote/core/data/repoimpl/UserRepositoryImplTest.kt +++ b/core/data/src/test/java/com/afternote/core/data/repoimpl/UserRepositoryImplTest.kt @@ -8,6 +8,8 @@ import com.afternote.core.model.user.Receiver import com.afternote.core.model.user.ReceiverCreated import com.afternote.core.network.di.NetworkModule import com.afternote.core.network.dto.DeletePushTokenRequestDto +import com.afternote.core.network.dto.PushInstallationDto +import com.afternote.core.network.dto.PushInstallationRequestDto import com.afternote.core.network.dto.PushTokenDto import com.afternote.core.network.dto.ReceiverDetailDto import com.afternote.core.network.dto.ReceiverListDto @@ -652,6 +654,8 @@ private class FakeUserApiService( override suspend fun deletePushToken(request: DeletePushTokenRequestDto): BaseResponse = TODO("이 테스트 미사용") + override suspend fun reportPushInstallation(request: PushInstallationRequestDto): BaseResponse = TODO("이 테스트 미사용") + override suspend fun getReceiverDetail(receiverId: Long): BaseResponse = TODO("이 테스트 미사용") override suspend fun updateReceiver( diff --git a/core/data/src/test/java/com/afternote/core/data/repoimpl/auth/AuthRepositoryImplTest.kt b/core/data/src/test/java/com/afternote/core/data/repoimpl/auth/AuthRepositoryImplTest.kt index c0f1814473..7916020aa2 100644 --- a/core/data/src/test/java/com/afternote/core/data/repoimpl/auth/AuthRepositoryImplTest.kt +++ b/core/data/src/test/java/com/afternote/core/data/repoimpl/auth/AuthRepositoryImplTest.kt @@ -8,6 +8,8 @@ import com.afternote.core.datastore.StoreScope import com.afternote.core.datastore.TokenDataSource import com.afternote.core.domain.error.CoreAuthFailure import com.afternote.core.domain.push.DevicePushTargetProvider +import com.afternote.core.domain.push.PushPermission +import com.afternote.core.domain.push.PushRegistration import com.afternote.core.domain.repository.push.PushTargetRepository import com.afternote.core.network.dto.LoginDto import com.afternote.core.network.dto.LoginRequestDto @@ -565,12 +567,16 @@ private class RecordingDevicePushTargetProvider( existingTargetIdCalls++ return targetId } + + override suspend fun resetTargetId(): String? = error("resetTargetId 는 이 테스트에서 호출되면 안 됨") } private class ThrowingDevicePushTargetProvider : DevicePushTargetProvider { override suspend fun currentTargetId(): String? = throw IllegalStateException("API disabled") override suspend fun existingTargetId(): String? = throw IllegalStateException("API disabled") + + override suspend fun resetTargetId(): String? = error("resetTargetId 는 이 테스트에서 호출되면 안 됨") } private class FakePushTargetRepository( @@ -579,12 +585,21 @@ private class FakePushTargetRepository( ) : PushTargetRepository { val unregistered = mutableListOf() - override suspend fun register(targetId: String): Result = - if (failing) Result.failure(IllegalStateException("등록 실패")) else Result.success(Unit) + override suspend fun register( + targetId: String, + installationId: String, + permission: PushPermission, + ): Result = + if (failing) Result.failure(IllegalStateException("등록 실패")) else Result.success(PushRegistration(requiresReset = false)) override suspend fun unregister(targetId: String): Result { unregistered += targetId onUnregister() return if (failing) Result.failure(IllegalStateException("해제 실패")) else Result.success(Unit) } + + override suspend fun reportPermission( + installationId: String, + permission: PushPermission, + ): Result = Result.success(Unit) } diff --git a/core/data/src/test/java/com/afternote/core/data/repoimpl/auth/SessionBoundReissueTest.kt b/core/data/src/test/java/com/afternote/core/data/repoimpl/auth/SessionBoundReissueTest.kt index f610c3e07f..9a5647c566 100644 --- a/core/data/src/test/java/com/afternote/core/data/repoimpl/auth/SessionBoundReissueTest.kt +++ b/core/data/src/test/java/com/afternote/core/data/repoimpl/auth/SessionBoundReissueTest.kt @@ -10,6 +10,8 @@ import com.afternote.core.datastore.StoreScope import com.afternote.core.datastore.TokenDataSource import com.afternote.core.domain.error.SessionChangedException import com.afternote.core.domain.push.DevicePushTargetProvider +import com.afternote.core.domain.push.PushPermission +import com.afternote.core.domain.push.PushRegistration import com.afternote.core.domain.repository.push.PushTargetRepository import com.afternote.core.network.dto.LoginDto import com.afternote.core.network.dto.LoginRequestDto @@ -313,13 +315,24 @@ private object LogoutOnlyAuthApiService : AuthApiService { } private object NoopPushTargetRepository : PushTargetRepository { - override suspend fun register(targetId: String): Result = error("register 는 이 테스트에서 호출되면 안 됨") + override suspend fun register( + targetId: String, + installationId: String, + permission: PushPermission, + ): Result = error("register 는 이 테스트에서 호출되면 안 됨") override suspend fun unregister(targetId: String): Result = Result.success(Unit) + + override suspend fun reportPermission( + installationId: String, + permission: PushPermission, + ): Result = Result.success(Unit) } private object NoDevicePushTargetProvider : DevicePushTargetProvider { override suspend fun currentTargetId(): String? = error("currentTargetId 는 이 테스트에서 호출되면 안 됨") override suspend fun existingTargetId(): String? = null + + override suspend fun resetTargetId(): String? = error("resetTargetId 는 이 테스트에서 호출되면 안 됨") } diff --git a/core/domain/src/main/java/com/afternote/core/domain/push/DevicePushTargetProvider.kt b/core/domain/src/main/java/com/afternote/core/domain/push/DevicePushTargetProvider.kt index b61b7a0d9d..f838c70aea 100644 --- a/core/domain/src/main/java/com/afternote/core/domain/push/DevicePushTargetProvider.kt +++ b/core/domain/src/main/java/com/afternote/core/domain/push/DevicePushTargetProvider.kt @@ -32,4 +32,12 @@ interface DevicePushTargetProvider { * 발급된 적이 없거나 조회에 실패하면 null. 구현은 예외를 올리지 않는다. */ suspend fun existingTargetId(): String? + + /** + * 지금 식별자를 버리고 새로 발급받는다 (#2321). 서버가 이 식별자를 무효(FCM UNREGISTERED)로 + * 판정했을 때만 쓴다 — 무효 판정은 같은 값을 다시 등록해도 풀리지 않는다. + * + * 실패하면 null. 구현은 예외를 올리지 않는다. + */ + suspend fun resetTargetId(): String? } diff --git a/core/domain/src/main/java/com/afternote/core/domain/push/PushPermission.kt b/core/domain/src/main/java/com/afternote/core/domain/push/PushPermission.kt new file mode 100644 index 0000000000..d35ec6d040 --- /dev/null +++ b/core/domain/src/main/java/com/afternote/core/domain/push/PushPermission.kt @@ -0,0 +1,14 @@ +package com.afternote.core.domain.push + +/** + * 이 기기에서 앱 알림이 사용자에게 보이는지 (#2321). + * + * 서버는 OS 권한을 직접 읽을 수 없어 앱이 보고한 이 값으로 권한 거부 기기의 푸시를 건너뛴다. + * [UNKNOWN] 은 서버의 레거시 기본값과 같은 이름이라 계약에 남겨 두지만 앱은 보내지 않는다 — + * 앱은 언제든 지금 값을 읽을 수 있다. + */ +enum class PushPermission { + UNKNOWN, + GRANTED, + DENIED, +} diff --git a/core/domain/src/main/java/com/afternote/core/domain/push/PushRegistration.kt b/core/domain/src/main/java/com/afternote/core/domain/push/PushRegistration.kt new file mode 100644 index 0000000000..7fc732be40 --- /dev/null +++ b/core/domain/src/main/java/com/afternote/core/domain/push/PushRegistration.kt @@ -0,0 +1,11 @@ +package com.afternote.core.domain.push + +/** + * 서버가 등록을 받고 돌려준 판정 (#2321). + * + * @property requiresReset 서버가 이 식별자로 보낸 발송에서 FCM UNREGISTERED 를 받았다. 같은 값을 다시 + * 등록해도 신호가 지워지지 않으므로, 기기가 새 식별자를 발급받아 등록해야 푸시가 다시 닿는다. + */ +data class PushRegistration( + val requiresReset: Boolean, +) diff --git a/core/domain/src/main/java/com/afternote/core/domain/repository/notification/NotificationRepository.kt b/core/domain/src/main/java/com/afternote/core/domain/repository/notification/NotificationRepository.kt new file mode 100644 index 0000000000..630d54057f --- /dev/null +++ b/core/domain/src/main/java/com/afternote/core/domain/repository/notification/NotificationRepository.kt @@ -0,0 +1,61 @@ +package com.afternote.core.domain.repository.notification + +/** + * 서버가 만든 알림(인앱·푸시 공통 ID)과 앱 진입 문맥을 다루는 계약 (#2321). + * + * 푸시 payload 는 발송 시점의 사진이다. 탭한 시점에는 대상이 지워졌거나 이미 답한 질문일 수 있어 + * 화면을 고르기 전에 [target] 으로 다시 묻는다. payload 자체는 열람 권한이 아니다. + */ +interface NotificationRepository { + suspend fun target(notificationId: Long): Result + + suspend fun markRead(notificationId: Long): Result + + /** 알림함 첫 페이지(최대 50개)와 전체 미읽음 수. */ + suspend fun inbox(): Result + + /** + * 앱에 들어왔다고 알린다. 서버는 이걸로 활동 시각을 갱신하고, 오래 비웠다 돌아온 사용자에게 줄 + * 쉬운 질문과 진행 중이던 보관 확인 절차가 취소됐는지를 돌려준다. + */ + suspend fun reportEntry(): Result +} + +/** + * 알림을 탭했을 때 지금 열어야 할 곳. + * + * @property data FCM data 와 같은 문자열 맵(`destination` 과 그 목적지의 ID·`action`). 앱 화면으로의 + * 번역은 app 몫이다. + * @property deleted 대상이 지워졌다. [data] 는 이미 그 목록을 가리킨다. + * @property toast 서버가 정한 안내 문구. 없으면 null. + */ +data class NotificationTarget( + val data: Map, + val deleted: Boolean, + val toast: String?, +) + +data class NotificationInbox( + val unreadCount: Long, + val items: List, +) + +/** 알림함 한 줄. [data] 는 FCM data 와 같은 형식이라 탭하면 같은 목적지 해석을 탄다. */ +data class NotificationInboxItem( + val id: Long, + val title: String, + val body: String, + val data: Map, + val isRead: Boolean, +) + +/** + * 앱 진입 문맥. + * + * @property easyQuestions 오래 비웠다 돌아온 사용자에게 보여 줄 쉬운 질문 문구. 보여 줄 때가 아니면 빈 목록이다. + * @property procedureCancelled 이번 진입으로 진행 중이던 보관 확인 절차가 취소됐다. + */ +data class NotificationEntry( + val easyQuestions: List, + val procedureCancelled: Boolean, +) diff --git a/core/domain/src/main/java/com/afternote/core/domain/repository/push/PushTargetRepository.kt b/core/domain/src/main/java/com/afternote/core/domain/repository/push/PushTargetRepository.kt index befe6b464f..b732e00d6f 100644 --- a/core/domain/src/main/java/com/afternote/core/domain/repository/push/PushTargetRepository.kt +++ b/core/domain/src/main/java/com/afternote/core/domain/repository/push/PushTargetRepository.kt @@ -1,5 +1,8 @@ package com.afternote.core.domain.repository.push +import com.afternote.core.domain.push.PushPermission +import com.afternote.core.domain.push.PushRegistration + /** * 이 기기의 푸시 대상 식별자([com.afternote.core.domain.push.DevicePushTargetProvider])를 * 서버에 알리고 지우는 계약 (#1493). @@ -7,12 +10,28 @@ package com.afternote.core.domain.repository.push * 서버는 등록된 식별자로만 푸시를 보낸다. 등록이 없으면 알림 권한이 있든 없든 푸시는 * 기기에 **도달조차 하지 않는다** — 수신부(#779)와 진입 인프라(#1310)가 다 갖춰져도 마찬가지다. * - * 두 연산 모두 서버가 멱등으로 처리하므로 재호출이 안전하다. + * [installationId] 는 앱 설치마다 한 번 만든 UUID 다 (#2321). 대상 식별자가 회전해도 그대로라 + * 서버가 같은 설치의 권한 보고와 토큰을 묶는다. + * + * 모든 연산을 서버가 멱등으로 처리하므로 재호출이 안전하다. */ interface PushTargetRepository { - /** 로그인 확정·식별자 회전 시 등록한다. 같은 값 재등록은 갱신(upsert)이다. */ - suspend fun register(targetId: String): Result + /** 로그인 확정·식별자 회전·권한 변경 시 등록한다. 같은 값 재등록은 갱신(upsert)이다. */ + suspend fun register( + targetId: String, + installationId: String, + permission: PushPermission, + ): Result /** 로그아웃 시 해제한다. 서버에 없는 값이어도 성공이다. */ suspend fun unregister(targetId: String): Result + + /** + * 이 설치의 OS 알림 권한을 보고한다 (#2321). 대상 식별자가 아직 없어도 부를 수 있다 — + * FCM 발급에 실패한 기기라도 서버가 「권한 거부」 를 알아야 대체 채널로 돌린다. + */ + suspend fun reportPermission( + installationId: String, + permission: PushPermission, + ): Result } diff --git a/core/network/src/main/kotlin/com/afternote/core/network/di/ServiceModule.kt b/core/network/src/main/kotlin/com/afternote/core/network/di/ServiceModule.kt index 018f4c70e0..4381596031 100644 --- a/core/network/src/main/kotlin/com/afternote/core/network/di/ServiceModule.kt +++ b/core/network/src/main/kotlin/com/afternote/core/network/di/ServiceModule.kt @@ -6,6 +6,7 @@ import com.afternote.core.network.service.AccountApiService import com.afternote.core.network.service.AppVersionApiService import com.afternote.core.network.service.AuthApiService import com.afternote.core.network.service.ImageApiService +import com.afternote.core.network.service.NotificationApiService import com.afternote.core.network.service.ReceiverInvitationApiService import com.afternote.core.network.service.TokenApiService import com.afternote.core.network.service.UserApiService @@ -72,4 +73,8 @@ object ServiceModule { @Singleton fun provideReceiverInvitationApiService(retrofit: Retrofit): ReceiverInvitationApiService = retrofit.create() + + @Provides + @Singleton + fun provideNotificationApiService(retrofit: Retrofit): NotificationApiService = retrofit.create() } diff --git a/core/network/src/main/kotlin/com/afternote/core/network/dto/NotificationDto.kt b/core/network/src/main/kotlin/com/afternote/core/network/dto/NotificationDto.kt new file mode 100644 index 0000000000..2395537943 --- /dev/null +++ b/core/network/src/main/kotlin/com/afternote/core/network/dto/NotificationDto.kt @@ -0,0 +1,105 @@ +package com.afternote.core.network.dto + +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.JsonElement + +// ======================================== +// Request +// ======================================== + +/** + * `PUT users/me/notification-preferences` 요청 (#2321). + * + * [time] 은 한국 시간 `HH:mm` 이다. 서버는 초·소수초가 0 이 아니면 거부한다. + * [weekdays] 는 `MONDAY`…`SUNDAY`, [weeklyGoal] 은 1~7 이다. + */ +@Serializable +data class NotificationPreferencesRequestDto( + @SerialName("enabled") val enabled: Boolean, + @SerialName("time") val time: String, + @SerialName("weekdays") val weekdays: List, + @SerialName("weeklyGoal") val weeklyGoal: Int, +) + +/** `PUT users/me/notification-preferences/delegate` 요청. 이름 100자·연락처 20자 이하, 둘 다 필수. */ +@Serializable +data class NotificationDelegateRequestDto( + @SerialName("name") val name: String, + @SerialName("phone") val phone: String, +) + +/** `POST users/me/notification-preferences/anniversaries` 요청. 존재하는 달력 날짜만 받는다. */ +@Serializable +data class NotificationAnniversaryRequestDto( + @SerialName("receiverId") val receiverId: Long, + @SerialName("month") val month: Int, + @SerialName("day") val day: Int, +) + +// ======================================== +// Response +// ======================================== + +/** + * `GET·PUT users/me/notification-preferences` 응답. + * + * [time] 은 서버 `LocalTime` 을 Jackson 이 쓴 그대로다. 기본 설정이면 `"18:00:00"` 문자열이지만, + * 서버 직렬화 설정에 따라 `[18,0]` 배열로도 온다. 해석은 data 계층이 한다 — 여기서 한 형태로 고정하면 + * 서버 설정 하나에 화면 전체가 파싱 오류로 죽는다. + */ +@Serializable +data class NotificationPreferencesDto( + @SerialName("enabled") val enabled: Boolean, + @SerialName("time") val time: JsonElement, + @SerialName("weekdays") val weekdays: List, + @SerialName("weeklyGoal") val weeklyGoal: Int, +) + +/** 대리인. 지정 전이면 둘 다 null 이다. */ +@Serializable +data class NotificationDelegateDto( + @SerialName("name") val name: String? = null, + @SerialName("phone") val phone: String? = null, +) + +@Serializable +data class NotificationAnniversaryDto( + @SerialName("id") val id: Long, + @SerialName("receiverId") val receiverId: Long, + @SerialName("month") val month: Int, + @SerialName("day") val day: Int, +) + +/** + * `POST users/me/notification-preferences/entry` 응답. + * + * [easyQuestions] 는 작성 화면에 보여 줄 문구다. daily question ID 가 아니다. + */ +@Serializable +data class NotificationEntryDto( + @SerialName("showEasyQuestions") val showEasyQuestions: Boolean, + @SerialName("easyQuestions") val easyQuestions: List, + @SerialName("procedureCancelled") val procedureCancelled: Boolean, +) + +/** `GET users/notifications` 응답. [unreadCount] 는 이 페이지가 아니라 전체 미읽음 수다. */ +@Serializable +data class NotificationInboxDto( + @SerialName("unreadCount") val unreadCount: Long, + @SerialName("items") val items: List, +) + +/** + * 알림함 한 줄. [data] 는 FCM data 와 같은 문자열 맵이다 — 탭하면 같은 목적지 해석을 탄다. + * [status] 는 서버 처리 상태라 화면에 보여 주지 않는다. + */ +@Serializable +data class NotificationInboxItemDto( + @SerialName("id") val id: Long, + @SerialName("title") val title: String, + @SerialName("body") val body: String, + @SerialName("data") val data: Map, + @SerialName("status") val status: String, + @SerialName("readAt") val readAt: String? = null, +) diff --git a/core/network/src/main/kotlin/com/afternote/core/network/dto/NotificationTargetDto.kt b/core/network/src/main/kotlin/com/afternote/core/network/dto/NotificationTargetDto.kt new file mode 100644 index 0000000000..5e82a29a47 --- /dev/null +++ b/core/network/src/main/kotlin/com/afternote/core/network/dto/NotificationTargetDto.kt @@ -0,0 +1,17 @@ +package com.afternote.core.network.dto + +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable + +/** + * `GET users/notifications/{id}/target` 응답 (#2321). + * + * [data] 는 FCM data 와 같은 문자열 맵이다 — `destination` 과 그 목적지의 ID·`action` 이 들어 있다. + */ +@Serializable +data class NotificationTargetDto( + @SerialName("data") val data: Map, + @SerialName("deleted") val deleted: Boolean, + @SerialName("toast") val toast: String? = null, + @SerialName("backDestination") val backDestination: String? = null, +) diff --git a/core/network/src/main/kotlin/com/afternote/core/network/dto/PushTokenDto.kt b/core/network/src/main/kotlin/com/afternote/core/network/dto/PushTokenDto.kt index f1104bbc4c..c12cbabd4b 100644 --- a/core/network/src/main/kotlin/com/afternote/core/network/dto/PushTokenDto.kt +++ b/core/network/src/main/kotlin/com/afternote/core/network/dto/PushTokenDto.kt @@ -10,12 +10,22 @@ import kotlinx.serialization.Serializable /** * `PUT users/push-tokens` 요청 (#1493). * - * 서버는 같은 token 을 upsert 로 처리하므로 재호출이 안전하다. + * 서버는 같은 token 을 upsert 로 처리하므로 재호출이 안전하다. [installationId]·[notificationPermission] + * 은 서버 계약상 선택 필드지만 앱은 늘 싣는다 (#2321) — 빼면 서버가 이 토큰의 권한을 `UNKNOWN` 으로 둔다. */ @Serializable data class RegisterPushTokenRequestDto( @SerialName("token") val token: String, @SerialName("platform") val platform: String, + @SerialName("installationId") val installationId: String, + @SerialName("notificationPermission") val notificationPermission: String, +) + +/** `PUT users/push-installations` 요청 (#2321). 토큰 없이도 설치별 OS 알림 권한을 보고한다. */ +@Serializable +data class PushInstallationRequestDto( + @SerialName("installationId") val installationId: String, + @SerialName("permission") val permission: String, ) /** `DELETE users/push-tokens` 요청 — 없는 token 을 보내도 200 이다(서버 멱등). */ @@ -28,9 +38,18 @@ data class DeletePushTokenRequestDto( // Response // ======================================== +@Serializable +data class PushInstallationDto( + @SerialName("installationId") val installationId: String, + @SerialName("permission") val permission: String, + @SerialName("showPermissionBanner") val showPermissionBanner: Boolean, +) + @Serializable data class PushTokenDto( @SerialName("token") val token: String, @SerialName("platform") val platform: String, @SerialName("lastSeenAt") val lastSeenAt: String? = null, + /** 서버가 이 토큰을 FCM UNREGISTERED 로 판정했다 — 앱이 재설정 안내를 띄운다 (#2321). 옛 서버는 보내지 않는다. */ + @SerialName("requiresReset") val requiresReset: Boolean? = null, ) diff --git a/core/network/src/main/kotlin/com/afternote/core/network/service/NotificationApiService.kt b/core/network/src/main/kotlin/com/afternote/core/network/service/NotificationApiService.kt new file mode 100644 index 0000000000..d1e2b45e1b --- /dev/null +++ b/core/network/src/main/kotlin/com/afternote/core/network/service/NotificationApiService.kt @@ -0,0 +1,87 @@ +package com.afternote.core.network.service + +import com.afternote.core.network.dto.NotificationAnniversaryDto +import com.afternote.core.network.dto.NotificationAnniversaryRequestDto +import com.afternote.core.network.dto.NotificationDelegateDto +import com.afternote.core.network.dto.NotificationDelegateRequestDto +import com.afternote.core.network.dto.NotificationEntryDto +import com.afternote.core.network.dto.NotificationInboxDto +import com.afternote.core.network.dto.NotificationPreferencesDto +import com.afternote.core.network.dto.NotificationPreferencesRequestDto +import com.afternote.core.network.dto.NotificationTargetDto +import com.afternote.core.network.model.BaseResponse +import retrofit2.http.Body +import retrofit2.http.DELETE +import retrofit2.http.GET +import retrofit2.http.PATCH +import retrofit2.http.POST +import retrofit2.http.PUT +import retrofit2.http.Path +import retrofit2.http.Query + +/** + * 서버 알림(BE#317 비결제 알림 A~E)의 사용자 쪽 API (#2321). 전부 인증이 필요하다. + * + * 기기 등록(`users/push-tokens`·`users/push-installations`)은 계정 API 와 수명이 같아 + * [UserApiService] 에 남긴다. 여기는 알림 그 자체 — 알림함·탭 목적지·앱 진입 문맥·알림 설정이다. + */ +interface NotificationApiService { + /** 알림함. 0 부터, 한 페이지 50개, ID 내림차순. 취소된 알림은 빠진다. */ + @GET("users/notifications") + suspend fun getInbox( + @Query("page") page: Int, + ): BaseResponse + + /** 알림을 탭한 시점의 현재 목적지. 지워진 대상이면 목록과 안내 문구를 준다. */ + @GET("users/notifications/{id}/target") + suspend fun getTarget( + @Path("id") notificationId: Long, + ): BaseResponse + + /** 본인 알림 읽음 처리. */ + @PATCH("users/notifications/{id}/read") + suspend fun markRead( + @Path("id") notificationId: Long, + ): BaseResponse + + /** + * 앱 실행·복귀 문맥. 이전 방문 기준 30일 복귀 여부와 쉬운 질문, 대리인 절차 취소 결과를 주고 + * 서버의 활동 시각을 갱신한다. 종료 상태에서의 실행·로그인 직후에 부른다. + */ + @POST("users/me/notification-preferences/entry") + suspend fun reportEntry(): BaseResponse + + @GET("users/me/notification-preferences") + suspend fun getPreferences(): BaseResponse + + /** 바꾸면 서버가 이전 대기 중인 기록 알림(B)을 취소한다. */ + @PUT("users/me/notification-preferences") + suspend fun updatePreferences( + @Body request: NotificationPreferencesRequestDto, + ): BaseResponse + + @GET("users/me/notification-preferences/delegate") + suspend fun getDelegate(): BaseResponse + + /** 바꾸면 이전 대리인에게 간 확인 링크가 무효가 된다. */ + @PUT("users/me/notification-preferences/delegate") + suspend fun updateDelegate( + @Body request: NotificationDelegateRequestDto, + ): BaseResponse + + @DELETE("users/me/notification-preferences/delegate") + suspend fun deleteDelegate(): BaseResponse + + @GET("users/me/notification-preferences/anniversaries") + suspend fun getAnniversaries(): BaseResponse> + + @POST("users/me/notification-preferences/anniversaries") + suspend fun createAnniversary( + @Body request: NotificationAnniversaryRequestDto, + ): BaseResponse + + @DELETE("users/me/notification-preferences/anniversaries/{id}") + suspend fun deleteAnniversary( + @Path("id") anniversaryId: Long, + ): BaseResponse +} diff --git a/core/network/src/main/kotlin/com/afternote/core/network/service/UserApiService.kt b/core/network/src/main/kotlin/com/afternote/core/network/service/UserApiService.kt index f201b49233..80a0438767 100644 --- a/core/network/src/main/kotlin/com/afternote/core/network/service/UserApiService.kt +++ b/core/network/src/main/kotlin/com/afternote/core/network/service/UserApiService.kt @@ -1,6 +1,8 @@ package com.afternote.core.network.service import com.afternote.core.network.dto.DeletePushTokenRequestDto +import com.afternote.core.network.dto.PushInstallationDto +import com.afternote.core.network.dto.PushInstallationRequestDto import com.afternote.core.network.dto.PushTokenDto import com.afternote.core.network.dto.ReceiverDetailDto import com.afternote.core.network.dto.ReceiverListDto @@ -101,6 +103,12 @@ interface UserApiService { @Body request: DeletePushTokenRequestDto, ): BaseResponse + /** 설치별 OS 알림 권한 보고 (#2321). 앱 실행·권한 변경 때 부른다. FCM 토큰이 없어도 된다. */ + @PUT("users/push-installations") + suspend fun reportPushInstallation( + @Body request: PushInstallationRequestDto, + ): BaseResponse + // 푸시 알림 설정 조회 @GET("users/push-settings") suspend fun getMyPushSettings(): BaseResponse diff --git a/core/network/src/test/kotlin/com/afternote/core/network/service/ApiWireContractSmokeTest.kt b/core/network/src/test/kotlin/com/afternote/core/network/service/ApiWireContractSmokeTest.kt index 262f774da1..3dcce462e5 100644 --- a/core/network/src/test/kotlin/com/afternote/core/network/service/ApiWireContractSmokeTest.kt +++ b/core/network/src/test/kotlin/com/afternote/core/network/service/ApiWireContractSmokeTest.kt @@ -5,7 +5,9 @@ import com.afternote.core.network.dto.DeletePushTokenRequestDto import com.afternote.core.network.dto.EmailFindRequestDto import com.afternote.core.network.dto.FindSendCodeRequestDto import com.afternote.core.network.dto.LoginDto +import com.afternote.core.network.dto.NotificationPreferencesRequestDto import com.afternote.core.network.dto.PasswordFindRequestDto +import com.afternote.core.network.dto.PushInstallationRequestDto import com.afternote.core.network.dto.RegisterPushTokenRequestDto import com.afternote.core.network.dto.SocialLoginRequestDto import com.afternote.core.network.dto.delivery.ConditionStateDto @@ -54,6 +56,7 @@ class ApiWireContractSmokeTest { private lateinit var appVersionService: AppVersionApiService private lateinit var authService: AuthApiService private lateinit var userService: UserApiService + private lateinit var notificationService: NotificationApiService @Before fun setUp() { @@ -84,6 +87,7 @@ class ApiWireContractSmokeTest { appVersionService = publicRetrofit.create(AppVersionApiService::class.java) authService = publicRetrofit.create(AuthApiService::class.java) userService = authenticatedRetrofit.create(UserApiService::class.java) + notificationService = authenticatedRetrofit.create(NotificationApiService::class.java) } @Test @@ -163,7 +167,11 @@ class ApiWireContractSmokeTest { requestBody = wireJson .parseToJsonElement( - """{"token":"fcm-token","platform":"ANDROID"}""", + """ + {"token":"fcm-token","platform":"ANDROID", + "installationId":"d92560f1-ad73-4bfb-8759-017c61ad5168", + "notificationPermission":"GRANTED"} + """.trimIndent(), ).jsonObject, responseBody = """ @@ -182,7 +190,12 @@ class ApiWireContractSmokeTest { val result = userService.registerPushToken( - RegisterPushTokenRequestDto(token = "fcm-token", platform = "ANDROID"), + RegisterPushTokenRequestDto( + token = "fcm-token", + platform = "ANDROID", + installationId = "d92560f1-ad73-4bfb-8759-017c61ad5168", + notificationPermission = "GRANTED", + ), ) assertEquals(200, result.status) @@ -211,6 +224,145 @@ class ApiWireContractSmokeTest { assertExactlyOneRecordedRequest("DELETE", "/api/v1/users/push-tokens") } + @Test + fun `push installation PUT reports permission without a token`() = + runTest { + installExpectation( + method = "PUT", + path = "/api/v1/users/push-installations", + requestHeaders = mapOf("Authorization" to "Bearer contract-token"), + requestBody = + wireJson + .parseToJsonElement( + """{"installationId":"d92560f1-ad73-4bfb-8759-017c61ad5168","permission":"DENIED"}""", + ).jsonObject, + responseBody = + """ + { + "status": 200, + "code": 200, + "message": "ok", + "data": { + "installationId": "d92560f1-ad73-4bfb-8759-017c61ad5168", + "permission": "DENIED", + "showPermissionBanner": true + } + } + """.trimIndent(), + ) + + val result = + userService.reportPushInstallation( + PushInstallationRequestDto( + installationId = "d92560f1-ad73-4bfb-8759-017c61ad5168", + permission = "DENIED", + ), + ) + + assertEquals(true, result.data?.showPermissionBanner) + assertExactlyOneRecordedRequest("PUT", "/api/v1/users/push-installations") + } + + @Test + fun `notification target GET decodes destination map and deleted toast`() = + runTest { + installExpectation( + method = "GET", + path = "/api/v1/users/notifications/42/target", + requestHeaders = mapOf("Authorization" to "Bearer contract-token"), + responseBody = + """ + { + "status": 200, + "code": 200, + "message": "ok", + "data": { + "data": {"destination": "TIME_LETTER_LIST"}, + "deleted": true, + "toast": "삭제된 항목이에요", + "backDestination": "HOME" + } + } + """.trimIndent(), + ) + + val result = notificationService.getTarget(42L) + + assertEquals("TIME_LETTER_LIST", result.data?.data?.get("destination")) + assertEquals(true, result.data?.deleted) + assertEquals("삭제된 항목이에요", result.data?.toast) + assertExactlyOneRecordedRequest("GET", "/api/v1/users/notifications/42/target") + } + + @Test + fun `notification preferences PUT sends HH-mm and decodes server LocalTime`() = + runTest { + installExpectation( + method = "PUT", + path = "/api/v1/users/me/notification-preferences", + requestHeaders = mapOf("Authorization" to "Bearer contract-token"), + requestBody = + wireJson + .parseToJsonElement( + """{"enabled":true,"time":"18:00","weekdays":["MONDAY","FRIDAY"],"weeklyGoal":3}""", + ).jsonObject, + responseBody = + """ + {"status":200,"code":200,"message":"ok", + "data":{"enabled":true,"time":"18:00:00","weekdays":["MONDAY","FRIDAY"],"weeklyGoal":3}} + """.trimIndent(), + ) + + val result = + notificationService.updatePreferences( + NotificationPreferencesRequestDto( + enabled = true, + time = "18:00", + weekdays = listOf("MONDAY", "FRIDAY"), + weeklyGoal = 3, + ), + ) + + assertEquals("\"18:00:00\"", result.data?.time.toString()) + assertExactlyOneRecordedRequest("PUT", "/api/v1/users/me/notification-preferences") + } + + @Test + fun `notification entry POST decodes easy questions`() = + runTest { + installExpectation( + method = "POST", + path = "/api/v1/users/me/notification-preferences/entry", + requestHeaders = mapOf("Authorization" to "Bearer contract-token"), + responseBody = + """ + {"status":200,"code":200,"message":"ok", + "data":{"showEasyQuestions":true,"easyQuestions":["a","b","c"],"procedureCancelled":false}} + """.trimIndent(), + ) + + val result = notificationService.reportEntry() + + assertEquals(listOf("a", "b", "c"), result.data?.easyQuestions) + assertExactlyOneRecordedRequest("POST", "/api/v1/users/me/notification-preferences/entry") + } + + @Test + fun `notification read PATCH targets the notification id`() = + runTest { + installExpectation( + method = "PATCH", + path = "/api/v1/users/notifications/42/read", + requestHeaders = mapOf("Authorization" to "Bearer contract-token"), + responseBody = """{"status":200,"code":200,"message":"ok","data":null}""", + ) + + val result = notificationService.markRead(42L) + + assertEquals(200, result.status) + assertExactlyOneRecordedRequest("PATCH", "/api/v1/users/notifications/42/read") + } + @Test fun `delivery conditions GET preserves authenticated receiver path and response schema`() = runTest { diff --git a/core/ui/src/main/kotlin/com/afternote/core/ui/Route.kt b/core/ui/src/main/kotlin/com/afternote/core/ui/Route.kt index 7bb5e91371..fd08b17cb2 100644 --- a/core/ui/src/main/kotlin/com/afternote/core/ui/Route.kt +++ b/core/ui/src/main/kotlin/com/afternote/core/ui/Route.kt @@ -54,6 +54,10 @@ sealed interface Route : NavKey { @Serializable data object Receiver : Route + /** 홈 탑바에서 여는 서버 알림함 (#2321). 홈 스택 위에 쌓인다. */ + @Serializable + data object NotificationInbox : Route + /** 카카오 수신자 초대 랜딩의 앱 루트 host (#944). 내부 화면은 수신자 피처 로컬 스택이 소유한다. */ @Serializable data object ReceiverInvitation : Route @@ -62,11 +66,23 @@ sealed interface Route : NavKey { * 설정 로컬 스택의 host destination (#1695). * * 설정 안의 화면은 전부 이 한 칸 아래의 로컬 Nav3 스택에 있다. 홈의 «수신인 지정 미완료» 칩은 - * 설정 홈을 거치지 않고 등록 화면으로 곧장 들어오는데, 로컬 스택의 시작점은 host 가 정하므로 - * 그 진입을 [startWithRecipientRegistration] 인자로 나른다. + * 설정 홈을 거치지 않고 등록 화면으로 곧장 들어오고, 알림은 수신인·대리인 화면으로 곧장 들어온다 + * (#2321). 로컬 스택의 시작점은 host 가 정하므로 그 진입을 [start] 로 나른다. [receiverId] 는 + * [SettingStart.RECIPIENT_EDIT] 일 때만 쓴다. */ @Serializable data class Setting( - val startWithRecipientRegistration: Boolean = false, + val start: SettingStart = SettingStart.HOME, + val receiverId: Long? = null, ) : Route } + +/** [Route.Setting] 로컬 스택의 첫 화면. 시작 화면에서 back 하면 설정을 부른 곳으로 돌아간다. */ +@Serializable +enum class SettingStart { + HOME, + RECIPIENT_REGISTRATION, + RECIPIENT_LIST, + RECIPIENT_EDIT, + DELEGATE, +} diff --git a/core/ui/src/main/kotlin/com/afternote/core/ui/topbar/HomeTopBar.kt b/core/ui/src/main/kotlin/com/afternote/core/ui/topbar/HomeTopBar.kt index 7b903667ed..0ac4f27544 100644 --- a/core/ui/src/main/kotlin/com/afternote/core/ui/topbar/HomeTopBar.kt +++ b/core/ui/src/main/kotlin/com/afternote/core/ui/topbar/HomeTopBar.kt @@ -1,16 +1,20 @@ package com.afternote.core.ui.topbar import androidx.compose.foundation.Image +import androidx.compose.foundation.background import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.CircleShape import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.testTag @@ -19,6 +23,7 @@ import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.Role import androidx.compose.ui.unit.dp import com.afternote.core.ui.R +import com.afternote.core.ui.theme.AfternoteDesign /** 프로필 아이콘 앵커. 장식이라 semantics 이름이 없어 테스트가 이 태그로 존재 여부를 본다. */ const val PROFILE_ICON_TEST_TAG = "home_top_bar_profile" @@ -29,6 +34,9 @@ const val PROFILE_ICON_TEST_TAG = "home_top_bar_profile" * @param onSettingClick 설정 진입 콜백. `null` 이면 설정 아이콘을 그리지 않는다 — 회원이 아닌 * 흐름(수신자 열람)은 설정이 향할 곳이 없어서, no-op 을 넘겨 아이콘만 남기면 눌러도 아무 일이 * 일어나지 않는 가짜 액션이 된다 (#620). + * @param onNotificationClick 알림함 진입 콜백 (#2321). `null` 이면 알림 아이콘을 그리지 않는다 — 설정과 같은 + * 이유다. 수신자 홈에는 알림함이 없다. + * @param hasUnreadNotification 읽지 않은 알림이 있으면 아이콘 위에 점을 찍는다. */ @OptIn(ExperimentalMaterial3Api::class) @Composable @@ -36,6 +44,8 @@ fun HomeTopBar( modifier: Modifier = Modifier, showProfileIcon: Boolean = true, onSettingClick: (() -> Unit)? = {}, + onNotificationClick: (() -> Unit)? = null, + hasUnreadNotification: Boolean = false, ) { TopAppBar( navigationIcon = { @@ -71,6 +81,13 @@ fun HomeTopBar( } } + if (onNotificationClick != null) { + NotificationIcon(hasUnread = hasUnreadNotification, onClick = onNotificationClick) + if (onSettingClick != null) { + Spacer(modifier = Modifier.width(15.dp)) + } + } + if (onSettingClick != null) { Image( painter = painterResource(R.drawable.core_ui_settings), @@ -92,3 +109,34 @@ fun HomeTopBar( modifier = modifier, ) } + +@Composable +private fun NotificationIcon( + hasUnread: Boolean, + onClick: () -> Unit, +) { + Box( + modifier = + Modifier + .size(18.dp) + .clickable(role = Role.Button, onClick = onClick), + ) { + Image( + painter = painterResource(R.drawable.core_ui_bell), + contentDescription = + stringResource( + if (hasUnread) R.string.core_ui_home_top_bar_notification_unread else R.string.core_ui_home_top_bar_notification, + ), + modifier = Modifier.size(18.dp), + ) + if (hasUnread) { + Box( + modifier = + Modifier + .align(Alignment.TopEnd) + .size(6.dp) + .background(AfternoteDesign.colors.error, CircleShape), + ) + } + } +} diff --git a/core/ui/src/main/res/drawable/core_ui_bell.xml b/core/ui/src/main/res/drawable/core_ui_bell.xml new file mode 100644 index 0000000000..f42399699a --- /dev/null +++ b/core/ui/src/main/res/drawable/core_ui_bell.xml @@ -0,0 +1,24 @@ + + + + + + diff --git a/core/ui/src/main/res/values/strings.xml b/core/ui/src/main/res/values/strings.xml index 95c0a1e416..ddd10bb262 100644 --- a/core/ui/src/main/res/values/strings.xml +++ b/core/ui/src/main/res/values/strings.xml @@ -46,6 +46,8 @@ 다시 시도하기 설정 + 알림함 + 알림함, 읽지 않은 알림 있음 %1$d년 %2$d월 diff --git a/docs/qa/device-baseline.md b/docs/qa/device-baseline.md index f10155e572..ee42b31595 100644 --- a/docs/qa/device-baseline.md +++ b/docs/qa/device-baseline.md @@ -148,7 +148,7 @@ adb -s shell dumpsys package com.afternote.afternote_fe | grep lastUpda 반대로 OS 버전 매트릭스는 지금 단계에서 얻는 게 거의 없다. - `Build.VERSION.SDK_INT` 분기가 저장소 전체에 0건이다 -- 알림 권한은 `DailyNotificationWorker` 가 런타임에 확인한다 +- 알림 권한은 `AfternoteFirebaseMessagingService` 가 게시 직전에 런타임으로 확인한다 제조사 다양화도 마찬가지로 미룬다. 다만 아래 두 가지는 출시 전에 한 번은 해야 한다. diff --git a/feature/home/presentation/src/main/kotlin/com/afternote/feature/home/presentation/HomeTabScreen.kt b/feature/home/presentation/src/main/kotlin/com/afternote/feature/home/presentation/HomeTabScreen.kt index 25436ba8d4..82b27134ee 100644 --- a/feature/home/presentation/src/main/kotlin/com/afternote/feature/home/presentation/HomeTabScreen.kt +++ b/feature/home/presentation/src/main/kotlin/com/afternote/feature/home/presentation/HomeTabScreen.kt @@ -1,15 +1,18 @@ package com.afternote.feature.home.presentation +import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues 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.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Scaffold import androidx.compose.material3.Text @@ -130,74 +133,128 @@ fun HomeTabScreen( actions: HomeTabActions = HomeTabActionsNoop, // 프리뷰·스크린샷 테스트가 고정 날짜를 주입할 수 있도록 파라미터로 노출한다. todayDateText: String = LocalDate.now().format(homeTabDateFormatter), + // 서버 알림(#2321). 알림함 진입이 없으면 탑바에 아이콘을 그리지 않는다. + onNotificationClick: (() -> Unit)? = null, + hasUnreadNotification: Boolean = false, + // 기기 알림이 꺼져 있을 때만 non-null 이다. 누르면 시스템 알림 설정을 연다. + onTurnOnNotificationClick: (() -> Unit)? = null, ) { Scaffold( modifier = modifier, - topBar = { HomeTopBar(onSettingClick = actions::onSettingClick) }, + topBar = { + HomeTopBar( + onSettingClick = actions::onSettingClick, + onNotificationClick = onNotificationClick, + hasUnreadNotification = hasUnreadNotification, + ) + }, containerColor = Color.Transparent, ) { paddingValues -> - PullToRefreshBox( - isRefreshing = uiState.showsRefreshIndicator, - onRefresh = actions::onRetryLoad, - modifier = - Modifier - .fillMaxSize() - .padding(paddingValues), - ) { - when (uiState) { - is HomeTabUiState.Loading -> { - HomeTabScrollContent( - userName = uiState.cachedUserName ?: "\u2026", - // 조회 전이다 — 지정 여부를 결과로 확정하지 않는다 (#698). - recipientBadgeState = RecipientDesignationBadgeState.Unknown, - // 조회 전에는 아는 값이 없다 — 0 을 채워 넣지 않는다 (#700). - todayDateText = todayDateText, - todayQuestionContent = null, - isQuestionLoading = true, - // 조회 전이다 — 0 을 넣으면 «이번 주 기록 없음» 을 확정한다 (#562). - weeklyRecordCount = null, - actions = actions, - ) - } + Column(modifier = Modifier.fillMaxSize().padding(paddingValues)) { + if (onTurnOnNotificationClick != null) { + NotificationOffBanner(onClick = onTurnOnNotificationClick) + } + HomeTabBody(uiState = uiState, actions = actions, todayDateText = todayDateText) + } + } +} - is HomeTabUiState.Success -> { - HomeTabScrollContent( - userName = uiState.userName, - recipientBadgeState = - if (uiState.isRecipientDesignated) { - RecipientDesignationBadgeState.Completed - } else { - RecipientDesignationBadgeState.Incomplete(onClick = actions::onRecipientChipClick) - }, - todayDateText = todayDateText, - todayQuestionContent = uiState.todayQuestionContent, - isQuestionLoading = false, - weeklyRecordCount = uiState.weeklyRecordCount, - actions = actions, - ) - } +/** + * 기기 알림이 꺼진 사용자에게 켜는 길을 알린다 (#2321). 서버는 권한이 거부된 기기에 푸시를 보내지 않으므로 + * 기록 알림·전달 완료 소식이 이 기기에는 오지 않는다. + */ +@Composable +private fun NotificationOffBanner(onClick: () -> Unit) { + Row( + modifier = + Modifier + .fillMaxWidth() + .padding(horizontal = 20.dp, vertical = 8.dp) + .background(AfternoteDesign.colors.gray2, RoundedCornerShape(8.dp)) + .padding(horizontal = 16.dp, vertical = 12.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + text = stringResource(R.string.home_notification_off_banner), + style = AfternoteDesign.typography.captionLargeR, + color = AfternoteDesign.colors.gray7, + modifier = Modifier.weight(1f), + ) + TextButton(onClick = onClick) { + Text( + text = stringResource(R.string.home_notification_off_banner_action), + style = AfternoteDesign.typography.captionLargeB, + color = AfternoteDesign.colors.gray9, + ) + } + } +} - is HomeTabUiState.Error -> { - LazyColumn( - modifier = Modifier.fillMaxSize(), - verticalArrangement = Arrangement.Center, - horizontalAlignment = Alignment.CenterHorizontally, - ) { - item { - Column(horizontalAlignment = Alignment.CenterHorizontally) { +@OptIn(ExperimentalMaterial3Api::class) +@Composable +private fun HomeTabBody( + uiState: HomeTabUiState, + actions: HomeTabActions, + todayDateText: String, +) { + PullToRefreshBox( + isRefreshing = uiState.showsRefreshIndicator, + onRefresh = actions::onRetryLoad, + modifier = Modifier.fillMaxSize(), + ) { + when (uiState) { + is HomeTabUiState.Loading -> { + HomeTabScrollContent( + userName = uiState.cachedUserName ?: "\u2026", + // 조회 전이다 — 지정 여부를 결과로 확정하지 않는다 (#698). + recipientBadgeState = RecipientDesignationBadgeState.Unknown, + // 조회 전에는 아는 값이 없다 — 0 을 채워 넣지 않는다 (#700). + todayDateText = todayDateText, + todayQuestionContent = null, + isQuestionLoading = true, + // 조회 전이다 — 0 을 넣으면 «이번 주 기록 없음» 을 확정한다 (#562). + weeklyRecordCount = null, + actions = actions, + ) + } + + is HomeTabUiState.Success -> { + HomeTabScrollContent( + userName = uiState.userName, + recipientBadgeState = + if (uiState.isRecipientDesignated) { + RecipientDesignationBadgeState.Completed + } else { + RecipientDesignationBadgeState.Incomplete(onClick = actions::onRecipientChipClick) + }, + todayDateText = todayDateText, + todayQuestionContent = uiState.todayQuestionContent, + isQuestionLoading = false, + weeklyRecordCount = uiState.weeklyRecordCount, + actions = actions, + ) + } + + is HomeTabUiState.Error -> { + LazyColumn( + modifier = Modifier.fillMaxSize(), + verticalArrangement = Arrangement.Center, + horizontalAlignment = Alignment.CenterHorizontally, + ) { + item { + Column(horizontalAlignment = Alignment.CenterHorizontally) { + Text( + text = stringResource(R.string.home_tab_error_message), + style = AfternoteDesign.typography.bodySmallR, + color = AfternoteDesign.colors.gray7, + ) + Spacer(modifier = Modifier.height(16.dp)) + TextButton(onClick = actions::onRetryLoad) { Text( - text = stringResource(R.string.home_tab_error_message), - style = AfternoteDesign.typography.bodySmallR, - color = AfternoteDesign.colors.gray7, + text = stringResource(R.string.home_tab_retry), + style = AfternoteDesign.typography.captionLargeB, + color = AfternoteDesign.colors.gray9, ) - Spacer(modifier = Modifier.height(16.dp)) - TextButton(onClick = actions::onRetryLoad) { - Text( - text = stringResource(R.string.home_tab_retry), - style = AfternoteDesign.typography.captionLargeB, - color = AfternoteDesign.colors.gray9, - ) - } } } } diff --git a/feature/home/presentation/src/main/kotlin/com/afternote/feature/home/presentation/notification/NotificationBadgeViewModel.kt b/feature/home/presentation/src/main/kotlin/com/afternote/feature/home/presentation/notification/NotificationBadgeViewModel.kt new file mode 100644 index 0000000000..9e0c986fd6 --- /dev/null +++ b/feature/home/presentation/src/main/kotlin/com/afternote/feature/home/presentation/notification/NotificationBadgeViewModel.kt @@ -0,0 +1,42 @@ +package com.afternote.feature.home.presentation.notification + +import androidx.lifecycle.viewModelScope +import com.afternote.core.domain.repository.notification.NotificationRepository +import com.afternote.core.ui.mvi.MviViewModel +import dagger.hilt.android.lifecycle.HiltViewModel +import kotlinx.coroutines.Job +import kotlinx.coroutines.launch +import javax.inject.Inject + +/** 홈 탑바 알림 아이콘의 미읽음 점. 홈이 보일 때마다 다시 센다. */ +@HiltViewModel +internal class NotificationBadgeViewModel + @Inject + constructor( + private val repository: NotificationRepository, + ) : MviViewModel(NotificationBadgeUiState()) { + private var countJob: Job? = null + + override fun onIntent(intent: NotificationBadgeIntent) { + when (intent) { + NotificationBadgeIntent.Refresh -> count() + } + } + + override fun reduce( + state: NotificationBadgeUiState, + event: NotificationBadgeReducerEvent, + ): NotificationBadgeUiState = + when (event) { + is NotificationBadgeReducerEvent.Counted -> state.copy(hasUnread = event.unreadCount > 0) + } + + private fun count() { + if (countJob?.isActive == true) return + countJob = + viewModelScope.launch { + // 실패하면 직전 점을 그대로 둔다. 장식이라 실패를 알릴 자리가 없다. + repository.inbox().onSuccess { dispatch(NotificationBadgeReducerEvent.Counted(it.unreadCount)) } + } + } + } diff --git a/feature/home/presentation/src/main/kotlin/com/afternote/feature/home/presentation/notification/NotificationInboxContract.kt b/feature/home/presentation/src/main/kotlin/com/afternote/feature/home/presentation/notification/NotificationInboxContract.kt new file mode 100644 index 0000000000..f16bd9889d --- /dev/null +++ b/feature/home/presentation/src/main/kotlin/com/afternote/feature/home/presentation/notification/NotificationInboxContract.kt @@ -0,0 +1,51 @@ +package com.afternote.feature.home.presentation.notification + +import com.afternote.core.domain.repository.notification.NotificationInboxItem +import com.afternote.core.ui.mvi.MviIntent +import com.afternote.core.ui.mvi.ReducerEvent +import com.afternote.core.ui.mvi.UiState + +internal sealed interface NotificationInboxIntent : MviIntent { + /** 화면이 다시 보일 때. 첫 로드와 같은 길이지만 이미 그린 목록은 지우지 않는다. */ + data object Refresh : NotificationInboxIntent + + /** 항목을 눌렀다. 이동은 화면 콜백이 하고, 여기서는 읽음 표시만 미리 바꾼다. */ + data class Open( + val notificationId: Long, + ) : NotificationInboxIntent +} + +internal data class NotificationInboxUiState( + val isLoading: Boolean = true, + val loadFailed: Boolean = false, + val items: List = emptyList(), +) : UiState + +internal sealed interface NotificationInboxReducerEvent : ReducerEvent { + data object Loading : NotificationInboxReducerEvent + + data class Loaded( + val items: List, + ) : NotificationInboxReducerEvent + + data object LoadFailed : NotificationInboxReducerEvent + + data class Opened( + val notificationId: Long, + ) : NotificationInboxReducerEvent +} + +internal sealed interface NotificationBadgeIntent : MviIntent { + data object Refresh : NotificationBadgeIntent +} + +/** @property hasUnread 모르면(조회 전·실패) false — 점은 확인된 미읽음만 찍는다. */ +internal data class NotificationBadgeUiState( + val hasUnread: Boolean = false, +) : UiState + +internal sealed interface NotificationBadgeReducerEvent : ReducerEvent { + data class Counted( + val unreadCount: Long, + ) : NotificationBadgeReducerEvent +} diff --git a/feature/home/presentation/src/main/kotlin/com/afternote/feature/home/presentation/notification/NotificationInboxScreen.kt b/feature/home/presentation/src/main/kotlin/com/afternote/feature/home/presentation/notification/NotificationInboxScreen.kt new file mode 100644 index 0000000000..1ad6951590 --- /dev/null +++ b/feature/home/presentation/src/main/kotlin/com/afternote/feature/home/presentation/notification/NotificationInboxScreen.kt @@ -0,0 +1,184 @@ +package com.afternote.feature.home.presentation.notification + +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.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.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +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.graphics.Color +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.compose.LifecycleEventEffect +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import com.afternote.core.domain.repository.notification.NotificationInboxItem +import com.afternote.core.ui.modifierextention.bottomBorder +import com.afternote.core.ui.theme.AfternoteDesign +import com.afternote.core.ui.topbar.DetailTopBar +import com.afternote.feature.home.presentation.R + +/** + * 서버 알림함 화면 (#2321). + * + * 항목을 누르면 [onItemClick] 으로 알림 ID 와 목적지 data 를 넘긴다. 목적지 확인·읽음 처리·이동은 + * 푸시 알림을 누른 것과 같은 앱 셸 경로가 맡는다 — 같은 알림이 들어온 길에 따라 다른 화면으로 가지 않게. + */ +@Composable +fun NotificationInboxScreen( + onBack: () -> Unit, + onItemClick: (notificationId: Long, data: Map) -> Unit, +) { + val viewModel: NotificationInboxViewModel = hiltViewModel() + val uiState by viewModel.uiState.collectAsStateWithLifecycle() + var isFirstResume by rememberSaveable { mutableStateOf(true) } + LifecycleEventEffect(Lifecycle.Event.ON_RESUME) { + if (isFirstResume) isFirstResume = false else viewModel.onIntent(NotificationInboxIntent.Refresh) + } + NotificationInboxContent( + uiState = uiState, + onBack = onBack, + onRetry = { viewModel.onIntent(NotificationInboxIntent.Refresh) }, + onItemClick = { item -> + viewModel.onIntent(NotificationInboxIntent.Open(item.id)) + onItemClick(item.id, item.data) + }, + ) +} + +@Composable +internal fun NotificationInboxContent( + uiState: NotificationInboxUiState, + onBack: () -> Unit, + onRetry: () -> Unit, + onItemClick: (NotificationInboxItem) -> Unit, +) { + Scaffold( + topBar = { DetailTopBar(title = stringResource(R.string.home_notification_inbox_title), onBackClick = onBack) }, + containerColor = Color.Transparent, + ) { padding -> + Box(modifier = Modifier.fillMaxSize().padding(padding)) { + when { + uiState.isLoading -> { + CircularProgressIndicator( + color = AfternoteDesign.colors.gray9, + modifier = Modifier.align(Alignment.Center), + ) + } + + uiState.loadFailed -> { + Column( + modifier = Modifier.align(Alignment.Center), + horizontalAlignment = Alignment.CenterHorizontally, + ) { + Text( + text = stringResource(R.string.home_notification_inbox_load_failed), + style = AfternoteDesign.typography.bodySmallR, + color = AfternoteDesign.colors.gray7, + ) + Spacer(Modifier.height(16.dp)) + TextButton(onClick = onRetry) { + Text( + text = stringResource(R.string.home_tab_retry), + style = AfternoteDesign.typography.captionLargeB, + color = AfternoteDesign.colors.gray9, + ) + } + } + } + + uiState.items.isEmpty() -> { + Text( + text = stringResource(R.string.home_notification_inbox_empty), + style = AfternoteDesign.typography.bodyBase, + color = AfternoteDesign.colors.gray5, + modifier = Modifier.align(Alignment.Center), + ) + } + + else -> { + LazyColumn(modifier = Modifier.fillMaxSize()) { + items(uiState.items, key = NotificationInboxItem::id) { item -> + NotificationInboxRow(item = item, onClick = { onItemClick(item) }) + } + } + } + } + } + } +} + +@Composable +private fun NotificationInboxRow( + item: NotificationInboxItem, + onClick: () -> Unit, +) { + Row( + modifier = + Modifier + .fillMaxWidth() + .clickable(role = Role.Button, onClick = onClick) + .bottomBorder(color = AfternoteDesign.colors.gray3, width = 1.dp) + .padding(horizontal = 20.dp, vertical = 16.dp), + horizontalArrangement = Arrangement.spacedBy(10.dp), + ) { + // 읽지 않은 알림 표시. 읽은 줄도 자리를 비워 두어 글 줄이 흔들리지 않게 한다. + Box( + modifier = + Modifier + .padding(top = 7.dp) + .size(6.dp) + .background(if (item.isRead) Color.Transparent else AfternoteDesign.colors.error, CircleShape), + ) + Column(modifier = Modifier.weight(1f)) { + Text( + text = item.title, + style = if (item.isRead) AfternoteDesign.typography.bodyBase else AfternoteDesign.typography.bodyLargeB, + color = if (item.isRead) AfternoteDesign.colors.gray6 else AfternoteDesign.colors.gray9, + ) + Spacer(Modifier.height(4.dp)) + Text( + text = item.body, + style = AfternoteDesign.typography.captionLargeR, + color = AfternoteDesign.colors.gray6, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + ) + } + } +} + +/** + * 홈 탑바 알림 점. 화면이 보일 때마다(처음 포함) 다시 센다 — 알림함에서 읽고 돌아오거나 푸시를 받은 뒤 + * 홈으로 돌아오면 점이 맞춰진다. + */ +@Composable +fun rememberHasUnreadNotification(): Boolean { + val viewModel: NotificationBadgeViewModel = hiltViewModel() + val uiState by viewModel.uiState.collectAsStateWithLifecycle() + LifecycleEventEffect(Lifecycle.Event.ON_RESUME) { viewModel.onIntent(NotificationBadgeIntent.Refresh) } + return uiState.hasUnread +} diff --git a/feature/home/presentation/src/main/kotlin/com/afternote/feature/home/presentation/notification/NotificationInboxViewModel.kt b/feature/home/presentation/src/main/kotlin/com/afternote/feature/home/presentation/notification/NotificationInboxViewModel.kt new file mode 100644 index 0000000000..b77dec7f18 --- /dev/null +++ b/feature/home/presentation/src/main/kotlin/com/afternote/feature/home/presentation/notification/NotificationInboxViewModel.kt @@ -0,0 +1,70 @@ +package com.afternote.feature.home.presentation.notification + +import androidx.lifecycle.viewModelScope +import com.afternote.core.domain.repository.notification.NotificationRepository +import com.afternote.core.ui.mvi.MviViewModel +import dagger.hilt.android.lifecycle.HiltViewModel +import kotlinx.coroutines.Job +import kotlinx.coroutines.launch +import javax.inject.Inject + +/** + * 서버 알림함 (#2321). 푸시를 못 받은 기기·하루 상한으로 인앱에만 남은 알림도 여기서 본다. + * + * 첫 페이지(최근 50개)만 보여 준다. 읽음 처리는 항목을 눌러 목적지를 확인하는 앱 셸이 서버에 보낸다. + */ +@HiltViewModel +internal class NotificationInboxViewModel + @Inject + constructor( + private val repository: NotificationRepository, + ) : MviViewModel(NotificationInboxUiState()) { + private var loadJob: Job? = null + + init { + load() + } + + override fun onIntent(intent: NotificationInboxIntent) { + when (intent) { + NotificationInboxIntent.Refresh -> load() + is NotificationInboxIntent.Open -> dispatch(NotificationInboxReducerEvent.Opened(intent.notificationId)) + } + } + + override fun reduce( + state: NotificationInboxUiState, + event: NotificationInboxReducerEvent, + ): NotificationInboxUiState = + when (event) { + // 이미 그린 목록이 있으면 다시 불러오는 동안에도 그대로 둔다. + NotificationInboxReducerEvent.Loading -> { + state.copy(isLoading = state.items.isEmpty(), loadFailed = false) + } + + is NotificationInboxReducerEvent.Loaded -> { + state.copy(isLoading = false, items = event.items) + } + + // 보던 목록이 있으면 실패를 덮어쓰지 않는다 — 일시적 실패로 목록이 사라지면 인과가 안 보인다. + NotificationInboxReducerEvent.LoadFailed -> { + state.copy(isLoading = false, loadFailed = state.items.isEmpty()) + } + + is NotificationInboxReducerEvent.Opened -> { + state.copy(items = state.items.map { if (it.id == event.notificationId) it.copy(isRead = true) else it }) + } + } + + private fun load() { + if (loadJob?.isActive == true) return + dispatch(NotificationInboxReducerEvent.Loading) + loadJob = + viewModelScope.launch { + repository + .inbox() + .onSuccess { dispatch(NotificationInboxReducerEvent.Loaded(it.items)) } + .onFailure { dispatch(NotificationInboxReducerEvent.LoadFailed) } + } + } + } diff --git a/feature/home/presentation/src/main/res/values/strings.xml b/feature/home/presentation/src/main/res/values/strings.xml index 4f7498ea53..3d6c74a2bc 100644 --- a/feature/home/presentation/src/main/res/values/strings.xml +++ b/feature/home/presentation/src/main/res/values/strings.xml @@ -49,4 +49,10 @@ 라이프 이벤트 레터가 있습니다. %1$s개 의 애프터노트가 있습니다. + + 알림 + 아직 받은 알림이 없어요 + 알림을 불러오지 못했어요. + 알림이 꺼져 있어 기록 알림과 전달 소식을 받을 수 없어요 + 알림 켜기 diff --git a/feature/home/presentation/src/test/kotlin/com/afternote/feature/home/presentation/NotificationInboxViewModelTest.kt b/feature/home/presentation/src/test/kotlin/com/afternote/feature/home/presentation/NotificationInboxViewModelTest.kt new file mode 100644 index 0000000000..ca1dfd9b8b --- /dev/null +++ b/feature/home/presentation/src/test/kotlin/com/afternote/feature/home/presentation/NotificationInboxViewModelTest.kt @@ -0,0 +1,112 @@ +package com.afternote.feature.home.presentation + +import com.afternote.core.domain.repository.notification.NotificationEntry +import com.afternote.core.domain.repository.notification.NotificationInbox +import com.afternote.core.domain.repository.notification.NotificationInboxItem +import com.afternote.core.domain.repository.notification.NotificationRepository +import com.afternote.core.domain.repository.notification.NotificationTarget +import com.afternote.feature.home.presentation.notification.NotificationBadgeIntent +import com.afternote.feature.home.presentation.notification.NotificationBadgeViewModel +import com.afternote.feature.home.presentation.notification.NotificationInboxIntent +import com.afternote.feature.home.presentation.notification.NotificationInboxViewModel +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.advanceUntilIdle +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.test.setMain +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +/** 알림함과 홈 탑바 미읽음 점의 회귀 기준 (#2321). */ +@OptIn(ExperimentalCoroutinesApi::class) +class NotificationInboxViewModelTest { + private val dispatcher = StandardTestDispatcher() + + @Before + fun setUp() { + Dispatchers.setMain(dispatcher) + } + + @After + fun tearDown() { + Dispatchers.resetMain() + } + + @Test + fun `알림함을 불러오고 누른 항목을 읽음으로 바꾼다`() = + runTest(dispatcher) { + val viewModel = NotificationInboxViewModel(FakeInboxRepository(Result.success(inbox(unread = 1)))) + advanceUntilIdle() + + assertEquals( + listOf(1L, 2L), + viewModel.uiState.value.items + .map { it.id }, + ) + + viewModel.onIntent(NotificationInboxIntent.Open(1L)) + assertTrue( + viewModel.uiState.value.items + .all { it.isRead }, + ) + } + + @Test + fun `다시 불러오다 실패해도 보던 목록을 지우지 않는다`() = + runTest(dispatcher) { + val repository = FakeInboxRepository(Result.success(inbox(unread = 1))) + val viewModel = NotificationInboxViewModel(repository) + advanceUntilIdle() + + repository.result = Result.failure(IllegalStateException("offline")) + viewModel.onIntent(NotificationInboxIntent.Refresh) + advanceUntilIdle() + + assertEquals(2, viewModel.uiState.value.items.size) + assertFalse(viewModel.uiState.value.loadFailed) + } + + @Test + fun `미읽음이 있을 때만 점을 찍는다`() = + runTest(dispatcher) { + val repository = FakeInboxRepository(Result.success(inbox(unread = 3))) + val viewModel = NotificationBadgeViewModel(repository) + + viewModel.onIntent(NotificationBadgeIntent.Refresh) + advanceUntilIdle() + assertTrue(viewModel.uiState.value.hasUnread) + + repository.result = Result.success(inbox(unread = 0)) + viewModel.onIntent(NotificationBadgeIntent.Refresh) + advanceUntilIdle() + assertFalse(viewModel.uiState.value.hasUnread) + } + + private fun inbox(unread: Long) = + NotificationInbox( + unreadCount = unread, + items = + listOf( + NotificationInboxItem(1, "제목", "본문", mapOf("destination" to "HOME"), isRead = false), + NotificationInboxItem(2, "제목", "본문", mapOf("destination" to "HOME"), isRead = true), + ), + ) + + private class FakeInboxRepository( + var result: Result, + ) : NotificationRepository { + override suspend fun inbox(): Result = result + + override suspend fun target(notificationId: Long): Result = error("알림함은 목적지를 묻지 않는다") + + override suspend fun markRead(notificationId: Long): Result = error("알림함은 읽음을 보내지 않는다") + + override suspend fun reportEntry(): Result = error("알림함은 진입을 보고하지 않는다") + } +} diff --git a/feature/mindrecord/presentation/src/main/kotlin/com/afternote/feature/mindrecord/presentation/navigation/MindRecordRoute.kt b/feature/mindrecord/presentation/src/main/kotlin/com/afternote/feature/mindrecord/presentation/navigation/MindRecordRoute.kt index ed352bbc1e..af5fcdf806 100644 --- a/feature/mindrecord/presentation/src/main/kotlin/com/afternote/feature/mindrecord/presentation/navigation/MindRecordRoute.kt +++ b/feature/mindrecord/presentation/src/main/kotlin/com/afternote/feature/mindrecord/presentation/navigation/MindRecordRoute.kt @@ -25,12 +25,16 @@ sealed interface MindRecordRoute { * [recordId] 가 있으면 그 일기를 프리필하고 저장 시 PATCH 한다. [isDraft] 가 true 면 * 임시저장 이어쓰기(등록 시 `isDraft=false` 로 전환), false 면 **정식 기록 수정**이다. * [yearMonth](`yyyy-MM`) 는 해당 항목을 찾을 달이다. + * + * [prefillTitle] 은 새 일기의 제목을 미리 채운다. 오래 비웠다 돌아온 사용자가 고른 «쉬운 질문» 이 + * 여기로 온다 (#2321). 기존 기록을 여는 경로에서는 쓰지 않는다. */ @Serializable data class DiaryWriteRoute( val recordId: Long? = null, val yearMonth: String? = null, val isDraft: Boolean = true, + val prefillTitle: String? = null, ) : MindRecordRoute /** diff --git a/feature/mindrecord/presentation/src/main/kotlin/com/afternote/feature/mindrecord/presentation/viewmodel/DiaryWriteViewModel.kt b/feature/mindrecord/presentation/src/main/kotlin/com/afternote/feature/mindrecord/presentation/viewmodel/DiaryWriteViewModel.kt index 1a8d0167b2..313d8d0556 100644 --- a/feature/mindrecord/presentation/src/main/kotlin/com/afternote/feature/mindrecord/presentation/viewmodel/DiaryWriteViewModel.kt +++ b/feature/mindrecord/presentation/src/main/kotlin/com/afternote/feature/mindrecord/presentation/viewmodel/DiaryWriteViewModel.kt @@ -63,6 +63,8 @@ class DiaryWriteViewModel // 이어쓰기든 정식 기록 수정이든 덮어쓸 원본이 있다 — 프리필 가드는 둘을 함께 본다 (#2027). if (editingDiaryId != null) { _uiState.update { it.copy(isEditingExistingRecord = true) } + } else { + route.prefillTitle?.takeIf(String::isNotBlank)?.let { title -> _uiState.update { it.copy(title = title) } } } loadReceivers() loadDraftCount() diff --git a/feature/setting/data/src/main/kotlin/com/afternote/feature/setting/data/NotificationPreferenceRepositoryImpl.kt b/feature/setting/data/src/main/kotlin/com/afternote/feature/setting/data/NotificationPreferenceRepositoryImpl.kt new file mode 100644 index 0000000000..65d95b7dcc --- /dev/null +++ b/feature/setting/data/src/main/kotlin/com/afternote/feature/setting/data/NotificationPreferenceRepositoryImpl.kt @@ -0,0 +1,119 @@ +package com.afternote.feature.setting.data + +import com.afternote.core.domain.result.runCatchingCancellable +import com.afternote.core.network.dto.NotificationAnniversaryDto +import com.afternote.core.network.dto.NotificationAnniversaryRequestDto +import com.afternote.core.network.dto.NotificationDelegateRequestDto +import com.afternote.core.network.dto.NotificationPreferencesDto +import com.afternote.core.network.dto.NotificationPreferencesRequestDto +import com.afternote.core.network.model.requireData +import com.afternote.core.network.model.requireStatus +import com.afternote.core.network.service.NotificationApiService +import com.afternote.feature.setting.domain.NotificationAnniversary +import com.afternote.feature.setting.domain.NotificationDelegate +import com.afternote.feature.setting.domain.NotificationPreferenceRepository +import com.afternote.feature.setting.domain.NotificationPreferences +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.int +import kotlinx.serialization.json.jsonPrimitive +import java.time.DayOfWeek +import java.time.LocalTime +import java.time.format.DateTimeFormatter +import javax.inject.Inject + +internal class NotificationPreferenceRepositoryImpl + @Inject + constructor( + private val notificationApiService: NotificationApiService, + ) : NotificationPreferenceRepository { + override suspend fun getPreferences(): Result = + runCatchingCancellable { notificationApiService.getPreferences().requireData().toDomain() } + + override suspend fun updatePreferences(preferences: NotificationPreferences): Result = + runCatchingCancellable { + notificationApiService + .updatePreferences( + NotificationPreferencesRequestDto( + enabled = preferences.enabled, + time = preferences.time.format(WIRE_TIME), + weekdays = preferences.weekdays.sorted().map(DayOfWeek::name), + weeklyGoal = preferences.weeklyGoal, + ), + ).requireData() + .toDomain() + } + + override suspend fun getDelegate(): Result = + runCatchingCancellable { + val dto = notificationApiService.getDelegate().requireData() + val name = dto.name?.takeIf(String::isNotBlank) + val phone = dto.phone?.takeIf(String::isNotBlank) + if (name != null && phone != null) NotificationDelegate(name = name, phone = phone) else null + } + + override suspend fun updateDelegate(delegate: NotificationDelegate): Result = + runCatchingCancellable { + notificationApiService + .updateDelegate(NotificationDelegateRequestDto(name = delegate.name, phone = delegate.phone)) + .requireStatus() + } + + override suspend fun deleteDelegate(): Result = + runCatchingCancellable { notificationApiService.deleteDelegate().requireStatus() } + + override suspend fun getAnniversaries(): Result> = + runCatchingCancellable { notificationApiService.getAnniversaries().requireData().map { it.toDomain() } } + + override suspend fun addAnniversary( + receiverId: Long, + month: Int, + day: Int, + ): Result = + runCatchingCancellable { + notificationApiService + .createAnniversary(NotificationAnniversaryRequestDto(receiverId = receiverId, month = month, day = day)) + .requireData() + .toDomain() + } + + override suspend fun deleteAnniversary(anniversaryId: Long): Result = + runCatchingCancellable { notificationApiService.deleteAnniversary(anniversaryId).requireStatus() } + + private companion object { + val WIRE_TIME: DateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm") + } + } + +private fun NotificationPreferencesDto.toDomain(): NotificationPreferences = + NotificationPreferences( + enabled = enabled, + time = time.toLocalTime(), + // 모르는 요일 이름은 버린다 — 서버가 enum 을 늘려도 화면은 아는 요일만 그린다. + weekdays = weekdays.mapNotNull { name -> DayOfWeek.entries.firstOrNull { it.name == name } }.toSet(), + weeklyGoal = weeklyGoal, + ) + +private fun NotificationAnniversaryDto.toDomain(): NotificationAnniversary = + NotificationAnniversary(id = id, receiverId = receiverId, month = month, day = day) + +/** + * 서버 `LocalTime` 을 읽는다. Jackson 기본 설정이면 `"18:00:00"` 문자열이고, 타임스탬프 모드면 + * `[18,0]` 배열이다. 둘 다 아니면 계약 위반이라 던진다 — 기본값으로 메우면 사용자가 고른 시각이 + * 18:00 으로 보이는 거짓이 된다. + */ +private fun JsonElement.toLocalTime(): LocalTime = + when (this) { + is JsonPrimitive -> { + LocalTime.parse(content) + } + + is JsonArray -> { + LocalTime.of(this[0].jsonPrimitive.int, getOrNull(1)?.jsonPrimitive?.int ?: 0) + } + + else -> { + throw IllegalArgumentException("알림 시각 형식을 읽을 수 없다: $this") + } + } diff --git a/feature/setting/data/src/main/kotlin/com/afternote/feature/setting/data/di/SettingUserRepositoryModule.kt b/feature/setting/data/src/main/kotlin/com/afternote/feature/setting/data/di/SettingUserRepositoryModule.kt index e208e420f1..642bb12aeb 100644 --- a/feature/setting/data/src/main/kotlin/com/afternote/feature/setting/data/di/SettingUserRepositoryModule.kt +++ b/feature/setting/data/src/main/kotlin/com/afternote/feature/setting/data/di/SettingUserRepositoryModule.kt @@ -1,7 +1,9 @@ package com.afternote.feature.setting.data.di +import com.afternote.feature.setting.data.NotificationPreferenceRepositoryImpl import com.afternote.feature.setting.data.SettingAccountRepositoryImpl import com.afternote.feature.setting.data.SettingNotificationRepositoryImpl +import com.afternote.feature.setting.domain.NotificationPreferenceRepository import com.afternote.feature.setting.domain.SettingAccountRepository import com.afternote.feature.setting.domain.SettingNotificationRepository import dagger.Binds @@ -23,3 +25,18 @@ internal abstract class SettingUserRepositoryModule { @Binds internal abstract fun bindSettingNotificationRepository(impl: SettingNotificationRepositoryImpl): SettingNotificationRepository } + +/** + * 서버 알림 설정 저장소 바인딩 (#2321). + * + * [SettingUserRepositoryModule] 과 따로 둔다 — 앱 계측 테스트가 그 모듈을 대역으로 통째로 갈아 끼우므로, + * 거기 함께 두면 대역을 쓰는 테스트 그래프에서 이 바인딩까지 빠진다. + */ +@Module +@InstallIn(SingletonComponent::class) +internal abstract class NotificationPreferenceRepositoryModule { + @Binds + internal abstract fun bindNotificationPreferenceRepository( + impl: NotificationPreferenceRepositoryImpl, + ): NotificationPreferenceRepository +} diff --git a/feature/setting/data/src/test/kotlin/com/afternote/feature/setting/data/NotificationPreferenceTimeTest.kt b/feature/setting/data/src/test/kotlin/com/afternote/feature/setting/data/NotificationPreferenceTimeTest.kt new file mode 100644 index 0000000000..db4e01387d --- /dev/null +++ b/feature/setting/data/src/test/kotlin/com/afternote/feature/setting/data/NotificationPreferenceTimeTest.kt @@ -0,0 +1,103 @@ +package com.afternote.feature.setting.data + +import com.afternote.core.network.dto.NotificationAnniversaryDto +import com.afternote.core.network.dto.NotificationAnniversaryRequestDto +import com.afternote.core.network.dto.NotificationDelegateDto +import com.afternote.core.network.dto.NotificationDelegateRequestDto +import com.afternote.core.network.dto.NotificationEntryDto +import com.afternote.core.network.dto.NotificationInboxDto +import com.afternote.core.network.dto.NotificationPreferencesDto +import com.afternote.core.network.dto.NotificationPreferencesRequestDto +import com.afternote.core.network.dto.NotificationTargetDto +import com.afternote.core.network.model.BaseResponse +import com.afternote.core.network.service.NotificationApiService +import com.afternote.feature.setting.domain.NotificationPreferences +import kotlinx.coroutines.test.runTest +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test +import java.time.DayOfWeek +import java.time.LocalTime + +/** + * 서버 알림 설정의 와이어 변환 (#2321). + * + * 서버 `LocalTime` 은 Jackson 설정에 따라 문자열이나 배열로 온다 — 어느 쪽이든 같은 시각이어야 하고, + * 둘 다 아니면 기본값으로 메우지 않고 실패해야 한다. 보낼 때는 `HH:mm` 과 요일 이름이다. + */ +class NotificationPreferenceTimeTest { + @Test + fun `문자열과 배열 시각을 같은 값으로 읽는다`() = + runTest { + listOf("\"18:00:00\"", "\"18:00\"", "[18,0]", "[18,0,0]").forEach { wire -> + val repository = NotificationPreferenceRepositoryImpl(FakeService(time = Json.parseToJsonElement(wire))) + + assertEquals(wire, LocalTime.of(18, 0), repository.getPreferences().getOrThrow().time) + } + } + + @Test + fun `알 수 없는 시각 형식은 기본값으로 메우지 않고 실패한다`() = + runTest { + val repository = NotificationPreferenceRepositoryImpl(FakeService(time = JsonObject(emptyMap()))) + + assertTrue(repository.getPreferences().isFailure) + } + + @Test + fun `저장은 HH-mm 과 요일 이름으로 보낸다`() = + runTest { + val service = FakeService(time = Json.parseToJsonElement("\"07:05:00\"")) + val repository = NotificationPreferenceRepositoryImpl(service) + + repository.updatePreferences( + NotificationPreferences( + enabled = true, + time = LocalTime.of(7, 5), + weekdays = setOf(DayOfWeek.FRIDAY, DayOfWeek.MONDAY), + weeklyGoal = 3, + ), + ) + + assertEquals(NotificationPreferencesRequestDto(true, "07:05", listOf("MONDAY", "FRIDAY"), 3), service.lastUpdate) + } + + private class FakeService( + private val time: JsonElement, + ) : NotificationApiService { + var lastUpdate: NotificationPreferencesRequestDto? = null + + private fun preferences() = BaseResponse(200, 200, "ok", NotificationPreferencesDto(true, time, listOf("FRIDAY"), 3)) + + override suspend fun getPreferences(): BaseResponse = preferences() + + override suspend fun updatePreferences(request: NotificationPreferencesRequestDto): BaseResponse { + lastUpdate = request + return preferences() + } + + override suspend fun getInbox(page: Int): BaseResponse = TODO("이 테스트 미사용") + + override suspend fun getTarget(notificationId: Long): BaseResponse = TODO("이 테스트 미사용") + + override suspend fun markRead(notificationId: Long): BaseResponse = TODO("이 테스트 미사용") + + override suspend fun reportEntry(): BaseResponse = TODO("이 테스트 미사용") + + override suspend fun getDelegate(): BaseResponse = TODO("이 테스트 미사용") + + override suspend fun updateDelegate(request: NotificationDelegateRequestDto): BaseResponse = TODO("이 테스트 미사용") + + override suspend fun deleteDelegate(): BaseResponse = TODO("이 테스트 미사용") + + override suspend fun getAnniversaries(): BaseResponse> = TODO("이 테스트 미사용") + + override suspend fun createAnniversary(request: NotificationAnniversaryRequestDto): BaseResponse = + TODO("이 테스트 미사용") + + override suspend fun deleteAnniversary(anniversaryId: Long): BaseResponse = TODO("이 테스트 미사용") + } +} diff --git a/feature/setting/data/src/test/kotlin/com/afternote/feature/setting/data/SettingUserApiServiceFake.kt b/feature/setting/data/src/test/kotlin/com/afternote/feature/setting/data/SettingUserApiServiceFake.kt index d0508e9fc5..66f2422d7f 100644 --- a/feature/setting/data/src/test/kotlin/com/afternote/feature/setting/data/SettingUserApiServiceFake.kt +++ b/feature/setting/data/src/test/kotlin/com/afternote/feature/setting/data/SettingUserApiServiceFake.kt @@ -2,6 +2,8 @@ package com.afternote.feature.setting.data import com.afternote.core.common.reporting.ErrorReporter import com.afternote.core.network.dto.DeletePushTokenRequestDto +import com.afternote.core.network.dto.PushInstallationDto +import com.afternote.core.network.dto.PushInstallationRequestDto import com.afternote.core.network.dto.PushTokenDto import com.afternote.core.network.dto.ReceiverDetailDto import com.afternote.core.network.dto.ReceiverListDto @@ -93,6 +95,8 @@ internal class SettingUserApiServiceFake( override suspend fun deletePushToken(request: DeletePushTokenRequestDto): BaseResponse = TODO("이 테스트 미사용") + override suspend fun reportPushInstallation(request: PushInstallationRequestDto): BaseResponse = TODO("이 테스트 미사용") + override suspend fun getReceiverDeliveryConditions(receiverId: Long): BaseResponse = TODO("이 테스트 미사용") override suspend fun updateReceiverDeliveryConditions( diff --git a/feature/setting/domain/src/main/java/com/afternote/feature/setting/domain/NotificationPreferenceRepository.kt b/feature/setting/domain/src/main/java/com/afternote/feature/setting/domain/NotificationPreferenceRepository.kt new file mode 100644 index 0000000000..33d37811ff --- /dev/null +++ b/feature/setting/domain/src/main/java/com/afternote/feature/setting/domain/NotificationPreferenceRepository.kt @@ -0,0 +1,63 @@ +package com.afternote.feature.setting.domain + +import java.time.DayOfWeek +import java.time.LocalTime + +/** + * 서버 알림(BE#317)의 사용자 설정 계약 (#2321) — 기록 알림 시각·요일·주간 목표, 대리인, 수신인 기념일. + * + * 기존 [SettingNotificationRepository] 의 카테고리 토글(타임레터·마음의 기록·애프터노트)과는 서버에서 + * 따로 적용된다. 마음의 기록 토글이 꺼져 있으면 여기 설정과 무관하게 기록 알림이 오지 않는다. + */ +public interface NotificationPreferenceRepository { + public suspend fun getPreferences(): Result + + /** 바꾸면 서버가 대기 중이던 이전 기록 알림을 취소한다. */ + public suspend fun updatePreferences(preferences: NotificationPreferences): Result + + /** 지정한 대리인. 아직 없으면 null. */ + public suspend fun getDelegate(): Result + + /** 바꾸면 이전 대리인에게 간 확인 링크가 무효가 된다. */ + public suspend fun updateDelegate(delegate: NotificationDelegate): Result + + public suspend fun deleteDelegate(): Result + + public suspend fun getAnniversaries(): Result> + + public suspend fun addAnniversary( + receiverId: Long, + month: Int, + day: Int, + ): Result + + public suspend fun deleteAnniversary(anniversaryId: Long): Result +} + +/** + * 기록 알림(B) 설정. + * + * @property time 한국 시간. 서버는 분 단위까지만 받는다. + * @property weekdays 알림을 받을 요일. 비어 있으면 서버가 거부한다. + * @property weeklyGoal 주간 목표 기록 수(1~7). 알림 요일과는 별개다. + */ +public data class NotificationPreferences( + val enabled: Boolean, + val time: LocalTime, + val weekdays: Set, + val weeklyGoal: Int, +) + +/** 오래 접속하지 않을 때 연락받을 사람. 수신인과 별개다. */ +public data class NotificationDelegate( + val name: String, + val phone: String, +) + +/** 수신인 생일. 2월 29일은 평년에 2월 28일로 안내된다. */ +public data class NotificationAnniversary( + val id: Long, + val receiverId: Long, + val month: Int, + val day: Int, +) diff --git a/feature/setting/domain/src/testFixtures/kotlin/com/afternote/feature/setting/domain/testing/StrictNotificationPreferenceRepository.kt b/feature/setting/domain/src/testFixtures/kotlin/com/afternote/feature/setting/domain/testing/StrictNotificationPreferenceRepository.kt new file mode 100644 index 0000000000..c378ce2a85 --- /dev/null +++ b/feature/setting/domain/src/testFixtures/kotlin/com/afternote/feature/setting/domain/testing/StrictNotificationPreferenceRepository.kt @@ -0,0 +1,33 @@ +package com.afternote.feature.setting.domain.testing + +import com.afternote.feature.setting.domain.NotificationAnniversary +import com.afternote.feature.setting.domain.NotificationDelegate +import com.afternote.feature.setting.domain.NotificationPreferenceRepository +import com.afternote.feature.setting.domain.NotificationPreferences + +/** + * 서버 알림 설정을 쓰지 않는 테스트의 Hilt 그래프를 채우는 대역 (#2321). 불리면 그 자체가 회귀라 던진다. + */ +public object StrictNotificationPreferenceRepository : NotificationPreferenceRepository { + override suspend fun getPreferences(): Result = unexpected() + + override suspend fun updatePreferences(preferences: NotificationPreferences): Result = unexpected() + + override suspend fun getDelegate(): Result = unexpected() + + override suspend fun updateDelegate(delegate: NotificationDelegate): Result = unexpected() + + override suspend fun deleteDelegate(): Result = unexpected() + + override suspend fun getAnniversaries(): Result> = unexpected() + + override suspend fun addAnniversary( + receiverId: Long, + month: Int, + day: Int, + ): Result = unexpected() + + override suspend fun deleteAnniversary(anniversaryId: Long): Result = unexpected() + + private fun unexpected(): Nothing = error("이 테스트는 서버 알림 설정을 부르지 않는다") +} diff --git a/feature/setting/presentation/src/main/kotlin/com/afternote/feature/setting/presentation/navigation/SettingLocalNavActions.kt b/feature/setting/presentation/src/main/kotlin/com/afternote/feature/setting/presentation/navigation/SettingLocalNavActions.kt index c06870a8d7..3d6f168b6b 100644 --- a/feature/setting/presentation/src/main/kotlin/com/afternote/feature/setting/presentation/navigation/SettingLocalNavActions.kt +++ b/feature/setting/presentation/src/main/kotlin/com/afternote/feature/setting/presentation/navigation/SettingLocalNavActions.kt @@ -49,6 +49,18 @@ internal class SettingLocalNavActions( backStack.add(SettingRoute.PushNotificationRoute) } + override fun onNotificationPreferenceClick() { + backStack.add(SettingRoute.NotificationPreferenceRoute) + } + + override fun onDelegateClick() { + backStack.add(SettingRoute.DelegateRoute) + } + + override fun onAnniversaryClick() { + backStack.add(SettingRoute.AnniversaryRoute) + } + override fun onRecipientListClick() { backStack.add(SettingRoute.RecipientListRoute()) } diff --git a/feature/setting/presentation/src/main/kotlin/com/afternote/feature/setting/presentation/navigation/SettingNavActions.kt b/feature/setting/presentation/src/main/kotlin/com/afternote/feature/setting/presentation/navigation/SettingNavActions.kt index c36d150267..c82dd779a1 100644 --- a/feature/setting/presentation/src/main/kotlin/com/afternote/feature/setting/presentation/navigation/SettingNavActions.kt +++ b/feature/setting/presentation/src/main/kotlin/com/afternote/feature/setting/presentation/navigation/SettingNavActions.kt @@ -28,6 +28,12 @@ internal interface SettingNavActions { fun onPushNotificationClick() + fun onNotificationPreferenceClick() + + fun onDelegateClick() + + fun onAnniversaryClick() + fun onRecipientListClick() fun onDeliveryConditionsClick() diff --git a/feature/setting/presentation/src/main/kotlin/com/afternote/feature/setting/presentation/navigation/SettingNavHost.kt b/feature/setting/presentation/src/main/kotlin/com/afternote/feature/setting/presentation/navigation/SettingNavHost.kt index 63f3717edb..e498866f0d 100644 --- a/feature/setting/presentation/src/main/kotlin/com/afternote/feature/setting/presentation/navigation/SettingNavHost.kt +++ b/feature/setting/presentation/src/main/kotlin/com/afternote/feature/setting/presentation/navigation/SettingNavHost.kt @@ -12,6 +12,7 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.viewmodel.compose.LocalViewModelStoreOwner import androidx.navigation3.runtime.entryProvider import androidx.navigation3.runtime.rememberNavBackStack +import com.afternote.core.ui.SettingStart import com.afternote.core.ui.asString import com.afternote.core.ui.navigation.FeatureNavDisplay import com.afternote.core.ui.navigation.FeatureNavigationCallbacks @@ -27,6 +28,9 @@ import com.afternote.feature.setting.presentation.home.WithdrawGuideScreen import com.afternote.feature.setting.presentation.notice.NoticeListScreen import com.afternote.feature.setting.presentation.notification.NotificationSettingScreen import com.afternote.feature.setting.presentation.notification.PushNotificationScreen +import com.afternote.feature.setting.presentation.notification.anniversary.AnniversaryScreen +import com.afternote.feature.setting.presentation.notification.delegate.DelegateScreen +import com.afternote.feature.setting.presentation.notification.preference.NotificationPreferenceScreen import com.afternote.feature.setting.presentation.passkey.PassKeyListIntent import com.afternote.feature.setting.presentation.passkey.PassKeyListScreen import com.afternote.feature.setting.presentation.passkey.PassKeyListViewModel @@ -55,9 +59,10 @@ import com.afternote.feature.setting.presentation.receiver.ReceiverRegisterScree * * ## 시작점 * - * 홈의 «수신인 지정 미완료» 칩은 설정 홈을 거치지 않고 등록 화면으로 곧장 들어온다 - * ([startWithRecipientRegistration]). 등록 화면을 스택 바닥에 두면 등록 성공의 pop 이 곧 host 이탈이라, - * 이관 전처럼 부른 곳(홈)으로 돌아간다. 설정 홈·목록에서 들어온 등록은 그 위에 쌓이므로 거기로 돌아간다. + * 홈의 «수신인 지정 미완료» 칩은 설정 홈을 거치지 않고 등록 화면으로 곧장 들어오고, 알림은 수신인 목록· + * 수신인·대리인 화면으로 곧장 들어온다 (#2321). 그 시작점이 [start] 다. 시작 화면을 스택 바닥에 두면 + * 그 화면의 pop 이 곧 host 이탈이라, 이관 전처럼 부른 곳으로 돌아간다. 설정 홈·목록에서 들어온 화면은 + * 그 위에 쌓이므로 거기로 돌아간다. * * ## 탈퇴 안내·확인이 공유하는 ViewModel * @@ -77,12 +82,10 @@ public fun SettingNavHost( navigationCallbacks: FeatureNavigationCallbacks, externalActions: SettingExternalActions, modifier: Modifier = Modifier, - startWithRecipientRegistration: Boolean = false, + start: SettingStart = SettingStart.HOME, + receiverId: Long? = null, ) { - val backStack = - rememberNavBackStack( - if (startWithRecipientRegistration) SettingRoute.RecipientRegisterRoute else SettingRoute.SettingHomeRoute, - ) + val backStack = rememberNavBackStack(startRoute(start, receiverId)) val actions = remember(backStack, navigationCallbacks, externalActions) { SettingLocalNavActions(backStack, navigationCallbacks, externalActions) @@ -159,9 +162,24 @@ public fun SettingNavHost( NotificationSettingScreen( onBack = actions::popBack, onPushNotificationClick = actions::onPushNotificationClick, + onNotificationPreferenceClick = actions::onNotificationPreferenceClick, + onDelegateClick = actions::onDelegateClick, + onAnniversaryClick = actions::onAnniversaryClick, ) } + entry { + NotificationPreferenceScreen(onBack = actions::popBack) + } + + entry { + DelegateScreen(onBack = actions::popBack) + } + + entry { + AnniversaryScreen(onBack = actions::popBack) + } + entry { PushNotificationScreen( onBack = actions::popBack, @@ -261,3 +279,20 @@ public fun SettingNavHost( }, ) } + +private fun startRoute( + start: SettingStart, + receiverId: Long?, +): SettingRoute = + when (start) { + SettingStart.HOME -> SettingRoute.SettingHomeRoute + + SettingStart.RECIPIENT_REGISTRATION -> SettingRoute.RecipientRegisterRoute + + SettingStart.RECIPIENT_LIST -> SettingRoute.RecipientListRoute() + + // 수신인을 모르면 고를 수 있는 목록으로 연다. + SettingStart.RECIPIENT_EDIT -> receiverId?.let(SettingRoute::RecipientEditRoute) ?: SettingRoute.RecipientListRoute() + + SettingStart.DELEGATE -> SettingRoute.DelegateRoute + } diff --git a/feature/setting/presentation/src/main/kotlin/com/afternote/feature/setting/presentation/navigation/SettingRoute.kt b/feature/setting/presentation/src/main/kotlin/com/afternote/feature/setting/presentation/navigation/SettingRoute.kt index 0715412fee..06accc10d0 100644 --- a/feature/setting/presentation/src/main/kotlin/com/afternote/feature/setting/presentation/navigation/SettingRoute.kt +++ b/feature/setting/presentation/src/main/kotlin/com/afternote/feature/setting/presentation/navigation/SettingRoute.kt @@ -43,6 +43,18 @@ internal sealed interface SettingRoute : NavKey { @Serializable data object PushNotificationRoute : SettingRoute + /** 기록 알림 시각·요일·주간 목표 (#2321). */ + @Serializable + data object NotificationPreferenceRoute : SettingRoute + + /** 오래 접속하지 않을 때 연락받을 대리인 (#2321). */ + @Serializable + data object DelegateRoute : SettingRoute + + /** 수신인 생일 — 그날 편지를 권하는 알림의 기준 (#2321). */ + @Serializable + data object AnniversaryRoute : SettingRoute + @Serializable data object RecipientRegisterRoute : SettingRoute diff --git a/feature/setting/presentation/src/main/kotlin/com/afternote/feature/setting/presentation/notification/NotificationSettingScreen.kt b/feature/setting/presentation/src/main/kotlin/com/afternote/feature/setting/presentation/notification/NotificationSettingScreen.kt index 9487ad1c42..8c049d5ae5 100644 --- a/feature/setting/presentation/src/main/kotlin/com/afternote/feature/setting/presentation/notification/NotificationSettingScreen.kt +++ b/feature/setting/presentation/src/main/kotlin/com/afternote/feature/setting/presentation/notification/NotificationSettingScreen.kt @@ -52,6 +52,9 @@ import kotlinx.coroutines.launch internal fun NotificationSettingScreen( onBack: () -> Unit, onPushNotificationClick: () -> Unit, + onNotificationPreferenceClick: () -> Unit, + onDelegateClick: () -> Unit, + onAnniversaryClick: () -> Unit, viewModel: PushNotificationViewModel = hiltViewModel(), ) { val uiState by viewModel.uiState.collectAsStateWithLifecycle() @@ -111,6 +114,9 @@ internal fun NotificationSettingScreen( snackbarHostState = snackbarHostState, onBack = onBack, onPushNotificationClick = onPushNotificationClick, + onNotificationPreferenceClick = onNotificationPreferenceClick, + onDelegateClick = onDelegateClick, + onAnniversaryClick = onAnniversaryClick, onDeviceAlarmClick = { val permissionGranted = ContextCompat.checkSelfPermission( @@ -139,6 +145,9 @@ private fun NotificationSettingContent( snackbarHostState: SnackbarHostState, onBack: () -> Unit, onPushNotificationClick: () -> Unit, + onNotificationPreferenceClick: () -> Unit, + onDelegateClick: () -> Unit, + onAnniversaryClick: () -> Unit, onDeviceAlarmClick: () -> Unit, onMarketingConsentChange: (MarketingConsent, Boolean) -> Unit, ) { @@ -197,6 +206,20 @@ private fun NotificationSettingContent( onPushCheck = { onMarketingConsentChange(MarketingConsent.PUSH, it) }, ) } + // 서버 알림 설정(#2321)은 기기 알림이 꺼져 있어도 고칠 수 있다 — 대리인·기념일은 푸시가 아니어도 + // 알림함과 알림톡으로 쓰인다. + SettingMenuItem( + label = stringResource(R.string.setting_notification_preference_menu), + onClick = onNotificationPreferenceClick, + ) + SettingMenuItem( + label = stringResource(R.string.setting_delegate_menu), + onClick = onDelegateClick, + ) + SettingMenuItem( + label = stringResource(R.string.setting_anniversary_menu), + onClick = onAnniversaryClick, + ) } } } diff --git a/feature/setting/presentation/src/main/kotlin/com/afternote/feature/setting/presentation/notification/anniversary/AnniversaryContract.kt b/feature/setting/presentation/src/main/kotlin/com/afternote/feature/setting/presentation/notification/anniversary/AnniversaryContract.kt new file mode 100644 index 0000000000..8e10f0c18f --- /dev/null +++ b/feature/setting/presentation/src/main/kotlin/com/afternote/feature/setting/presentation/notification/anniversary/AnniversaryContract.kt @@ -0,0 +1,71 @@ +package com.afternote.feature.setting.presentation.notification.anniversary + +import com.afternote.core.ui.UiText +import com.afternote.core.ui.mvi.MviIntent +import com.afternote.core.ui.mvi.ReducerEvent +import com.afternote.core.ui.mvi.UiState + +internal sealed interface AnniversaryIntent : MviIntent { + data object Retry : AnniversaryIntent + + data class Add( + val receiverId: Long, + val month: Int, + val day: Int, + ) : AnniversaryIntent + + data class Delete( + val anniversaryId: Long, + ) : AnniversaryIntent + + data object ConsumeError : AnniversaryIntent +} + +/** 화면에 그릴 기념일 한 줄. 수신인 이름은 수신인 목록에서 찾아 붙인다 — 서버 응답에는 ID 만 있다. */ +internal data class AnniversaryItem( + val id: Long, + val receiverName: String?, + val month: Int, + val day: Int, +) + +internal data class AnniversaryReceiver( + val id: Long, + val name: String, +) + +internal data class AnniversaryUiState( + val isLoading: Boolean = true, + val loadFailed: Boolean = false, + val items: List = emptyList(), + val receivers: List = emptyList(), + val isSubmitting: Boolean = false, + val errorMessage: UiText? = null, +) : UiState + +internal sealed interface AnniversaryReducerEvent : ReducerEvent { + data object Loading : AnniversaryReducerEvent + + data class Loaded( + val items: List, + val receivers: List, + ) : AnniversaryReducerEvent + + data object LoadFailed : AnniversaryReducerEvent + + data object Submitting : AnniversaryReducerEvent + + data class Added( + val item: AnniversaryItem, + ) : AnniversaryReducerEvent + + data class Deleted( + val anniversaryId: Long, + ) : AnniversaryReducerEvent + + data class Failed( + val message: UiText, + ) : AnniversaryReducerEvent + + data object ErrorConsumed : AnniversaryReducerEvent +} diff --git a/feature/setting/presentation/src/main/kotlin/com/afternote/feature/setting/presentation/notification/anniversary/AnniversaryScreen.kt b/feature/setting/presentation/src/main/kotlin/com/afternote/feature/setting/presentation/notification/anniversary/AnniversaryScreen.kt new file mode 100644 index 0000000000..9aa297e2e4 --- /dev/null +++ b/feature/setting/presentation/src/main/kotlin/com/afternote/feature/setting/presentation/notification/anniversary/AnniversaryScreen.kt @@ -0,0 +1,293 @@ +package com.afternote.feature.setting.presentation.notification.anniversary + +import androidx.compose.foundation.clickable +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.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.SnackbarHostState +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +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.graphics.Color +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.unit.dp +import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import com.afternote.core.ui.asString +import com.afternote.core.ui.button.AfternoteButton +import com.afternote.core.ui.modifierextention.bottomBorder +import com.afternote.core.ui.mvi.ObserveSignal +import com.afternote.core.ui.theme.AfternoteDesign +import com.afternote.core.ui.topbar.DetailTopBar +import com.afternote.feature.setting.presentation.R +import com.afternote.feature.setting.presentation.shared.component.SettingLoadErrorContent +import kotlinx.coroutines.launch +import java.time.Month + +@Composable +internal fun AnniversaryScreen( + onBack: () -> Unit, + viewModel: AnniversaryViewModel = hiltViewModel(), +) { + val uiState by viewModel.uiState.collectAsStateWithLifecycle() + val snackbarHostState = remember { SnackbarHostState() } + val snackbarScope = rememberCoroutineScope() + val errorMessage = uiState.errorMessage?.asString() + ObserveSignal(signal = errorMessage, consumed = AnniversaryIntent.ConsumeError, onIntent = viewModel::onIntent) { message -> + snackbarScope.launch { snackbarHostState.showSnackbar(message) } + } + AnniversaryContent( + uiState = uiState, + snackbarHostState = snackbarHostState, + onBack = onBack, + onIntent = viewModel::onIntent, + ) +} + +@Composable +internal fun AnniversaryContent( + uiState: AnniversaryUiState, + snackbarHostState: SnackbarHostState, + onBack: () -> Unit, + onIntent: (AnniversaryIntent) -> Unit, +) { + var isAdding by rememberSaveable { mutableStateOf(false) } + Scaffold( + topBar = { + DetailTopBar(title = stringResource(R.string.setting_anniversary_title), onBackClick = onBack) + }, + snackbarHost = { SnackbarHost(snackbarHostState) }, + containerColor = Color.Transparent, + ) { padding -> + when { + uiState.isLoading -> { + Box(Modifier.fillMaxSize().padding(padding), contentAlignment = Alignment.Center) { + CircularProgressIndicator(color = AfternoteDesign.colors.gray9) + } + } + + uiState.loadFailed -> { + SettingLoadErrorContent( + message = stringResource(R.string.setting_anniversary_load_failed), + onRetry = { onIntent(AnniversaryIntent.Retry) }, + modifier = Modifier.padding(padding), + ) + } + + else -> { + Column( + modifier = + Modifier + .fillMaxSize() + .padding(padding) + .padding(horizontal = 20.dp, vertical = 16.dp), + ) { + Text( + text = stringResource(R.string.setting_anniversary_description), + style = AfternoteDesign.typography.captionLargeR, + color = AfternoteDesign.colors.gray6, + ) + Spacer(Modifier.height(16.dp)) + if (uiState.items.isEmpty()) { + Text( + text = stringResource(R.string.setting_anniversary_empty), + style = AfternoteDesign.typography.bodyBase, + color = AfternoteDesign.colors.gray5, + modifier = Modifier.padding(vertical = 24.dp).align(Alignment.CenterHorizontally), + ) + } + LazyColumn(modifier = Modifier.weight(1f, fill = false)) { + items(uiState.items, key = AnniversaryItem::id) { item -> + AnniversaryRow( + item = item, + enabled = !uiState.isSubmitting, + onDelete = { onIntent(AnniversaryIntent.Delete(item.id)) }, + ) + } + } + Spacer(Modifier.height(24.dp)) + if (uiState.receivers.isEmpty()) { + Text( + text = stringResource(R.string.setting_anniversary_no_receiver), + style = AfternoteDesign.typography.captionLargeR, + color = AfternoteDesign.colors.gray6, + ) + } else { + AfternoteButton( + text = stringResource(R.string.setting_anniversary_add), + onClick = { isAdding = true }, + isLoading = uiState.isSubmitting, + modifier = Modifier.fillMaxWidth(), + ) + } + } + } + } + } + if (isAdding) { + AddAnniversaryDialog( + receivers = uiState.receivers, + onConfirm = { receiverId, month, day -> + isAdding = false + onIntent(AnniversaryIntent.Add(receiverId, month, day)) + }, + onDismiss = { isAdding = false }, + ) + } +} + +@Composable +private fun AnniversaryRow( + item: AnniversaryItem, + enabled: Boolean, + onDelete: () -> Unit, +) { + Row( + modifier = + Modifier + .fillMaxWidth() + .bottomBorder(color = AfternoteDesign.colors.gray3, width = 1.dp) + .padding(vertical = 14.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + text = item.receiverName ?: stringResource(R.string.setting_anniversary_unknown_receiver), + style = AfternoteDesign.typography.bodyBase, + color = AfternoteDesign.colors.gray9, + modifier = Modifier.weight(1f), + ) + Text( + text = stringResource(R.string.setting_anniversary_date, item.month, item.day), + style = AfternoteDesign.typography.bodyBase, + color = AfternoteDesign.colors.gray6, + ) + Spacer(Modifier.width(12.dp)) + TextButton(onClick = onDelete, enabled = enabled) { + Text( + text = stringResource(R.string.setting_anniversary_delete), + style = AfternoteDesign.typography.captionLargeR, + color = AfternoteDesign.colors.gray6, + ) + } + } +} + +/** 수신인 하나와 월·일을 고른다. 연도는 받지 않는다 — 매년 그날 알린다. 2월은 29일까지 고를 수 있다. */ +@Composable +private fun AddAnniversaryDialog( + receivers: List, + onConfirm: (receiverId: Long, month: Int, day: Int) -> Unit, + onDismiss: () -> Unit, +) { + var receiverId by rememberSaveable { mutableStateOf(receivers.first().id) } + var month by rememberSaveable { mutableStateOf(1) } + var day by rememberSaveable { mutableStateOf(1) } + val maxDay = Month.of(month).maxLength() + if (day > maxDay) day = maxDay + + AlertDialog( + onDismissRequest = onDismiss, + containerColor = AfternoteDesign.colors.white, + title = { + Text( + text = stringResource(R.string.setting_anniversary_add), + style = AfternoteDesign.typography.bodyLargeB, + color = AfternoteDesign.colors.gray9, + ) + }, + text = { + Column { + PickerRow( + label = stringResource(R.string.setting_anniversary_receiver), + selected = receivers.first { it.id == receiverId }.name, + options = receivers.map { it.id to it.name }, + onSelect = { receiverId = it }, + ) + PickerRow( + label = stringResource(R.string.setting_anniversary_month), + selected = stringResource(R.string.setting_anniversary_month_value, month), + options = (1..12).map { it.toLong() to stringResource(R.string.setting_anniversary_month_value, it) }, + onSelect = { month = it.toInt() }, + ) + PickerRow( + label = stringResource(R.string.setting_anniversary_day), + selected = stringResource(R.string.setting_anniversary_day_value, day), + options = (1..maxDay).map { it.toLong() to stringResource(R.string.setting_anniversary_day_value, it) }, + onSelect = { day = it.toInt() }, + ) + } + }, + confirmButton = { + TextButton(onClick = { onConfirm(receiverId, month, day) }) { + Text(stringResource(R.string.setting_notification_preference_confirm), color = AfternoteDesign.colors.gray9) + } + }, + dismissButton = { + TextButton(onClick = onDismiss) { + Text(stringResource(R.string.setting_notification_preference_cancel), color = AfternoteDesign.colors.gray6) + } + }, + ) +} + +@Composable +private fun PickerRow( + label: String, + selected: String, + options: List>, + onSelect: (Long) -> Unit, +) { + var expanded by remember { mutableStateOf(false) } + Row( + modifier = + Modifier + .fillMaxWidth() + .clickable(role = Role.DropdownList) { expanded = true } + .padding(vertical = 12.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + text = label, + style = AfternoteDesign.typography.captionLargeR, + color = AfternoteDesign.colors.gray6, + modifier = Modifier.weight(1f), + ) + Box { + Text(text = selected, style = AfternoteDesign.typography.bodyBase, color = AfternoteDesign.colors.gray9) + DropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) { + options.forEach { (value, text) -> + DropdownMenuItem( + text = { Text(text) }, + onClick = { + expanded = false + onSelect(value) + }, + ) + } + } + } + } +} diff --git a/feature/setting/presentation/src/main/kotlin/com/afternote/feature/setting/presentation/notification/anniversary/AnniversaryViewModel.kt b/feature/setting/presentation/src/main/kotlin/com/afternote/feature/setting/presentation/notification/anniversary/AnniversaryViewModel.kt new file mode 100644 index 0000000000..e7f72b7ad0 --- /dev/null +++ b/feature/setting/presentation/src/main/kotlin/com/afternote/feature/setting/presentation/notification/anniversary/AnniversaryViewModel.kt @@ -0,0 +1,129 @@ +package com.afternote.feature.setting.presentation.notification.anniversary + +import androidx.lifecycle.viewModelScope +import com.afternote.core.domain.repository.UserReceiverRepository +import com.afternote.core.domain.result.runCatchingCancellable +import com.afternote.core.ui.UiText +import com.afternote.core.ui.mvi.MviViewModel +import com.afternote.feature.setting.domain.NotificationAnniversary +import com.afternote.feature.setting.domain.NotificationPreferenceRepository +import com.afternote.feature.setting.presentation.R +import dagger.hilt.android.lifecycle.HiltViewModel +import kotlinx.coroutines.async +import kotlinx.coroutines.launch +import javax.inject.Inject + +/** + * 수신인 생일을 등록·삭제한다 (#2321). 그날 서버가 「오늘은 ○○님 생신이에요」 알림을 보내고, + * 알림을 누르면 그 수신인 앞으로 편지 작성이 열린다. + */ +@HiltViewModel +internal class AnniversaryViewModel + @Inject + constructor( + private val repository: NotificationPreferenceRepository, + private val receiverRepository: UserReceiverRepository, + ) : MviViewModel(AnniversaryUiState()) { + init { + load() + } + + override fun onIntent(intent: AnniversaryIntent) { + when (intent) { + AnniversaryIntent.Retry -> load() + is AnniversaryIntent.Add -> add(intent.receiverId, intent.month, intent.day) + is AnniversaryIntent.Delete -> delete(intent.anniversaryId) + AnniversaryIntent.ConsumeError -> dispatch(AnniversaryReducerEvent.ErrorConsumed) + } + } + + override fun reduce( + state: AnniversaryUiState, + event: AnniversaryReducerEvent, + ): AnniversaryUiState = + when (event) { + AnniversaryReducerEvent.Loading -> { + state.copy(isLoading = true, loadFailed = false) + } + + is AnniversaryReducerEvent.Loaded -> { + state.copy(isLoading = false, items = event.items.sortedForDisplay(), receivers = event.receivers) + } + + AnniversaryReducerEvent.LoadFailed -> { + state.copy(isLoading = false, loadFailed = true) + } + + AnniversaryReducerEvent.Submitting -> { + state.copy(isSubmitting = true, errorMessage = null) + } + + is AnniversaryReducerEvent.Added -> { + state.copy(isSubmitting = false, items = (state.items + event.item).sortedForDisplay()) + } + + is AnniversaryReducerEvent.Deleted -> { + state.copy(isSubmitting = false, items = state.items.filterNot { it.id == event.anniversaryId }) + } + + is AnniversaryReducerEvent.Failed -> { + state.copy(isSubmitting = false, errorMessage = event.message) + } + + AnniversaryReducerEvent.ErrorConsumed -> { + state.copy(errorMessage = null) + } + } + + private fun load() { + dispatch(AnniversaryReducerEvent.Loading) + viewModelScope.launch { + val receivers = async { runCatchingCancellable { receiverRepository.getReceivers() } } + val anniversaries = async { repository.getAnniversaries() } + val receiverList = receivers.await().getOrNull() + val anniversaryList = anniversaries.await().getOrNull() + if (receiverList == null || anniversaryList == null) { + dispatch(AnniversaryReducerEvent.LoadFailed) + return@launch + } + val options = receiverList.map { AnniversaryReceiver(id = it.receiverId, name = it.name) } + dispatch(AnniversaryReducerEvent.Loaded(anniversaryList.map { it.toItem(options) }, options)) + } + } + + private fun add( + receiverId: Long, + month: Int, + day: Int, + ) { + if (currentState.isSubmitting) return + dispatch(AnniversaryReducerEvent.Submitting) + viewModelScope.launch { + repository + .addAnniversary(receiverId, month, day) + .onSuccess { dispatch(AnniversaryReducerEvent.Added(it.toItem(currentState.receivers))) } + .onFailure { dispatch(AnniversaryReducerEvent.Failed(UiText.Resource(R.string.setting_anniversary_add_failed))) } + } + } + + private fun delete(anniversaryId: Long) { + if (currentState.isSubmitting) return + dispatch(AnniversaryReducerEvent.Submitting) + viewModelScope.launch { + repository + .deleteAnniversary(anniversaryId) + .onSuccess { dispatch(AnniversaryReducerEvent.Deleted(anniversaryId)) } + .onFailure { dispatch(AnniversaryReducerEvent.Failed(UiText.Resource(R.string.setting_anniversary_delete_failed))) } + } + } + } + +private fun NotificationAnniversary.toItem(receivers: List): AnniversaryItem = + AnniversaryItem( + id = id, + receiverName = receivers.firstOrNull { it.id == receiverId }?.name, + month = month, + day = day, + ) + +private fun List.sortedForDisplay(): List = sortedWith(compareBy({ it.month }, { it.day }, { it.id })) diff --git a/feature/setting/presentation/src/main/kotlin/com/afternote/feature/setting/presentation/notification/delegate/DelegateContract.kt b/feature/setting/presentation/src/main/kotlin/com/afternote/feature/setting/presentation/notification/delegate/DelegateContract.kt new file mode 100644 index 0000000000..e2f3e4bdd0 --- /dev/null +++ b/feature/setting/presentation/src/main/kotlin/com/afternote/feature/setting/presentation/notification/delegate/DelegateContract.kt @@ -0,0 +1,60 @@ +package com.afternote.feature.setting.presentation.notification.delegate + +import com.afternote.core.ui.UiText +import com.afternote.core.ui.mvi.MviIntent +import com.afternote.core.ui.mvi.ReducerEvent +import com.afternote.core.ui.mvi.UiState +import com.afternote.feature.setting.domain.NotificationDelegate + +internal sealed interface DelegateIntent : MviIntent { + data object Retry : DelegateIntent + + data class Save( + val name: String, + val phone: String, + ) : DelegateIntent + + data object Remove : DelegateIntent + + data object ConsumeDone : DelegateIntent + + data object ConsumeError : DelegateIntent +} + +/** + * @property delegate 서버에 지정된 대리인. 없으면 null 이고 입력칸이 빈 채로 열린다. + * @property doneMessage 저장·해제 성공 안내. 화면이 한 번 띄우고 소비한다. + */ +internal data class DelegateUiState( + val isLoading: Boolean = true, + val loadFailed: Boolean = false, + val delegate: NotificationDelegate? = null, + val isSubmitting: Boolean = false, + val doneMessage: UiText? = null, + val errorMessage: UiText? = null, +) : UiState + +internal sealed interface DelegateReducerEvent : ReducerEvent { + data object Loading : DelegateReducerEvent + + data class Loaded( + val delegate: NotificationDelegate?, + ) : DelegateReducerEvent + + data object LoadFailed : DelegateReducerEvent + + data object Submitting : DelegateReducerEvent + + data class Done( + val delegate: NotificationDelegate?, + val message: UiText, + ) : DelegateReducerEvent + + data class Failed( + val message: UiText, + ) : DelegateReducerEvent + + data object DoneConsumed : DelegateReducerEvent + + data object ErrorConsumed : DelegateReducerEvent +} diff --git a/feature/setting/presentation/src/main/kotlin/com/afternote/feature/setting/presentation/notification/delegate/DelegateScreen.kt b/feature/setting/presentation/src/main/kotlin/com/afternote/feature/setting/presentation/notification/delegate/DelegateScreen.kt new file mode 100644 index 0000000000..623a6d6576 --- /dev/null +++ b/feature/setting/presentation/src/main/kotlin/com/afternote/feature/setting/presentation/notification/delegate/DelegateScreen.kt @@ -0,0 +1,160 @@ +package com.afternote.feature.setting.presentation.notification.delegate + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +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.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.text.input.TextFieldState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.SnackbarHostState +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.unit.dp +import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import com.afternote.core.ui.CaptionLabeledTextField +import com.afternote.core.ui.asString +import com.afternote.core.ui.button.AfternoteButton +import com.afternote.core.ui.mvi.ObserveSignal +import com.afternote.core.ui.theme.AfternoteDesign +import com.afternote.core.ui.topbar.DetailTopBar +import com.afternote.feature.setting.domain.NotificationDelegate +import com.afternote.feature.setting.presentation.R +import com.afternote.feature.setting.presentation.shared.component.SettingLoadErrorContent +import kotlinx.coroutines.launch + +@Composable +internal fun DelegateScreen( + onBack: () -> Unit, + viewModel: DelegateViewModel = hiltViewModel(), +) { + val uiState by viewModel.uiState.collectAsStateWithLifecycle() + val snackbarHostState = remember { SnackbarHostState() } + val snackbarScope = rememberCoroutineScope() + + val doneMessage = uiState.doneMessage?.asString() + ObserveSignal(signal = doneMessage, consumed = DelegateIntent.ConsumeDone, onIntent = viewModel::onIntent) { message -> + snackbarScope.launch { snackbarHostState.showSnackbar(message) } + } + val errorMessage = uiState.errorMessage?.asString() + ObserveSignal(signal = errorMessage, consumed = DelegateIntent.ConsumeError, onIntent = viewModel::onIntent) { message -> + snackbarScope.launch { snackbarHostState.showSnackbar(message) } + } + + DelegateContent( + uiState = uiState, + snackbarHostState = snackbarHostState, + onBack = onBack, + onIntent = viewModel::onIntent, + ) +} + +@Composable +internal fun DelegateContent( + uiState: DelegateUiState, + snackbarHostState: SnackbarHostState, + onBack: () -> Unit, + onIntent: (DelegateIntent) -> Unit, +) { + Scaffold( + topBar = { + DetailTopBar(title = stringResource(R.string.setting_delegate_title), onBackClick = onBack) + }, + snackbarHost = { SnackbarHost(snackbarHostState) }, + containerColor = Color.Transparent, + ) { padding -> + when { + uiState.isLoading -> { + Box(Modifier.fillMaxSize().padding(padding), contentAlignment = Alignment.Center) { + CircularProgressIndicator(color = AfternoteDesign.colors.gray9) + } + } + + uiState.loadFailed -> { + SettingLoadErrorContent( + message = stringResource(R.string.setting_delegate_load_failed), + onRetry = { onIntent(DelegateIntent.Retry) }, + modifier = Modifier.padding(padding), + ) + } + + else -> { + DelegateForm( + delegate = uiState.delegate, + isSubmitting = uiState.isSubmitting, + onIntent = onIntent, + modifier = Modifier.padding(padding), + ) + } + } + } +} + +@Composable +private fun DelegateForm( + delegate: NotificationDelegate?, + isSubmitting: Boolean, + onIntent: (DelegateIntent) -> Unit, + modifier: Modifier = Modifier, +) { + // 서버 값이 바뀌면(저장·해제) 입력칸도 그 값으로 다시 연다. + val nameState = remember(delegate) { TextFieldState(delegate?.name.orEmpty()) } + val phoneState = remember(delegate) { TextFieldState(delegate?.phone.orEmpty()) } + Column( + modifier = + modifier + .fillMaxSize() + .verticalScroll(rememberScrollState()) + .padding(horizontal = 20.dp, vertical = 16.dp), + ) { + Text( + text = stringResource(R.string.setting_delegate_description), + style = AfternoteDesign.typography.captionLargeR, + color = AfternoteDesign.colors.gray6, + ) + Spacer(Modifier.height(24.dp)) + CaptionLabeledTextField(label = stringResource(R.string.setting_delegate_name), state = nameState) + Spacer(Modifier.height(16.dp)) + CaptionLabeledTextField( + label = stringResource(R.string.setting_delegate_phone), + state = phoneState, + keyboardType = KeyboardType.Phone, + ) + Spacer(Modifier.height(32.dp)) + AfternoteButton( + text = stringResource(R.string.setting_delegate_save), + onClick = { onIntent(DelegateIntent.Save(nameState.text.toString(), phoneState.text.toString())) }, + isLoading = isSubmitting, + modifier = Modifier.fillMaxWidth(), + ) + if (delegate != null) { + TextButton( + onClick = { onIntent(DelegateIntent.Remove) }, + enabled = !isSubmitting, + modifier = Modifier.align(Alignment.CenterHorizontally).padding(top = 8.dp), + ) { + Text( + text = stringResource(R.string.setting_delegate_remove), + style = AfternoteDesign.typography.captionLargeR, + color = AfternoteDesign.colors.gray6, + ) + } + } + } +} diff --git a/feature/setting/presentation/src/main/kotlin/com/afternote/feature/setting/presentation/notification/delegate/DelegateViewModel.kt b/feature/setting/presentation/src/main/kotlin/com/afternote/feature/setting/presentation/notification/delegate/DelegateViewModel.kt new file mode 100644 index 0000000000..0839779ae1 --- /dev/null +++ b/feature/setting/presentation/src/main/kotlin/com/afternote/feature/setting/presentation/notification/delegate/DelegateViewModel.kt @@ -0,0 +1,112 @@ +package com.afternote.feature.setting.presentation.notification.delegate + +import androidx.lifecycle.viewModelScope +import com.afternote.core.ui.UiText +import com.afternote.core.ui.mvi.MviViewModel +import com.afternote.feature.setting.domain.NotificationDelegate +import com.afternote.feature.setting.domain.NotificationPreferenceRepository +import com.afternote.feature.setting.presentation.R +import com.afternote.feature.setting.presentation.receiver.ReceiverPhoneValidation +import com.afternote.feature.setting.presentation.receiver.normalizeReceiverPhone +import com.afternote.feature.setting.presentation.receiver.validateReceiverPhone +import dagger.hilt.android.lifecycle.HiltViewModel +import kotlinx.coroutines.launch +import javax.inject.Inject + +/** + * 대리인을 지정·변경·해제한다 (#2321). + * + * 대리인은 사용자가 오래 접속하지 않을 때 서버가 연락하는 사람이다. 수신인과 별개이고, 연락만 받을 뿐 + * 기록을 열람하지 않는다. 연락처 형식은 수신인과 같은 규칙으로 검사한다. + */ +@HiltViewModel +internal class DelegateViewModel + @Inject + constructor( + private val repository: NotificationPreferenceRepository, + ) : MviViewModel(DelegateUiState()) { + init { + load() + } + + override fun onIntent(intent: DelegateIntent) { + when (intent) { + DelegateIntent.Retry -> load() + is DelegateIntent.Save -> save(intent.name, intent.phone) + DelegateIntent.Remove -> remove() + DelegateIntent.ConsumeDone -> dispatch(DelegateReducerEvent.DoneConsumed) + DelegateIntent.ConsumeError -> dispatch(DelegateReducerEvent.ErrorConsumed) + } + } + + override fun reduce( + state: DelegateUiState, + event: DelegateReducerEvent, + ): DelegateUiState = + when (event) { + DelegateReducerEvent.Loading -> state.copy(isLoading = true, loadFailed = false) + is DelegateReducerEvent.Loaded -> state.copy(isLoading = false, delegate = event.delegate) + DelegateReducerEvent.LoadFailed -> state.copy(isLoading = false, loadFailed = true) + DelegateReducerEvent.Submitting -> state.copy(isSubmitting = true, errorMessage = null) + is DelegateReducerEvent.Done -> state.copy(isSubmitting = false, delegate = event.delegate, doneMessage = event.message) + is DelegateReducerEvent.Failed -> state.copy(isSubmitting = false, errorMessage = event.message) + DelegateReducerEvent.DoneConsumed -> state.copy(doneMessage = null) + DelegateReducerEvent.ErrorConsumed -> state.copy(errorMessage = null) + } + + private fun load() { + dispatch(DelegateReducerEvent.Loading) + viewModelScope.launch { + repository + .getDelegate() + .onSuccess { dispatch(DelegateReducerEvent.Loaded(it)) } + .onFailure { dispatch(DelegateReducerEvent.LoadFailed) } + } + } + + private fun save( + name: String, + phone: String, + ) { + if (currentState.isSubmitting) return + val trimmedName = name.trim() + if (trimmedName.isEmpty()) { + dispatch(DelegateReducerEvent.Failed(UiText.Resource(R.string.setting_delegate_name_required))) + return + } + when (phone.validateReceiverPhone(isRequired = true)) { + ReceiverPhoneValidation.VALID -> { + Unit + } + + ReceiverPhoneValidation.REQUIRED -> { + dispatch(DelegateReducerEvent.Failed(UiText.Resource(R.string.setting_delegate_phone_required))) + return + } + + ReceiverPhoneValidation.INVALID -> { + dispatch(DelegateReducerEvent.Failed(UiText.Resource(R.string.setting_delegate_phone_invalid))) + return + } + } + val delegate = NotificationDelegate(name = trimmedName, phone = phone.normalizeReceiverPhone()) + dispatch(DelegateReducerEvent.Submitting) + viewModelScope.launch { + repository + .updateDelegate(delegate) + .onSuccess { dispatch(DelegateReducerEvent.Done(delegate, UiText.Resource(R.string.setting_delegate_saved))) } + .onFailure { dispatch(DelegateReducerEvent.Failed(UiText.Resource(R.string.setting_delegate_save_failed))) } + } + } + + private fun remove() { + if (currentState.isSubmitting || currentState.delegate == null) return + dispatch(DelegateReducerEvent.Submitting) + viewModelScope.launch { + repository + .deleteDelegate() + .onSuccess { dispatch(DelegateReducerEvent.Done(null, UiText.Resource(R.string.setting_delegate_removed))) } + .onFailure { dispatch(DelegateReducerEvent.Failed(UiText.Resource(R.string.setting_delegate_save_failed))) } + } + } + } diff --git a/feature/setting/presentation/src/main/kotlin/com/afternote/feature/setting/presentation/notification/preference/NotificationPreferenceContract.kt b/feature/setting/presentation/src/main/kotlin/com/afternote/feature/setting/presentation/notification/preference/NotificationPreferenceContract.kt new file mode 100644 index 0000000000..9c4946f40b --- /dev/null +++ b/feature/setting/presentation/src/main/kotlin/com/afternote/feature/setting/presentation/notification/preference/NotificationPreferenceContract.kt @@ -0,0 +1,77 @@ +package com.afternote.feature.setting.presentation.notification.preference + +import com.afternote.core.ui.UiText +import com.afternote.core.ui.mvi.MviIntent +import com.afternote.core.ui.mvi.ReducerEvent +import com.afternote.core.ui.mvi.UiState +import com.afternote.feature.setting.domain.NotificationPreferences +import java.time.DayOfWeek +import java.time.LocalTime + +internal sealed interface NotificationPreferenceIntent : MviIntent { + data object Retry : NotificationPreferenceIntent + + data class ChangeEnabled( + val enabled: Boolean, + ) : NotificationPreferenceIntent + + data class ChangeTime( + val time: LocalTime, + ) : NotificationPreferenceIntent + + data class ToggleWeekday( + val day: DayOfWeek, + ) : NotificationPreferenceIntent + + data class ChangeWeeklyGoal( + val goal: Int, + ) : NotificationPreferenceIntent + + data object Save : NotificationPreferenceIntent + + data object ConsumeSaved : NotificationPreferenceIntent + + data object ConsumeError : NotificationPreferenceIntent +} + +/** + * @property form 편집 중인 값. 불러오기 전에는 null 이다 — 기본값을 채워 두면 서버 값을 받기 전에 + * 「18:00」 이 사용자의 설정처럼 보인다. + * @property isSaved 저장 성공 신호. 화면이 한 번 안내하고 소비한다. + */ +internal data class NotificationPreferenceUiState( + val isLoading: Boolean = true, + val loadFailed: Boolean = false, + val form: NotificationPreferences? = null, + val isSaving: Boolean = false, + val isSaved: Boolean = false, + val errorMessage: UiText? = null, +) : UiState + +internal sealed interface NotificationPreferenceReducerEvent : ReducerEvent { + data object Loading : NotificationPreferenceReducerEvent + + data class Loaded( + val preferences: NotificationPreferences, + ) : NotificationPreferenceReducerEvent + + data object LoadFailed : NotificationPreferenceReducerEvent + + data class Edited( + val form: NotificationPreferences, + ) : NotificationPreferenceReducerEvent + + data object Saving : NotificationPreferenceReducerEvent + + data class Saved( + val preferences: NotificationPreferences, + ) : NotificationPreferenceReducerEvent + + data class Failed( + val message: UiText, + ) : NotificationPreferenceReducerEvent + + data object SavedConsumed : NotificationPreferenceReducerEvent + + data object ErrorConsumed : NotificationPreferenceReducerEvent +} diff --git a/feature/setting/presentation/src/main/kotlin/com/afternote/feature/setting/presentation/notification/preference/NotificationPreferenceScreen.kt b/feature/setting/presentation/src/main/kotlin/com/afternote/feature/setting/presentation/notification/preference/NotificationPreferenceScreen.kt new file mode 100644 index 0000000000..ef1c244c69 --- /dev/null +++ b/feature/setting/presentation/src/main/kotlin/com/afternote/feature/setting/presentation/notification/preference/NotificationPreferenceScreen.kt @@ -0,0 +1,342 @@ +package com.afternote.feature.setting.presentation.notification.preference + +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +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.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.SnackbarHostState +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TimePicker +import androidx.compose.material3.rememberTimePickerState +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.graphics.Color +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.selected +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.unit.dp +import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import com.afternote.core.ui.asString +import com.afternote.core.ui.button.AfternoteButton +import com.afternote.core.ui.mvi.ObserveFlag +import com.afternote.core.ui.mvi.ObserveSignal +import com.afternote.core.ui.theme.AfternoteDesign +import com.afternote.core.ui.topbar.DetailTopBar +import com.afternote.feature.setting.domain.NotificationPreferences +import com.afternote.feature.setting.presentation.R +import com.afternote.feature.setting.presentation.notification.component.LabeledSwitchRow +import com.afternote.feature.setting.presentation.shared.component.SettingLoadErrorContent +import kotlinx.coroutines.launch +import java.time.DayOfWeek +import java.time.LocalTime +import java.time.format.DateTimeFormatter +import java.time.format.TextStyle +import java.util.Locale + +@Composable +internal fun NotificationPreferenceScreen( + onBack: () -> Unit, + viewModel: NotificationPreferenceViewModel = hiltViewModel(), +) { + val uiState by viewModel.uiState.collectAsStateWithLifecycle() + val snackbarHostState = remember { SnackbarHostState() } + val snackbarScope = rememberCoroutineScope() + val savedMessage = stringResource(R.string.setting_notification_preference_saved) + + ObserveFlag( + raised = uiState.isSaved, + consumed = NotificationPreferenceIntent.ConsumeSaved, + onIntent = viewModel::onIntent, + ) { + snackbarScope.launch { snackbarHostState.showSnackbar(savedMessage) } + } + val errorMessage = uiState.errorMessage?.asString() + ObserveSignal( + signal = errorMessage, + consumed = NotificationPreferenceIntent.ConsumeError, + onIntent = viewModel::onIntent, + ) { message -> + snackbarScope.launch { snackbarHostState.showSnackbar(message) } + } + + NotificationPreferenceContent( + uiState = uiState, + snackbarHostState = snackbarHostState, + onBack = onBack, + onIntent = viewModel::onIntent, + ) +} + +@Composable +internal fun NotificationPreferenceContent( + uiState: NotificationPreferenceUiState, + snackbarHostState: SnackbarHostState, + onBack: () -> Unit, + onIntent: (NotificationPreferenceIntent) -> Unit, +) { + Scaffold( + topBar = { + DetailTopBar( + title = stringResource(R.string.setting_notification_preference_title), + onBackClick = onBack, + ) + }, + snackbarHost = { SnackbarHost(snackbarHostState) }, + containerColor = Color.Transparent, + ) { padding -> + val form = uiState.form + when { + form != null -> { + PreferenceForm( + form = form, + isSaving = uiState.isSaving, + onIntent = onIntent, + modifier = Modifier.padding(padding), + ) + } + + uiState.loadFailed -> { + SettingLoadErrorContent( + message = stringResource(R.string.setting_notification_preference_load_failed), + onRetry = { onIntent(NotificationPreferenceIntent.Retry) }, + modifier = Modifier.padding(padding), + ) + } + + else -> { + Box(Modifier.fillMaxSize().padding(padding), contentAlignment = Alignment.Center) { + CircularProgressIndicator(color = AfternoteDesign.colors.gray9) + } + } + } + } +} + +@Composable +private fun PreferenceForm( + form: NotificationPreferences, + isSaving: Boolean, + onIntent: (NotificationPreferenceIntent) -> Unit, + modifier: Modifier = Modifier, +) { + var isPickingTime by rememberSaveable { mutableStateOf(false) } + Column( + modifier = + modifier + .fillMaxSize() + .verticalScroll(rememberScrollState()) + .padding(horizontal = 20.dp, vertical = 16.dp), + ) { + LabeledSwitchRow( + label = stringResource(R.string.setting_notification_preference_enabled), + checked = form.enabled, + onCheckedChange = { onIntent(NotificationPreferenceIntent.ChangeEnabled(it)) }, + enabled = !isSaving, + ) + Text( + text = stringResource(R.string.setting_notification_preference_description), + style = AfternoteDesign.typography.captionLargeR, + color = AfternoteDesign.colors.gray6, + ) + + SectionLabel(stringResource(R.string.setting_notification_preference_time)) + Row( + modifier = + Modifier + .fillMaxWidth() + .clickable(enabled = form.enabled && !isSaving, role = Role.Button) { isPickingTime = true } + .padding(vertical = 12.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + text = form.time.toDisplayText(), + style = AfternoteDesign.typography.bodyLargeB, + color = if (form.enabled) AfternoteDesign.colors.gray9 else AfternoteDesign.colors.gray5, + modifier = Modifier.weight(1f), + ) + Text( + text = stringResource(R.string.setting_notification_preference_change), + style = AfternoteDesign.typography.captionLargeR, + color = AfternoteDesign.colors.gray6, + ) + } + + SectionLabel(stringResource(R.string.setting_notification_preference_weekdays)) + Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) { + DayOfWeek.entries.forEach { day -> + WeekdayChip( + day = day, + selected = day in form.weekdays, + enabled = form.enabled && !isSaving, + onClick = { onIntent(NotificationPreferenceIntent.ToggleWeekday(day)) }, + ) + } + } + + SectionLabel(stringResource(R.string.setting_notification_preference_goal)) + Row(verticalAlignment = Alignment.CenterVertically) { + StepButton( + text = "−", + enabled = !isSaving && form.weeklyGoal > 1, + onClick = { onIntent(NotificationPreferenceIntent.ChangeWeeklyGoal(form.weeklyGoal - 1)) }, + ) + Text( + text = stringResource(R.string.setting_notification_preference_goal_value, form.weeklyGoal), + style = AfternoteDesign.typography.bodyLargeB, + color = AfternoteDesign.colors.gray9, + modifier = Modifier.padding(horizontal = 16.dp), + ) + StepButton( + text = "+", + enabled = !isSaving && form.weeklyGoal < 7, + onClick = { onIntent(NotificationPreferenceIntent.ChangeWeeklyGoal(form.weeklyGoal + 1)) }, + ) + } + Text( + text = stringResource(R.string.setting_notification_preference_goal_description), + style = AfternoteDesign.typography.captionLargeR, + color = AfternoteDesign.colors.gray6, + modifier = Modifier.padding(top = 8.dp), + ) + + Spacer(Modifier.height(32.dp)) + AfternoteButton( + text = stringResource(R.string.setting_notification_preference_save), + onClick = { onIntent(NotificationPreferenceIntent.Save) }, + isLoading = isSaving, + modifier = Modifier.fillMaxWidth(), + ) + } + + if (isPickingTime) { + TimePickerDialog( + initial = form.time, + onConfirm = { time -> + isPickingTime = false + onIntent(NotificationPreferenceIntent.ChangeTime(time)) + }, + onDismiss = { isPickingTime = false }, + ) + } +} + +@Composable +private fun SectionLabel(text: String) { + Text( + text = text, + style = AfternoteDesign.typography.captionLargeR, + color = AfternoteDesign.colors.gray6, + modifier = Modifier.padding(top = 24.dp, bottom = 8.dp), + ) +} + +@Composable +private fun WeekdayChip( + day: DayOfWeek, + selected: Boolean, + enabled: Boolean, + onClick: () -> Unit, +) { + val label = day.getDisplayName(TextStyle.NARROW, Locale.KOREAN) + Box( + modifier = + Modifier + .size(40.dp) + .border( + width = 1.dp, + color = if (selected) AfternoteDesign.colors.gray9 else AfternoteDesign.colors.gray3, + shape = CircleShape, + ).clickable(enabled = enabled, role = Role.Checkbox, onClick = onClick) + .semantics { this.selected = selected }, + contentAlignment = Alignment.Center, + ) { + Text( + text = label, + style = AfternoteDesign.typography.bodyBase, + color = + when { + !enabled -> AfternoteDesign.colors.gray5 + selected -> AfternoteDesign.colors.gray9 + else -> AfternoteDesign.colors.gray6 + }, + ) + } +} + +@Composable +private fun StepButton( + text: String, + enabled: Boolean, + onClick: () -> Unit, +) { + Box( + modifier = + Modifier + .size(36.dp) + .border(1.dp, AfternoteDesign.colors.gray3, CircleShape) + .clickable(enabled = enabled, role = Role.Button, onClick = onClick), + contentAlignment = Alignment.Center, + ) { + Text( + text = text, + style = AfternoteDesign.typography.bodyLargeB, + color = if (enabled) AfternoteDesign.colors.gray9 else AfternoteDesign.colors.gray5, + ) + } +} + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +private fun TimePickerDialog( + initial: LocalTime, + onConfirm: (LocalTime) -> Unit, + onDismiss: () -> Unit, +) { + val state = rememberTimePickerState(initialHour = initial.hour, initialMinute = initial.minute, is24Hour = false) + AlertDialog( + onDismissRequest = onDismiss, + confirmButton = { + TextButton(onClick = { onConfirm(LocalTime.of(state.hour, state.minute)) }) { + Text(stringResource(R.string.setting_notification_preference_confirm), color = AfternoteDesign.colors.gray9) + } + }, + dismissButton = { + TextButton(onClick = onDismiss) { + Text(stringResource(R.string.setting_notification_preference_cancel), color = AfternoteDesign.colors.gray6) + } + }, + text = { TimePicker(state = state) }, + containerColor = AfternoteDesign.colors.white, + ) +} + +/** 「오후 6:00」 처럼 보여 준다. 서버 계약은 24시간 `HH:mm` 이고 표시만 바꾼다. */ +private fun LocalTime.toDisplayText(): String = format(DISPLAY_TIME) + +private val DISPLAY_TIME: DateTimeFormatter = DateTimeFormatter.ofPattern("a h:mm", Locale.KOREAN) diff --git a/feature/setting/presentation/src/main/kotlin/com/afternote/feature/setting/presentation/notification/preference/NotificationPreferenceViewModel.kt b/feature/setting/presentation/src/main/kotlin/com/afternote/feature/setting/presentation/notification/preference/NotificationPreferenceViewModel.kt new file mode 100644 index 0000000000..dc55886dd5 --- /dev/null +++ b/feature/setting/presentation/src/main/kotlin/com/afternote/feature/setting/presentation/notification/preference/NotificationPreferenceViewModel.kt @@ -0,0 +1,108 @@ +package com.afternote.feature.setting.presentation.notification.preference + +import androidx.annotation.StringRes +import androidx.lifecycle.viewModelScope +import com.afternote.core.ui.UiText +import com.afternote.core.ui.mvi.MviViewModel +import com.afternote.feature.setting.domain.NotificationPreferenceRepository +import com.afternote.feature.setting.domain.NotificationPreferences +import com.afternote.feature.setting.presentation.R +import dagger.hilt.android.lifecycle.HiltViewModel +import kotlinx.coroutines.launch +import javax.inject.Inject + +/** + * 기록 알림 시각·요일·주간 목표를 고친다 (#2321). + * + * 값을 바꿀 때마다 저장하지 않고 «저장» 으로 한 번에 보낸다. 서버는 설정이 바뀔 때마다 대기 중인 + * 기록 알림을 취소하고 다시 잡으므로, 시각을 고르는 도중의 값마다 그 일을 시키지 않는다. + */ +@HiltViewModel +internal class NotificationPreferenceViewModel + @Inject + constructor( + private val repository: NotificationPreferenceRepository, + ) : MviViewModel( + NotificationPreferenceUiState(), + ) { + init { + load() + } + + override fun onIntent(intent: NotificationPreferenceIntent) { + when (intent) { + NotificationPreferenceIntent.Retry -> load() + is NotificationPreferenceIntent.ChangeEnabled -> edit { it.copy(enabled = intent.enabled) } + is NotificationPreferenceIntent.ChangeTime -> edit { it.copy(time = intent.time.withSecond(0).withNano(0)) } + is NotificationPreferenceIntent.ToggleWeekday -> edit { it.copy(weekdays = it.weekdays.toggle(intent.day)) } + is NotificationPreferenceIntent.ChangeWeeklyGoal -> edit { it.copy(weeklyGoal = intent.goal.coerceIn(MIN_GOAL, MAX_GOAL)) } + NotificationPreferenceIntent.Save -> save() + NotificationPreferenceIntent.ConsumeSaved -> dispatch(NotificationPreferenceReducerEvent.SavedConsumed) + NotificationPreferenceIntent.ConsumeError -> dispatch(NotificationPreferenceReducerEvent.ErrorConsumed) + } + } + + override fun reduce( + state: NotificationPreferenceUiState, + event: NotificationPreferenceReducerEvent, + ): NotificationPreferenceUiState = + when (event) { + NotificationPreferenceReducerEvent.Loading -> state.copy(isLoading = true, loadFailed = false) + is NotificationPreferenceReducerEvent.Loaded -> state.copy(isLoading = false, form = event.preferences) + NotificationPreferenceReducerEvent.LoadFailed -> state.copy(isLoading = false, loadFailed = true) + is NotificationPreferenceReducerEvent.Edited -> state.copy(form = event.form) + NotificationPreferenceReducerEvent.Saving -> state.copy(isSaving = true, errorMessage = null) + is NotificationPreferenceReducerEvent.Saved -> state.copy(isSaving = false, isSaved = true, form = event.preferences) + is NotificationPreferenceReducerEvent.Failed -> state.copy(isSaving = false, errorMessage = event.message) + NotificationPreferenceReducerEvent.SavedConsumed -> state.copy(isSaved = false) + NotificationPreferenceReducerEvent.ErrorConsumed -> state.copy(errorMessage = null) + } + + private fun load() { + dispatch(NotificationPreferenceReducerEvent.Loading) + viewModelScope.launch { + repository + .getPreferences() + .onSuccess { dispatch(NotificationPreferenceReducerEvent.Loaded(it)) } + .onFailure { dispatch(NotificationPreferenceReducerEvent.LoadFailed) } + } + } + + private fun edit(transform: (NotificationPreferences) -> NotificationPreferences) { + val form = currentState.form ?: return + if (currentState.isSaving) return + dispatch(NotificationPreferenceReducerEvent.Edited(transform(form))) + } + + private fun save() { + val form = currentState.form ?: return + if (currentState.isSaving) return + // 알림을 받는 동안 요일이 하나도 없으면 서버가 거부한다. 요청 전에 막아 이유를 알려 준다. + if (form.enabled && form.weekdays.isEmpty()) { + dispatch( + NotificationPreferenceReducerEvent.Failed(UiText.Resource(R.string.setting_notification_preference_weekday_required)), + ) + return + } + dispatch(NotificationPreferenceReducerEvent.Saving) + viewModelScope.launch { + repository + .updatePreferences(form) + .onSuccess { dispatch(NotificationPreferenceReducerEvent.Saved(it)) } + .onFailure { + dispatch( + NotificationPreferenceReducerEvent.Failed( + UiText.Resource(R.string.setting_notification_preference_save_failed), + ), + ) + } + } + } + + private companion object { + const val MIN_GOAL = 1 + const val MAX_GOAL = 7 + } + } + +private fun Set.toggle(value: T): Set = if (value in this) this - value else this + value diff --git a/feature/setting/presentation/src/main/res/values/strings.xml b/feature/setting/presentation/src/main/res/values/strings.xml index d2dc39012a..8f3682e7c8 100644 --- a/feature/setting/presentation/src/main/res/values/strings.xml +++ b/feature/setting/presentation/src/main/res/values/strings.xml @@ -218,4 +218,53 @@ 패스키 등록 준비에 실패했습니다. 다시 시도해 주세요. 패스키 등록에 실패했습니다. 다시 시도해 주세요. 패스키 생성이 완료되었습니다 + + 기록 알림 시간 + 대리인 + 수신인 기념일 + 기록 알림 + 기록 알림 받기 + 고른 요일·시각에 기록을 권하는 알림을 보내요. 다른 알림과 합쳐 하루에 한 번만 보내고, 밤 10시부터 아침 8시 사이에는 보내지 않아요. + 알림 시각 + 변경 + 알림 요일 + 주간 목표 + 주 %1$d회 + 이번 주 기록 횟수를 이 목표와 견주어 금요일에 알려 드려요. + 저장 + 알림 설정을 저장했어요 + 알림 설정을 저장하지 못했어요. 잠시 후 다시 시도해 주세요. + 알림 설정을 불러오지 못했어요. + 알림 요일을 하나 이상 골라 주세요. + 확인 + 취소 + 대리인 + 오래 들어오지 않으시면 이분께 연락드려요. 수신인과는 별개이고, 남기신 기록을 열람하지 않아요. + 이름 + 연락처 + 저장 + 대리인 해제 + 대리인을 저장했어요 + 대리인을 해제했어요 + 대리인을 저장하지 못했어요. 잠시 후 다시 시도해 주세요. + 대리인 정보를 불러오지 못했어요. + 이름을 입력해 주세요. + 연락처를 입력해 주세요. + 연락처 형식을 확인해 주세요. + 수신인 기념일 + 수신인의 생일을 등록하면 그날 편지를 남길 수 있게 알려 드려요. + 등록한 기념일이 없어요 + 수신인을 먼저 등록해 주세요. + 기념일 추가 + 삭제 + %1$d월 %2$d일 + 수신인 + 월 + 일 + %1$d월 + %1$d일 + 삭제된 수신인 + 기념일을 추가하지 못했어요. 잠시 후 다시 시도해 주세요. + 기념일을 삭제하지 못했어요. 잠시 후 다시 시도해 주세요. + 기념일을 불러오지 못했어요. diff --git a/feature/setting/presentation/src/test/kotlin/com/afternote/feature/setting/presentation/notification/NotificationPreferenceSettingsTest.kt b/feature/setting/presentation/src/test/kotlin/com/afternote/feature/setting/presentation/notification/NotificationPreferenceSettingsTest.kt new file mode 100644 index 0000000000..04c856b0cd --- /dev/null +++ b/feature/setting/presentation/src/test/kotlin/com/afternote/feature/setting/presentation/notification/NotificationPreferenceSettingsTest.kt @@ -0,0 +1,211 @@ +package com.afternote.feature.setting.presentation.notification + +import com.afternote.core.domain.testing.FakeUserReceiverRepository +import com.afternote.core.model.user.Receiver +import com.afternote.feature.setting.domain.NotificationAnniversary +import com.afternote.feature.setting.domain.NotificationDelegate +import com.afternote.feature.setting.domain.NotificationPreferenceRepository +import com.afternote.feature.setting.domain.NotificationPreferences +import com.afternote.feature.setting.presentation.notification.anniversary.AnniversaryIntent +import com.afternote.feature.setting.presentation.notification.anniversary.AnniversaryViewModel +import com.afternote.feature.setting.presentation.notification.delegate.DelegateIntent +import com.afternote.feature.setting.presentation.notification.delegate.DelegateViewModel +import com.afternote.feature.setting.presentation.notification.preference.NotificationPreferenceIntent +import com.afternote.feature.setting.presentation.notification.preference.NotificationPreferenceViewModel +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.advanceUntilIdle +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.test.setMain +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import java.time.DayOfWeek +import java.time.LocalTime + +/** 서버 알림 설정 세 화면(기록 알림·대리인·기념일)의 ViewModel 회귀 기준 (#2321). */ +@OptIn(ExperimentalCoroutinesApi::class) +class NotificationPreferenceSettingsTest { + private val dispatcher = StandardTestDispatcher() + + @Before + fun setUp() { + Dispatchers.setMain(dispatcher) + } + + @After + fun tearDown() { + Dispatchers.resetMain() + } + + @Test + fun `기록 알림 - 고친 값을 저장 한 번에 보낸다`() = + runTest(dispatcher) { + val repository = FakeNotificationPreferenceRepository() + val viewModel = NotificationPreferenceViewModel(repository) + advanceUntilIdle() + + viewModel.onIntent(NotificationPreferenceIntent.ChangeTime(LocalTime.of(21, 30, 15))) + viewModel.onIntent(NotificationPreferenceIntent.ToggleWeekday(DayOfWeek.MONDAY)) + viewModel.onIntent(NotificationPreferenceIntent.ChangeWeeklyGoal(9)) + assertTrue(repository.savedPreferences.isEmpty()) + + viewModel.onIntent(NotificationPreferenceIntent.Save) + advanceUntilIdle() + + val saved = repository.savedPreferences.single() + assertEquals(LocalTime.of(21, 30), saved.time) + assertEquals(DayOfWeek.entries.toSet() - DayOfWeek.MONDAY, saved.weekdays) + assertEquals(7, saved.weeklyGoal) + assertTrue(viewModel.uiState.value.isSaved) + } + + @Test + fun `기록 알림 - 요일을 모두 끄면 보내지 않고 이유를 알린다`() = + runTest(dispatcher) { + val repository = FakeNotificationPreferenceRepository() + val viewModel = NotificationPreferenceViewModel(repository) + advanceUntilIdle() + + DayOfWeek.entries.forEach { viewModel.onIntent(NotificationPreferenceIntent.ToggleWeekday(it)) } + viewModel.onIntent(NotificationPreferenceIntent.Save) + advanceUntilIdle() + + assertTrue(repository.savedPreferences.isEmpty()) + assertNotNull(viewModel.uiState.value.errorMessage) + } + + @Test + fun `기록 알림 - 불러오기 전에는 기본값을 그리지 않는다`() = + runTest(dispatcher) { + val repository = FakeNotificationPreferenceRepository(loadFails = true) + val viewModel = NotificationPreferenceViewModel(repository) + advanceUntilIdle() + + assertNull(viewModel.uiState.value.form) + assertTrue(viewModel.uiState.value.loadFailed) + } + + @Test + fun `대리인 - 연락처 숫자만 남겨 저장하고 해제한다`() = + runTest(dispatcher) { + val repository = FakeNotificationPreferenceRepository() + val viewModel = DelegateViewModel(repository) + advanceUntilIdle() + + viewModel.onIntent(DelegateIntent.Save(" 김대리 ", "010-1234-5678")) + advanceUntilIdle() + assertEquals(NotificationDelegate("김대리", "01012345678"), repository.delegate) + assertEquals(NotificationDelegate("김대리", "01012345678"), viewModel.uiState.value.delegate) + + viewModel.onIntent(DelegateIntent.Remove) + advanceUntilIdle() + assertNull(repository.delegate) + assertNull(viewModel.uiState.value.delegate) + } + + @Test + fun `대리인 - 이름이나 연락처가 비면 보내지 않는다`() = + runTest(dispatcher) { + val repository = FakeNotificationPreferenceRepository() + val viewModel = DelegateViewModel(repository) + advanceUntilIdle() + + viewModel.onIntent(DelegateIntent.Save(" ", "01012345678")) + viewModel.onIntent(DelegateIntent.ConsumeError) + viewModel.onIntent(DelegateIntent.Save("김대리", "")) + advanceUntilIdle() + + assertNull(repository.delegate) + assertNotNull(viewModel.uiState.value.errorMessage) + } + + @Test + fun `기념일 - 수신인 이름을 붙여 날짜순으로 보이고 추가·삭제가 반영된다`() = + runTest(dispatcher) { + val repository = + FakeNotificationPreferenceRepository( + anniversaries = mutableListOf(NotificationAnniversary(id = 1, receiverId = 10, month = 5, day = 8)), + ) + val receivers = FakeUserReceiverRepository(receivers = listOf(Receiver(10, "엄마", "MOTHER"), Receiver(11, "아빠", "FATHER"))) + val viewModel = AnniversaryViewModel(repository, receivers) + advanceUntilIdle() + + assertEquals( + listOf("엄마"), + viewModel.uiState.value.items + .map { it.receiverName }, + ) + + viewModel.onIntent(AnniversaryIntent.Add(receiverId = 11, month = 2, day = 29)) + advanceUntilIdle() + assertEquals( + listOf("아빠", "엄마"), + viewModel.uiState.value.items + .map { it.receiverName }, + ) + + viewModel.onIntent(AnniversaryIntent.Delete(1)) + advanceUntilIdle() + assertEquals( + listOf("아빠"), + viewModel.uiState.value.items + .map { it.receiverName }, + ) + } + + private class FakeNotificationPreferenceRepository( + private val loadFails: Boolean = false, + val anniversaries: MutableList = mutableListOf(), + ) : NotificationPreferenceRepository { + val savedPreferences = mutableListOf() + var delegate: NotificationDelegate? = null + + override suspend fun getPreferences(): Result = + if (loadFails) { + Result.failure(IllegalStateException("offline")) + } else { + Result.success(NotificationPreferences(true, LocalTime.of(18, 0), DayOfWeek.entries.toSet(), 3)) + } + + override suspend fun updatePreferences(preferences: NotificationPreferences): Result { + savedPreferences += preferences + return Result.success(preferences) + } + + override suspend fun getDelegate(): Result = Result.success(delegate) + + override suspend fun updateDelegate(delegate: NotificationDelegate): Result { + this.delegate = delegate + return Result.success(Unit) + } + + override suspend fun deleteDelegate(): Result { + delegate = null + return Result.success(Unit) + } + + override suspend fun getAnniversaries(): Result> = Result.success(anniversaries.toList()) + + override suspend fun addAnniversary( + receiverId: Long, + month: Int, + day: Int, + ): Result { + val anniversary = NotificationAnniversary(id = (anniversaries.maxOfOrNull { it.id } ?: 0) + 1, receiverId, month, day) + anniversaries += anniversary + return Result.success(anniversary) + } + + override suspend fun deleteAnniversary(anniversaryId: Long): Result { + anniversaries.removeAll { it.id == anniversaryId } + return Result.success(Unit) + } + } +} diff --git a/feature/setting/presentation/src/test/kotlin/com/afternote/feature/setting/presentation/notification/NotificationSettingSignalTest.kt b/feature/setting/presentation/src/test/kotlin/com/afternote/feature/setting/presentation/notification/NotificationSettingSignalTest.kt index 69d87b2b6e..4a40a52020 100644 --- a/feature/setting/presentation/src/test/kotlin/com/afternote/feature/setting/presentation/notification/NotificationSettingSignalTest.kt +++ b/feature/setting/presentation/src/test/kotlin/com/afternote/feature/setting/presentation/notification/NotificationSettingSignalTest.kt @@ -142,6 +142,9 @@ class NotificationSettingSignalTest { NotificationSettingScreen( onBack = {}, onPushNotificationClick = {}, + onNotificationPreferenceClick = {}, + onDelegateClick = {}, + onAnniversaryClick = {}, viewModel = viewModel, ) } diff --git a/feature/setting/presentation/src/test/kotlin/com/afternote/feature/setting/presentation/passkey/PassKeyMakingApi29Test.kt b/feature/setting/presentation/src/test/kotlin/com/afternote/feature/setting/presentation/passkey/PassKeyMakingApi29Test.kt index 013ea9a8ef..7ba26d7f96 100644 --- a/feature/setting/presentation/src/test/kotlin/com/afternote/feature/setting/presentation/passkey/PassKeyMakingApi29Test.kt +++ b/feature/setting/presentation/src/test/kotlin/com/afternote/feature/setting/presentation/passkey/PassKeyMakingApi29Test.kt @@ -27,12 +27,14 @@ import com.afternote.core.common.reporting.ErrorReporter import com.afternote.core.domain.push.DevicePushTargetProvider import com.afternote.core.domain.repository.UserProfileCacheRepository import com.afternote.core.ui.theme.AfternoteTheme +import com.afternote.feature.setting.domain.NotificationPreferenceRepository import com.afternote.feature.setting.domain.Passkey import com.afternote.feature.setting.domain.PasskeyRepository import com.afternote.feature.setting.domain.SettingAccountRepository import com.afternote.feature.setting.domain.SettingNotificationRepository import com.afternote.feature.setting.domain.testing.FakeSettingAccountRepository import com.afternote.feature.setting.domain.testing.FakeSettingNotificationRepository +import com.afternote.feature.setting.domain.testing.StrictNotificationPreferenceRepository import dagger.hilt.android.AndroidEntryPoint import dagger.hilt.android.testing.BindValue import dagger.hilt.android.testing.HiltAndroidRule @@ -104,12 +106,17 @@ class PassKeyMakingApi29Test { @BindValue val notificationRepository: SettingNotificationRepository = FakeSettingNotificationRepository.strict() + @BindValue + val notificationPreferenceRepository: NotificationPreferenceRepository = StrictNotificationPreferenceRepository + @BindValue val pushTargetProvider: DevicePushTargetProvider = object : DevicePushTargetProvider { override suspend fun currentTargetId(): String? = error("생체 인증 오류 경로는 푸시 대상을 조회하지 않는다") override suspend fun existingTargetId(): String? = error("생체 인증 오류 경로는 푸시 대상을 조회하지 않는다") + + override suspend fun resetTargetId(): String? = error("생체 인증 오류 경로는 푸시 대상을 조회하지 않는다") } @BindValue diff --git a/feature/timeletter/presentation/src/main/kotlin/com/afternote/feature/timeletter/presentation/navigation/TimeLetterRoute.kt b/feature/timeletter/presentation/src/main/kotlin/com/afternote/feature/timeletter/presentation/navigation/TimeLetterRoute.kt index 8de9e0e9b1..3aefb0c5ab 100644 --- a/feature/timeletter/presentation/src/main/kotlin/com/afternote/feature/timeletter/presentation/navigation/TimeLetterRoute.kt +++ b/feature/timeletter/presentation/src/main/kotlin/com/afternote/feature/timeletter/presentation/navigation/TimeLetterRoute.kt @@ -6,9 +6,16 @@ sealed interface TimeLetterRoute { @Serializable data object TimeLetterHomeRoute : TimeLetterRoute + /** + * 편지 작성·수정 화면. + * + * [timeLetterId] 가 있으면 그 편지를 고친다. [prefillReceiverId] 는 새 편지의 수신인을 미리 고른다 — + * 기념일 알림(「오늘은 ○○님 생신이에요」)이 그 수신인 앞으로 바로 쓰게 연다 (#2321). + */ @Serializable data class TimeLetterWriteRoute( val timeLetterId: Long? = null, + val prefillReceiverId: Long? = null, ) : TimeLetterRoute @Serializable diff --git a/feature/timeletter/presentation/src/main/kotlin/com/afternote/feature/timeletter/presentation/viewmodel/TimeLetterWriteViewModel.kt b/feature/timeletter/presentation/src/main/kotlin/com/afternote/feature/timeletter/presentation/viewmodel/TimeLetterWriteViewModel.kt index 30fd000bf8..1ca98ac8b5 100644 --- a/feature/timeletter/presentation/src/main/kotlin/com/afternote/feature/timeletter/presentation/viewmodel/TimeLetterWriteViewModel.kt +++ b/feature/timeletter/presentation/src/main/kotlin/com/afternote/feature/timeletter/presentation/viewmodel/TimeLetterWriteViewModel.kt @@ -46,8 +46,8 @@ class TimeLetterWriteViewModel private val voiceRecorderRepository: VoiceRecorderRepository, private val savedStateHandle: SavedStateHandle, ) : ViewModel() { - private val editingTimeLetterId = - savedStateHandle.toRoute().timeLetterId + private val route = savedStateHandle.toRoute() + private val editingTimeLetterId = route.timeLetterId private val _uiState = MutableStateFlow( @@ -76,6 +76,11 @@ class TimeLetterWriteViewModel .getOrElse { emptyList() } .associate { it.receiverId to it.name } editingTimeLetterId?.let { loadEditingTimeLetter(it) } + // 이름 표를 받은 뒤에 고른다 — 먼저 고르면 칩에 이름이 비어 보인다. 이미 고른 수신인이 있으면 + // (화면 복원 뒤 사용자가 바꾼 값) 덮지 않는다. + route.prefillReceiverId + ?.takeIf { editingTimeLetterId == null && _uiState.value.recipientIds.isEmpty() } + ?.let { setRecipients(listOf(it)) } } loadDraftCount() observeRecipientResult() diff --git a/konsist/src/test/kotlin/com/afternote/konsist/DailyNotificationScheduleKonsistTest.kt b/konsist/src/test/kotlin/com/afternote/konsist/DailyNotificationScheduleKonsistTest.kt deleted file mode 100644 index b77c359e9e..0000000000 --- a/konsist/src/test/kotlin/com/afternote/konsist/DailyNotificationScheduleKonsistTest.kt +++ /dev/null @@ -1,90 +0,0 @@ -package com.afternote.konsist - -import com.lemonappdev.konsist.api.declaration.KoFileDeclaration -import org.junit.Test - -/** - * 데일리 알림 예약은 로그인 관찰자 한 곳에서만 한다 (#2146). - * - * 데일리 알림 문구는 계정의 기록을 재촉한다. 세션을 보지 않는 자리에서 예약을 넣으면 로그인하지 않은 - * 기기에도 매일 알림이 뜬다. #2146 이 그 경우였다. App Startup Initializer 가 기동마다 예약했고, - * Initializer 는 Hilt 에 닿지 못해 세션을 볼 수 없었다. - * - * 지금은 `DailyNotificationScheduleSynchronizer` 가 로그인 상태를 보고 예약과 취소를 함께 맡는다. - * 다른 자리에서 예약을 넣으면 그 관찰자의 취소와 어긋나고, 로그아웃한 기기에 예약이 다시 생긴다. - * - * 관찰자를 `GlobalApplication` 이 시작하는지도 본다. 시작 줄을 지워도 컴파일은 통과하고, 그러면 - * 로그인한 사용자도 알림을 못 받는다. - */ -class DailyNotificationScheduleKonsistTest { - @Test - fun `데일리 알림 예약은 로그인 관찰자만 부른다`() { - val callers = - AfternoteKonsistScope.productionFiles - .filter { SCHEDULE_REFERENCE.containsMatchIn(it.text.withoutComments()) } - .map { it.normalizedProjectPath() } - .toSet() - - check(OBSERVER_PATH in callers) { - "$OBSERVER_PATH 에서 scheduleDailyNotification 호출을 못 찾았다. 관찰자를 옮기거나 이름을 바꿨으면 " + - "이 가드를 함께 고칠 것. 못 찾은 채 초록이면 이 가드는 아무것도 안 본 것이다." - } - - val violations = (callers - OBSERVER_PATH).sorted() - check(violations.isEmpty()) { - buildString { - appendLine("로그인 관찰자 밖에서 데일리 알림을 예약한다 (${violations.size}건).") - appendLine("세션을 보지 않고 예약하면 로그인하지 않은 기기에도 매일 알림이 뜬다 (#2146).") - appendLine() - violations.forEach { appendLine(" $it") } - appendLine() - appendLine("예약·취소는 $OBSERVER_PATH 가 로그인 상태를 보고 한다.") - } - } - } - - @Test - fun `GlobalApplication 이 데일리 알림 관찰자를 시작한다`() { - val source = singleFile(APPLICATION_PATH).text.withoutComments() - val property = OBSERVER_PROPERTY.find(source)?.groupValues?.get(1) - - check(property != null) { - "$APPLICATION_PATH 에 $OBSERVER_CLASS 주입 필드가 없다. 관찰자를 시작하지 않으면 로그인한 사용자도 " + - "데일리 알림을 못 받는다 (#2146)." - } - check(Regex("""\b${Regex.escape(property)}\s*\.\s*observeLogin\s*\(""").containsMatchIn(source)) { - "$APPLICATION_PATH 가 $property.observeLogin() 을 부르지 않는다. 주입만 하고 시작하지 않으면 " + - "예약도 취소도 일어나지 않는다 (#2146)." - } - } - - private fun singleFile(projectPath: String): KoFileDeclaration { - val candidates = AfternoteKonsistScope.files.filter { it.normalizedProjectPath() == projectPath } - - check(candidates.size == 1) { - "$projectPath 가 ${candidates.size}건 잡혔다. 파일이 옮겨졌거나 사본이 섞였다.\n" + - candidates.joinToString("\n") { " " + it.path } - } - return candidates.single() - } - - private fun String.withoutComments(): String = replace(BLOCK_COMMENT, " ").replace(LINE_COMMENT, " ") - - private fun KoFileDeclaration.normalizedProjectPath(): String = projectPath.replace('\\', '/').trimStart('/') - - private companion object { - const val OBSERVER_CLASS = "DailyNotificationScheduleSynchronizer" - const val OBSERVER_PATH = - "app/src/main/java/com/afternote/afternote_fe/notification/$OBSERVER_CLASS.kt" - const val APPLICATION_PATH = "app/src/main/java/com/afternote/afternote_fe/GlobalApplication.kt" - - /** 호출과 함수 참조(`::scheduleDailyNotification`)를 잡고, 선언(`fun scheduleDailyNotification`)은 뺀다. */ - val SCHEDULE_REFERENCE = Regex("""(?