diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index d377b664..8d50ddee 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -118,6 +118,13 @@ + + (ActivityGiftDetailBinding::inflate) { + private val viewModel: GiftDetailViewModel by viewModel() + private val cancelViewModel: GiftCancelViewModel by viewModel() + private var cancelDialog: V2ModalDialog? = null + private var hasChanged = false + private val timelineAdapter = GiftStatusTimelineAdapter() + private val trackingLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> + if (result.resultCode == Activity.RESULT_OK) { + markChanged() + val canceled = GiftCancelResult.fromIntent(result.data, intent.getStringExtra(EXTRA_APPLICATION_NO).orEmpty()) + if (canceled != null) viewModel.applyCancellation(canceled) else reload() + } + } + + override fun onCreate(savedInstanceState: Bundle?) { + hasChanged = savedInstanceState?.getBoolean(STATE_CHANGED) == true + super.onCreate(savedInstanceState) + if (hasChanged) setResult(Activity.RESULT_OK) + } + + override fun onSaveInstanceState(outState: Bundle) { + outState.putBoolean(STATE_CHANGED, hasChanged) + super.onSaveInstanceState(outState) + } + + override fun setupView() { + binding.btnBack.setOnClickListener { finish() } + binding.close.setOnClickListener { finish() } + binding.retry.setOnClickListener { viewModel.retry() } + binding.inquiry.setOnClickListener { viewModel.onInquiryClick() } + binding.undeliverableInquiry.setOnClickListener { viewModel.onInquiryClick() } + binding.timeline.layoutManager = GridLayoutManager(this, 4) + binding.timeline.adapter = timelineAdapter + binding.tracking.setOnClickListener { + trackingLauncher.launch(GiftTrackingActivity.newIntent(this, intent.getStringExtra(EXTRA_APPLICATION_NO).orEmpty())) + } + binding.cancel.setText(R.string.gift_cancel_title) + binding.cancel.setOnClickListener { showCancelDialog() } + observeCancellation() + observe() + viewModel.loadInitial(intent.getStringExtra(EXTRA_APPLICATION_NO).orEmpty()) + } + + private fun reload() = viewModel.retry() + + private fun showCancelDialog() { + val detail = (viewModel.state.value as? GiftDetailUiState.Content)?.detail ?: return + if (detail.direction != "SENT" || detail.status != "RECEIVED" || cancelDialog != null) return + cancelDialog = giftCancelDialog(detail.giftInfo.recipientCreatorNickname, onConfirm = { + (viewModel.state.value as? GiftDetailUiState.Content)?.detail?.let(cancelViewModel::cancelGift) + }, onExit = { cancelDialog = null }).also { it.show(screenWidth) } + } + + private fun observeCancellation() { + cancelViewModel.isSubmitting.observe(this) { submitting -> + cancelDialog?.dialogView?.tvConfirm?.isEnabled = !submitting + cancelDialog?.dialogView?.tvCancel?.isEnabled = !submitting + binding.cancel.isEnabled = !submitting + } + cancelViewModel.toastLiveData.observe(this) { toast -> + if (toast != null) { + cancelViewModel.consumeToast()?.let { + showToast(it.resId?.let(::getString) ?: it.message.orEmpty()) + } + } + } + cancelViewModel.cancelSuccessLiveData.observe(this) { response -> + if (response != null) { + cancelViewModel.consumeCancelSuccessEvent()?.let { + cancelDialog?.dismiss() + cancelDialog = null + viewModel.applyCancellation(it) + markChanged() + showToast(getString(R.string.gift_cancel_success)) + } + } + } + } + + override fun onDestroy() { + cancelDialog?.dismiss() + super.onDestroy() + } + + private fun observe() { + viewModel.state.observe(this, ::render) + viewModel.finishErrorLiveData.observe(this) { event -> + if (event != null) { + viewModel.consumeFinishError()?.let { error -> + showToast(error.resId?.let(::getString) ?: error.message.orEmpty()) + finish() + } + } + } + viewModel.inquiryLiveData.observe(this) { requested -> + if (requested) viewModel.consumeInquiryIntent()?.let(::startActivity) + } + } + + private fun render(state: GiftDetailUiState) { + binding.progress.isVisible = state == GiftDetailUiState.Loading + binding.error.isVisible = state is GiftDetailUiState.Error + binding.content.isVisible = state is GiftDetailUiState.Content || state is GiftDetailUiState.Canceled + binding.tracking.isVisible = GiftDetailPresenter.showsTrackingAction(state) + when (state) { + GiftDetailUiState.Loading -> Unit + is GiftDetailUiState.Error -> { + binding.errorMessage.text = state.message?.takeIf { it.isNotBlank() } + ?: getString(R.string.common_error_unknown) + } + is GiftDetailUiState.Content -> bind(GiftDetailPresenter.present(state.detail)) + is GiftDetailUiState.Canceled -> { + if (state.cancel != null) markChanged() + bind(GiftDetailPresenter.present(state.detail, state.cancel)) + } + } + } + + private fun markChanged() { + hasChanged = true + setResult(Activity.RESULT_OK) + } + + private fun bind(model: GiftDetailUiModel) { + val canceled = model.cancellation != null + val received = model.status == "RECEIVED" + val undeliverable = model.undeliverable != null + binding.header.setText(if (canceled) R.string.gift_detail_canceled_header else R.string.gift_detail_title) + if (received) binding.header.text = "" + binding.btnBack.isVisible = !received + binding.close.isVisible = received + binding.heroChip.bindText(model.hero.chip) + binding.heroChip.setTextColor( + getColor( + when { + canceled -> R.color.gray_400 + undeliverable -> R.color.red_400 + else -> R.color.soda_400 + } + ) + ) + binding.heroTitle.bindText(model.hero.title) + binding.heroBody.bindText(model.hero.body) + binding.heroIllustration.isVisible = model.showProgress + binding.timeline.isVisible = model.showProgress + timelineAdapter.submitList(model.progressSegments) + binding.cancel.isVisible = GiftDetailAction.CANCEL in model.actions + binding.inquiry.isVisible = !undeliverable && GiftDetailAction.INQUIRY in model.actions + binding.undeliverableInquiry.isVisible = undeliverable && GiftDetailAction.INQUIRY in model.actions + binding.normalSections.isVisible = !canceled + binding.canceledCompletion.root.isVisible = canceled + GiftInfoRows.bind(binding.giftInfo, giftInfoRows(model)) + binding.senderSection.isVisible = model.senderInfo != null + binding.mailboxSection.isVisible = model.mailbox != null + binding.recipientSection.isVisible = model.recipientAddress != null + bindAddress(binding.senderInfo, model.senderInfo) + bindAddress(binding.mailbox, model.mailbox) + bindAddress(binding.recipientAddress, model.recipientAddress) + binding.normalSections.removeView(binding.mailboxSection) + binding.normalSections.addView( + binding.mailboxSection, + if (received) 1 else binding.normalSections.indexOfChild(binding.giftInfo) + 1 + ) + binding.registrationGuidance.isVisible = received && model.mailbox != null + binding.sectionSeparator.isVisible = received || undeliverable || model.showProgress + binding.undeliverable.isVisible = undeliverable + binding.undeliverableReason.bindText(model.undeliverable?.title) + binding.undeliverableGuidance.bindText(model.undeliverable?.guidance) + GiftInfoRows.bind( + binding.canceledCompletion.details, + model.cancellationRows.map { + it.label to resolveGiftDetailText(it.value) + } + ) + } + + private fun giftInfoRows(model: GiftDetailUiModel): List> = with(model.giftInfo) { + listOf( + R.string.gift_detail_counterpart to counterpartNickname, + R.string.gift_send_size to sizeName, + R.string.gift_send_category to categoryName, + R.string.gift_detail_application_no to model.applicationNo, + R.string.gift_detail_paid_can to paidCan?.let { getString(R.string.gift_detail_can_amount, it) }, + R.string.gift_detail_tracking to tracking, + R.string.gift_detail_shipping_date to shippingRequestedDate, + R.string.gift_detail_inspection_date to inspectionDate, + R.string.gift_detail_delivered_date to deliveredDate, + R.string.gift_detail_canceled_date to canceledDate + ) + } + + private fun bindAddress(view: LinearLayout, address: GiftDetailAddress?) { + GiftInfoRows.bind( + view, + listOf( + R.string.gift_send_name to address?.name, + R.string.gift_send_phone to address?.phoneNumber, + R.string.gift_send_address to address?.address + ), + labelWidth = 72 + ) + } + + private fun TextView.bindText(value: GiftDetailText?) { + isVisible = value != null + text = value?.let(::resolveGiftDetailText) + } + + companion object { + const val EXTRA_APPLICATION_NO = "EXTRA_APPLICATION_NO" + private const val STATE_CHANGED = "STATE_CHANGED" + + fun newIntent(context: Context, applicationNo: String): Intent = + Intent(context, GiftDetailActivity::class.java).putExtra(EXTRA_APPLICATION_NO, applicationNo) + } +} + +internal fun Context.resolveGiftDetailText(text: GiftDetailText): String = when (text) { + is GiftDetailText.Raw -> text.value + is GiftDetailText.CanAmount -> getString(R.string.gift_detail_can_amount, text.amount) + is GiftDetailText.CancellationBody -> getString( + R.string.gift_detail_canceled_body, + text.creatorNickname?.takeIf { it.isNotBlank() } ?: getString(R.string.gift_detail_creator), + text.applicationNo + ) + is Key -> getString( + when (text) { + Key.RECEIVED_LABEL -> R.string.gift_detail_received_label + Key.RECEIVED_TITLE -> R.string.gift_detail_received_title + Key.RECEIVED_BODY -> R.string.gift_detail_received_body + Key.TRACKING_REGISTERED_LABEL -> R.string.gift_inbox_sent_confirmed + Key.TRACKING_REGISTERED_TITLE -> R.string.gift_detail_tracking_title + Key.ARRIVED_AT_MAILBOX_LABEL -> R.string.gift_inbox_arrived + Key.ARRIVED_AT_MAILBOX_TITLE -> R.string.gift_detail_arrived_title + Key.INSPECTION_COMPLETED_LABEL -> R.string.gift_detail_inspected_label + Key.INSPECTION_COMPLETED_TITLE -> R.string.gift_detail_inspected_title + Key.DELIVERED_LABEL -> R.string.gift_inbox_delivered + Key.DELIVERED_TITLE -> R.string.gift_detail_delivered_title + Key.UNDELIVERABLE_LABEL -> R.string.gift_inbox_undeliverable + Key.UNDELIVERABLE_TITLE -> R.string.gift_detail_undeliverable_title + Key.UNDELIVERABLE_BODY -> R.string.gift_detail_undeliverable_body + Key.CANCELED_LABEL -> R.string.gift_inbox_canceled + Key.CANCELED_TITLE -> R.string.gift_detail_canceled_title + Key.CANCELED_BODY -> R.string.gift_detail_canceled_body + Key.DISPOSAL_NON_RETURN_GUIDANCE -> R.string.gift_detail_disposal_guidance + } + ) +} diff --git a/app/src/main/java/kr/co/vividnext/sodalive/v2/gift/GiftTrackingActivity.kt b/app/src/main/java/kr/co/vividnext/sodalive/v2/gift/GiftTrackingActivity.kt new file mode 100644 index 00000000..7cbf2f64 --- /dev/null +++ b/app/src/main/java/kr/co/vividnext/sodalive/v2/gift/GiftTrackingActivity.kt @@ -0,0 +1,218 @@ +package kr.co.vividnext.sodalive.v2.gift + +import android.app.Activity +import android.content.Context +import android.content.Intent +import android.view.View +import android.widget.AdapterView +import androidx.core.content.ContextCompat +import androidx.core.view.WindowCompat +import androidx.core.view.isVisible +import androidx.core.widget.addTextChangedListener +import kr.co.vividnext.sodalive.R +import kr.co.vividnext.sodalive.base.BaseActivity +import kr.co.vividnext.sodalive.common.LoadingDialog +import kr.co.vividnext.sodalive.databinding.ActivityGiftTrackingBinding +import kr.co.vividnext.sodalive.v2.components.modal.V2ModalDialog +import kr.co.vividnext.sodalive.v2.gift.ui.GiftInfoRows +import org.koin.androidx.viewmodel.ext.android.viewModel + +class GiftTrackingActivity : BaseActivity(ActivityGiftTrackingBinding::inflate) { + private val viewModel: GiftTrackingViewModel by viewModel() + private val cancelViewModel: GiftCancelViewModel by viewModel() + private var cancelDialog: V2ModalDialog? = null + private val applicationNo: String by lazy { intent.getStringExtra(EXTRA_APPLICATION_NO).orEmpty() } + private var loadingDialog: LoadingDialog? = null + + override fun setupView() { + WindowCompat.getInsetsController(window, binding.root).apply { + isAppearanceLightStatusBars = false + isAppearanceLightNavigationBars = false + } + binding.btnBack.setOnClickListener { finish() } + binding.retry.setOnClickListener { viewModel.retry() } + binding.cancel.setText(R.string.gift_cancel_title) + binding.cancel.setOnClickListener { showCancelDialog() } + binding.courier.adapter = GiftCategoryAdapter( + this, + listOf(getString(R.string.gift_tracking_courier_hint)) + giftCourierCompanyNames + ).apply { setDropDownViewResource(R.layout.item_gift_send_category) } + binding.courier.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { + override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { + updateCtaState() + } + + override fun onNothingSelected(parent: AdapterView<*>?) { + updateCtaState() + } + } + binding.trackingNumber.addTextChangedListener { updateCtaState() } + binding.submit.setOnClickListener { + if (cancelViewModel.isSubmitting.value != true) { + viewModel.submitTracking(selectedCourier(), binding.trackingNumber.text.toString()) + } + } + observeCancellation() + observe() + viewModel.loadInitial(applicationNo) + } + + private fun showCancelDialog() { + val detail = viewModel.loadedDetail ?: return + if ( + detail.direction != "SENT" || detail.status != "RECEIVED" || cancelDialog != null || + viewModel.isSubmitting.value == true + ) { + return + } + cancelDialog = giftCancelDialog(detail.giftInfo.recipientCreatorNickname, onConfirm = { + viewModel.loadedDetail?.let(cancelViewModel::cancelGift) + }, onExit = { cancelDialog = null }).also { it.show(screenWidth) } + } + + private fun observeCancellation() { + cancelViewModel.isSubmitting.observe(this) { submitting -> + cancelDialog?.dialogView?.tvConfirm?.isEnabled = !submitting + cancelDialog?.dialogView?.tvCancel?.isEnabled = !submitting + updateCtaState() + } + cancelViewModel.toastLiveData.observe(this) { toast -> + if (toast != null) { + cancelViewModel.consumeToast()?.let { + showToast(it.resId?.let(::getString) ?: it.message.orEmpty()) + } + } + } + cancelViewModel.cancelSuccessLiveData.observe(this) { response -> + if (response != null) { + cancelViewModel.consumeCancelSuccessEvent()?.let { + cancelDialog?.dismiss() + cancelDialog = null + showToast(getString(R.string.gift_cancel_success)) + setResult(Activity.RESULT_OK, GiftCancelResult.toIntent(applicationNo, it)) + finish() + } + } + } + } + + private fun observe() { + viewModel.state.observe(this, ::render) + viewModel.isSubmitting.observe(this) { submitting -> + if (submitting) { + val dialog = loadingDialog ?: LoadingDialog(this, layoutInflater).also { loadingDialog = it } + dialog.show(screenWidth) + } else { + loadingDialog?.dismiss() + } + binding.courier.isEnabled = !submitting + binding.trackingNumber.isEnabled = !submitting + updateCtaState() + } + viewModel.toastLiveData.observe(this) { toast -> + if (toast != null) { + viewModel.consumeToast()?.let { showToast(it.resId?.let(::getString) ?: it.message.orEmpty()) } + } + } + viewModel.ineligibleLiveData.observe(this) { requested -> + if (requested && viewModel.consumeIneligibleEvent()) { + val detail = (viewModel.state.value as? GiftTrackingUiState.Content)?.detail + showToast( + getString( + if (detail != null && detail.mailbox == null) { + R.string.gift_tracking_missing_mailbox + } else { + R.string.gift_tracking_ineligible + } + ) + ) + finish() + } + } + viewModel.submitSuccessLiveData.observe(this) { success -> + if (success && viewModel.consumeSubmitSuccessEvent()) { + showToast(getString(R.string.gift_tracking_success)) + setResult(Activity.RESULT_OK, Intent().putExtra(EXTRA_APPLICATION_NO, applicationNo)) + finish() + } + } + } + + private fun render(state: GiftTrackingUiState) { + binding.progress.isVisible = state == GiftTrackingUiState.Loading + binding.error.isVisible = state is GiftTrackingUiState.Error + binding.content.isVisible = state is GiftTrackingUiState.Content + binding.actions.isVisible = state is GiftTrackingUiState.Content + when (state) { + GiftTrackingUiState.Loading -> Unit + is GiftTrackingUiState.Error -> binding.errorMessage.text = state.message?.takeIf { it.isNotBlank() } + ?: getString(R.string.common_error_unknown) + is GiftTrackingUiState.Content -> bind(state.detail) + } + updateCtaState() + } + + private fun bind(model: GiftTrackingUiModel) { + GiftInfoRows.bind( + binding.summary, + listOf( + R.string.gift_send_recipient to model.recipientCreatorNickname, + R.string.gift_detail_application_no to model.applicationNo, + R.string.gift_send_size to model.sizeName, + R.string.gift_send_category to model.categoryName, + R.string.gift_detail_paid_can to model.paidCan?.let { getString(R.string.gift_detail_can_amount, it) }, + R.string.gift_tracking_application_date to model.applicationDate + ) + ) + GiftInfoRows.bind( + binding.mailbox, + listOf( + R.string.gift_send_name to model.mailbox?.name, + R.string.gift_send_phone to model.mailbox?.phoneNumber, + R.string.gift_send_address to model.mailbox?.address + ), + labelWidth = 72 + ) + } + + private fun selectedCourier(): String? = giftCourierCompanyNames.getOrNull(binding.courier.selectedItemPosition - 1) + + private fun updateCtaState() { + val trackingNumber = binding.trackingNumber.text.toString() + val hasError = GiftTrackingPresenter.hasTrackingNumberError(trackingNumber) + binding.trackingNumberError.isVisible = hasError + binding.trackingNumber.setBackgroundResource( + if (hasError) R.drawable.bg_gift_send_input_error else R.drawable.bg_creator_channel_fantalk_reply + ) + val detail = viewModel.loadedDetail + val idle = viewModel.isSubmitting.value != true && cancelViewModel.isSubmitting.value != true + binding.cancel.isVisible = detail?.direction == "SENT" && detail.status == "RECEIVED" + binding.cancel.isEnabled = idle + binding.cancel.setTextColor(ContextCompat.getColor(this, if (idle) R.color.white else R.color.gray_500)) + val eligible = (viewModel.state.value as? GiftTrackingUiState.Content)?.detail?.isEligible == true + val enabled = eligible && idle && + GiftTrackingPresenter.isSubmitEnabled(selectedCourier(), trackingNumber) + binding.submit.isEnabled = enabled + binding.submit.setTextColor(ContextCompat.getColor(this, if (enabled) R.color.white else R.color.gray_500)) + binding.submit.setBackgroundResource( + if (enabled) { + R.drawable.bg_creator_channel_fantalk_write_send_enabled + } else { + R.drawable.bg_creator_channel_fantalk_write_send_disabled + } + ) + } + + override fun onDestroy() { + cancelDialog?.dismiss() + loadingDialog?.dismiss() + super.onDestroy() + } + + companion object { + const val EXTRA_APPLICATION_NO = GiftDetailActivity.EXTRA_APPLICATION_NO + + fun newIntent(context: Context, applicationNo: String): Intent = + Intent(context, GiftTrackingActivity::class.java).putExtra(EXTRA_APPLICATION_NO, applicationNo) + } +} diff --git a/app/src/test/java/kr/co/vividnext/sodalive/v2/gift/GiftNavigationTest.kt b/app/src/test/java/kr/co/vividnext/sodalive/v2/gift/GiftNavigationTest.kt new file mode 100644 index 00000000..787d68bd --- /dev/null +++ b/app/src/test/java/kr/co/vividnext/sodalive/v2/gift/GiftNavigationTest.kt @@ -0,0 +1,376 @@ +package kr.co.vividnext.sodalive.v2.gift + +import android.app.Activity +import android.app.Application +import android.content.Intent +import android.view.View +import androidx.lifecycle.ViewModelProvider +import androidx.test.core.app.ApplicationProvider +import io.reactivex.rxjava3.android.plugins.RxAndroidPlugins +import io.reactivex.rxjava3.core.Single +import io.reactivex.rxjava3.plugins.RxJavaPlugins +import io.reactivex.rxjava3.schedulers.Schedulers +import io.reactivex.rxjava3.subjects.SingleSubject +import kr.co.vividnext.sodalive.R +import kr.co.vividnext.sodalive.common.ApiResponse +import kr.co.vividnext.sodalive.common.SharedPreferenceManager +import kr.co.vividnext.sodalive.v2.gift.data.GiftApi +import kr.co.vividnext.sodalive.v2.gift.data.GiftCancelResponse +import kr.co.vividnext.sodalive.v2.gift.data.GiftAddressResponse +import kr.co.vividnext.sodalive.v2.gift.data.GiftDeliveryResponse +import kr.co.vividnext.sodalive.v2.gift.data.GiftDetailInfoResponse +import kr.co.vividnext.sodalive.v2.gift.data.GiftDetailResponse +import kr.co.vividnext.sodalive.v2.gift.data.GiftRepository +import kr.co.vividnext.sodalive.v2.gift.data.GiftTrackingRequest +import kr.co.vividnext.sodalive.v2.gift.data.GiftTrackingResponse +import org.junit.After +import org.junit.Before +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Assert.assertNull +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.Robolectric +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import org.robolectric.shadows.ShadowToast +import org.robolectric.shadows.ShadowDialog +import org.koin.core.context.startKoin +import org.koin.core.context.stopKoin +import org.koin.androidx.viewmodel.dsl.viewModel +import org.koin.dsl.module + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], application = Application::class) +class GiftNavigationTest { + private lateinit var api: NavigationFakeApi + + @Before + fun setUp() { + RxJavaPlugins.setIoSchedulerHandler { Schedulers.trampoline() } + RxAndroidPlugins.setInitMainThreadSchedulerHandler { Schedulers.trampoline() } + RxAndroidPlugins.setMainThreadSchedulerHandler { Schedulers.trampoline() } + SharedPreferenceManager.resetForTest() + SharedPreferenceManager.init(ApplicationProvider.getApplicationContext()) + api = NavigationFakeApi() + startKoin { + modules( + module { + viewModel { GiftDetailViewModel(GiftRepository(api)) } + viewModel { GiftTrackingViewModel(GiftRepository(api)) } + viewModel { GiftCancelViewModel(GiftRepository(api)) } + } + ) + } + } + + @After + fun tearDown() { + stopKoin() + RxJavaPlugins.reset() + RxAndroidPlugins.reset() + SharedPreferenceManager.resetForTest() + } + + @Test + fun `양쪽 취소 dialog는 실패를 유지하고 성공만 닫아 취소 결과와 목록 갱신을 전달한다`() { + listOf(false, true).forEach { tracking -> + api.cancelRequests.clear() + api.cancelResponse = SingleSubject.create() + val parent = Robolectric.buildActivity( + GiftDetailActivity::class.java, + GiftDetailActivity.newIntent(ApplicationProvider.getApplicationContext(), "cancel-gift") + ).setup() + val detail = parent.get() + var requestCode = 0 + val child = if (tracking) { + detail.binding.tracking.performClick() + val launched = shadowOf(detail).nextStartedActivityForResult + requestCode = launched.requestCode + Robolectric.buildActivity(GiftTrackingActivity::class.java, launched.intent).setup() + } else { + null + } + val activity = child?.get() ?: detail + activity.findViewById(R.id.cancel).performClick() + val exited = ShadowDialog.getLatestDialog() + assertTrue(exited != null && exited.isShowing) + assertTrue(api.cancelRequests.isEmpty()) + exited.findViewById(R.id.tv_cancel).performClick() + assertFalse(exited.isShowing) + assertTrue(api.cancelRequests.isEmpty()) + activity.findViewById(R.id.cancel).performClick() + val dialog = ShadowDialog.getLatestDialog() + val confirm = dialog.findViewById(R.id.tv_confirm) + confirm.performClick() + assertTrue(dialog.isShowing) + assertFalse(confirm.isEnabled) + assertEquals(listOf("cancel-gift"), api.cancelRequests) + api.cancelResponse.onSuccess(ApiResponse(false, null, "취소 실패")) + assertTrue(dialog.isShowing) + assertTrue(confirm.isEnabled) + assertEquals("취소 실패", ShadowToast.getTextOfLatestToast()) + assertNull(ViewModelProvider(activity)[GiftCancelViewModel::class.java].toastLiveData.value) + api.cancelResponse = SingleSubject.create() + confirm.performClick() + val cancel = GiftCancelResponse("cancel-gift", "CANCELED", "신청 취소", 77, "2026-10-02T00:00:00Z") + api.cancelResponse.onSuccess(ApiResponse(true, cancel, null)) + assertFalse(dialog.isShowing) + assertEquals(Activity.RESULT_OK, shadowOf(activity).resultCode) + val requestsBeforeResult = api.requests.size + if (child != null) { + assertTrue(activity.isFinishing) + val result = shadowOf(activity).resultIntent + assertEquals("cancel-gift", result.getStringExtra(GiftDetailActivity.EXTRA_APPLICATION_NO)) + assertEquals(cancel.canceledAt, result.getStringExtra("EXTRA_CANCELED_AT")) + assertEquals(77, result.getIntExtra("EXTRA_PRICE_CAN", -1)) + detail.activityResultRegistry.dispatchResult(requestCode, Activity.RESULT_OK, result) + child.pause().stop().destroy() + } + val state = ViewModelProvider(detail)[GiftDetailViewModel::class.java].state.value as GiftDetailUiState.Canceled + assertEquals(cancel, state.cancel) + assertEquals(requestsBeforeResult, api.requests.size) + assertFalse(detail.isFinishing) + val requestsBeforeRecreate = api.requests.size + val cancelRequestsBeforeRecreate = api.cancelRequests.toList() + val recreatedDetail = parent.recreate().get() + assertEquals(requestsBeforeRecreate, api.requests.size) + assertEquals(cancelRequestsBeforeRecreate, api.cancelRequests) + if (tracking) { + recreatedDetail.binding.btnBack.performClick() + } else { + recreatedDetail.onBackPressedDispatcher.onBackPressed() + } + assertTrue(recreatedDetail.isFinishing) + assertTrue(shouldRefreshGiftInbox(shadowOf(recreatedDetail).resultCode)) + parent.pause().stop().destroy() + } + } + + @Test + fun `상세 TRACKING 액션은 같은 신청번호만 전달한다`() { + val intent = GiftDetailActivity.newIntent(ApplicationProvider.getApplicationContext(), " gift-001/신청 ") + val controller = Robolectric.buildActivity(GiftDetailActivity::class.java, intent).setup() + val activity = controller.get() + activity.binding.tracking.performClick() + val launched = shadowOf(activity).nextStartedActivityForResult.intent + assertEquals(GiftTrackingActivity::class.java.name, launched.component?.className) + assertEquals(" gift-001/신청 ", launched.getStringExtra(GiftTrackingActivity.EXTRA_APPLICATION_NO)) + assertEquals(setOf(GiftTrackingActivity.EXTRA_APPLICATION_NO), launched.extras?.keySet()) + controller.pause().stop().destroy() + } + + @Test + fun `운송장 등록 성공은 같은 신청번호의 RESULT_OK로 종료한다`() { + val intent = GiftTrackingActivity.newIntent(ApplicationProvider.getApplicationContext(), " gift-001/신청 ") + val controller = Robolectric.buildActivity(GiftTrackingActivity::class.java, intent).setup() + val activity = controller.get() + activity.binding.courier.setSelection(1) + activity.binding.trackingNumber.setText("00123456789012") + shadowOf(android.os.Looper.getMainLooper()).idle() + activity.binding.submit.performClick() + assertTrue(activity.isFinishing) + assertEquals(activity.getString(R.string.gift_tracking_success), ShadowToast.getTextOfLatestToast()) + assertEquals(Activity.RESULT_OK, shadowOf(activity).resultCode) + val result = shadowOf(activity).resultIntent + assertEquals(" gift-001/신청 ", result.getStringExtra(GiftTrackingActivity.EXTRA_APPLICATION_NO)) + assertEquals(setOf(GiftTrackingActivity.EXTRA_APPLICATION_NO), result.extras?.keySet()) + assertEquals( + listOf(" gift-001/신청 " to GiftTrackingRequest(giftCourierCompanyNames.first(), "00123456789012")), + api.submissions + ) + controller.pause().stop().destroy() + } + + @Test + fun `운송장 RESULT_OK만 원래 신청번호의 상세를 재조회한다`() { + val intent = GiftDetailActivity.newIntent(ApplicationProvider.getApplicationContext(), "original-gift") + val controller = Robolectric.buildActivity(GiftDetailActivity::class.java, intent).setup() + val activity = controller.get() + listOf(Activity.RESULT_CANCELED, Activity.RESULT_FIRST_USER, Activity.RESULT_OK).forEach { code -> + activity.binding.tracking.performClick() + val launched = shadowOf(activity).nextStartedActivityForResult + activity.activityResultRegistry.dispatchResult( + launched.requestCode, + code, + Intent().putExtra(GiftTrackingActivity.EXTRA_APPLICATION_NO, "other-gift") + ) + assertEquals(if (code == Activity.RESULT_OK) 2 else 1, api.requests.size) + } + assertEquals(listOf("original-gift", "original-gift"), api.requests) + assertEquals(Activity.RESULT_OK, shadowOf(activity).resultCode) + controller.pause().stop().destroy() + } + + @Test + fun `운송장 성공 후 재생성한 상세는 양쪽 뒤로가기에서 부모 성공 결과를 유지한다`() { + listOf(true, false).forEach { toolbarBack -> + val controller = Robolectric.buildActivity( + GiftDetailActivity::class.java, + GiftDetailActivity.newIntent(ApplicationProvider.getApplicationContext(), "tracking-gift") + ).setup() + val activity = controller.get() + activity.binding.tracking.performClick() + val launched = shadowOf(activity).nextStartedActivityForResult + activity.activityResultRegistry.dispatchResult( + launched.requestCode, + Activity.RESULT_OK, + Intent().putExtra(GiftTrackingActivity.EXTRA_APPLICATION_NO, "tracking-gift") + ) + val requestsBeforeRecreate = api.requests.size + + val recreatedDetail = controller.recreate().get() + + assertEquals(requestsBeforeRecreate, api.requests.size) + if (toolbarBack) { + recreatedDetail.binding.btnBack.performClick() + } else { + recreatedDetail.onBackPressedDispatcher.onBackPressed() + } + assertTrue(recreatedDetail.isFinishing) + assertEquals(Activity.RESULT_OK, shadowOf(recreatedDetail).resultCode) + controller.pause().stop().destroy() + } + } + + @Test + fun `변경 없는 일반 상세는 재생성 뒤에도 성공 결과나 추가 요청을 만들지 않는다`() { + val controller = Robolectric.buildActivity( + GiftDetailActivity::class.java, + GiftDetailActivity.newIntent(ApplicationProvider.getApplicationContext(), "unchanged-gift") + ).setup() + val requestsBeforeRecreate = api.requests.size + + val recreatedDetail = controller.recreate().get() + + assertEquals(requestsBeforeRecreate, api.requests.size) + assertTrue(api.cancelRequests.isEmpty()) + assertTrue(api.submissions.isEmpty()) + recreatedDetail.onBackPressedDispatcher.onBackPressed() + assertTrue(recreatedDetail.isFinishing) + assertEquals(Activity.RESULT_CANCELED, shadowOf(recreatedDetail).resultCode) + controller.pause().stop().destroy() + } + + @Test + fun `서버 CANCELED 조회만으로는 재생성 뒤에도 성공 결과를 만들지 않는다`() { + api.detailStatus = "CANCELED" + val controller = Robolectric.buildActivity( + GiftDetailActivity::class.java, + GiftDetailActivity.newIntent(ApplicationProvider.getApplicationContext(), "canceled-gift") + ).setup() + val requestsBeforeRecreate = api.requests.size + + val recreatedDetail = controller.recreate().get() + + assertEquals(requestsBeforeRecreate, api.requests.size) + assertTrue(api.cancelRequests.isEmpty()) + assertTrue(api.submissions.isEmpty()) + recreatedDetail.binding.btnBack.performClick() + assertTrue(recreatedDetail.isFinishing) + assertEquals(Activity.RESULT_CANCELED, shadowOf(recreatedDetail).resultCode) + controller.pause().stop().destroy() + } + + @Test + fun `운송장 화면의 일반 뒤로가기는 성공 결과나 제출을 만들지 않는다`() { + val intent = GiftTrackingActivity.newIntent(ApplicationProvider.getApplicationContext(), "test-gift") + listOf(true, false).forEach { toolbarBack -> + val controller = Robolectric.buildActivity(GiftTrackingActivity::class.java, intent).setup() + val activity = controller.get() + if (toolbarBack) { + activity.binding.btnBack.performClick() + } else { + activity.onBackPressedDispatcher.onBackPressed() + } + assertTrue(activity.isFinishing) + assertEquals(Activity.RESULT_CANCELED, shadowOf(activity).resultCode) + assertNull(shadowOf(activity).resultIntent) + controller.pause().stop().destroy() + } + assertTrue(api.submissions.isEmpty()) + } + + @Test + fun `잘못된 진입과 사서함 없는 신청은 오류 후 성공 결과 없이 종료한다`() { + listOf("", "missing-mailbox").forEach { applicationNo -> + val intent = GiftTrackingActivity.newIntent(ApplicationProvider.getApplicationContext(), applicationNo) + val controller = Robolectric.buildActivity(GiftTrackingActivity::class.java, intent).setup() + val activity = controller.get() + assertTrue(activity.isFinishing) + assertEquals(Activity.RESULT_CANCELED, shadowOf(activity).resultCode) + assertNull(shadowOf(activity).resultIntent) + val error = if (applicationNo.isEmpty()) R.string.gift_tracking_ineligible else R.string.gift_tracking_missing_mailbox + assertEquals(activity.getString(error), ShadowToast.getTextOfLatestToast()) + controller.pause().stop().destroy() + } + assertEquals(listOf("missing-mailbox"), api.requests) + assertTrue(api.submissions.isEmpty()) + } + + @Test + fun `상세에서 RESULT_OK로 돌아온 경우만 목록을 갱신한다`() = assertTrue(shouldRefreshGiftInbox(Activity.RESULT_OK)) + + @Test + fun `상세에서 취소하거나 다른 결과로 돌아오면 목록을 갱신하지 않는다`() { + assertFalse(shouldRefreshGiftInbox(Activity.RESULT_CANCELED)) + assertFalse(shouldRefreshGiftInbox(Activity.RESULT_FIRST_USER)) + } + + @Test + fun `상세 Intent는 신청번호만 원본 그대로 전달한다`() { + val applicationNo = " gift-001/신청 " + val intent = GiftDetailActivity.newIntent(ApplicationProvider.getApplicationContext(), applicationNo) + assertEquals(GiftDetailActivity::class.java.name, intent.component?.className) + assertEquals(applicationNo, intent.getStringExtra(GiftDetailActivity.EXTRA_APPLICATION_NO)) + assertEquals(setOf(GiftDetailActivity.EXTRA_APPLICATION_NO), intent.extras?.keySet()) + } + private class NavigationFakeApi : GiftApi by InboxFakeApi() { + val cancelRequests = mutableListOf() + var cancelResponse = SingleSubject.create>() + var detailStatus = "RECEIVED" + var nextDetailResponse: Single>? = null + override fun cancelGift(applicationNo: String, authHeader: String): Single> = + cancelResponse.also { cancelRequests.add(applicationNo) } + val requests = mutableListOf() + val submissions = mutableListOf>() + override fun getGiftDetail(applicationNo: String, authHeader: String): Single> { + requests.add(applicationNo) + return nextDetailResponse?.also { nextDetailResponse = null } ?: Single.just( + ApiResponse( + true, + GiftDetailResponse( + applicationNo, "SENT", detailStatus, "접수 완료", + GiftDetailInfoResponse("테스트", null, "소형", "도서", applicationNo, 100, null, null), + null, null, + if (applicationNo == "missing-mailbox") null else GiftAddressResponse("테스트 사서함", "000", "테스트 주소"), + true, false, null, GiftDeliveryResponse(null, null, null), emptyList() + ), + null + ) + ) + } + override fun registerGiftTracking( + applicationNo: String, + request: GiftTrackingRequest, + authHeader: String + ): Single> = + Single.just( + ApiResponse( + true, + GiftTrackingResponse( + applicationNo, + "TRACKING_REGISTERED", + "발송 확인", + request.courierCompanyName, + request.trackingNumber, + "2026-10-02T00:00:00Z", + "2026-10-09T00:00:00Z" + ), + null + ) + ).also { submissions.add(applicationNo to request) } + } +}