From e6afd06b085a03ce6e42b6926f309c45ff5d06f3 Mon Sep 17 00:00:00 2001 From: 915dbfl Date: Mon, 16 Oct 2023 15:22:55 +0900 Subject: [PATCH] feat: move checking storeId logic(mainActivity -> homeFragment) --- .../java/org/swm/att/home/MainActivity.kt | 57 +++-------- .../java/org/swm/att/home/MainViewModel.kt | 96 ------------------- .../org/swm/att/home/home/HomeFragment.kt | 47 ++++++++- .../org/swm/att/home/home/HomeViewModel.kt | 93 +++++++++++++++++- .../org/swm/att/home/recipe/RecipeFragment.kt | 1 + .../swm/att/home/recipe/RecipeViewModel.kt | 5 +- 6 files changed, 154 insertions(+), 145 deletions(-) diff --git a/feature/main/src/main/java/org/swm/att/home/MainActivity.kt b/feature/main/src/main/java/org/swm/att/home/MainActivity.kt index c79699f0..db43807e 100644 --- a/feature/main/src/main/java/org/swm/att/home/MainActivity.kt +++ b/feature/main/src/main/java/org/swm/att/home/MainActivity.kt @@ -3,19 +3,14 @@ package org.swm.att.home import android.content.Intent import android.os.Bundle import android.widget.CheckBox -import android.widget.Toast import androidx.activity.viewModels -import androidx.lifecycle.Lifecycle -import androidx.lifecycle.lifecycleScope -import androidx.lifecycle.repeatOnLifecycle import androidx.navigation.NavController import androidx.navigation.fragment.NavHostFragment import dagger.hilt.android.AndroidEntryPoint -import kotlinx.coroutines.launch import org.swm.att.common_ui.presenter.base.BaseActivity -import org.swm.att.common_ui.state.UiState import org.swm.att.home.databinding.ActivityMainBinding import org.swm.att.home.home.HomeFragmentDirections +import org.swm.att.home.util.alarm.AlarmManager import java.text.SimpleDateFormat import java.util.Date import java.util.Locale @@ -27,23 +22,16 @@ class MainActivity: BaseActivity(R.layout.activity_main) { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) + //TODO: 로그인 과정 추가되면 수정 //checkRefreshToken() - //TODO: 회원가입 화면이 나오기 전까지 임시 accessToken, refreshToken 사용 - checkStoreId() - setPreorderAlarm() + setNavController() setBindingData() setObserver() - setNavController() } - // private fun checkRefreshToken() { // mainViewModel.checkRefreshToken() // } - private fun checkStoreId() { - mainViewModel.checkStoreId() - } - private fun setNavController() { val navHost = supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment @@ -58,14 +46,14 @@ class MainActivity: BaseActivity(R.layout.activity_main) { } private fun setObserver() { - mainViewModel.refreshExist.observe(this) { exist -> - if (exist == false) { - // 로그인 및 회원가입으로 화면 전환 - } else { - // storeId 확인 - mainViewModel.checkStoreId() - } - } +// mainViewModel.refreshExist.observe(this) { exist -> +// if (exist == false) { +// // 로그인 및 회원가입으로 화면 전환 +// } else { +// // storeId 확인 +// mainViewModel.checkStoreId() +// } +// } mainViewModel.selectedScreen.observe(this) { destination -> mainViewModel.isGlobalAction.value?.let { @@ -75,28 +63,11 @@ class MainActivity: BaseActivity(R.layout.activity_main) { } else { mainViewModel.resetIsGlobalAction() } - if (mainViewModel.isDestinationDiff(destination)) { changeNavDestination() } } } - - lifecycleScope.launch { - repeatOnLifecycle(Lifecycle.State.STARTED) { - mainViewModel.registerStoreState.collect { uiState -> - when(uiState) { - is UiState.Success -> { - uiState.data?.let { - mainViewModel.setStoreId(it.storeId) - } - } - is UiState.Loading -> {/* nothing */} - is UiState.Error -> { Toast.makeText(this@MainActivity, uiState.errorMsg, Toast.LENGTH_SHORT).show() } - } - } - } - } } private fun changeNavDestination() { @@ -108,12 +79,8 @@ class MainActivity: BaseActivity(R.layout.activity_main) { } } - private fun setPreorderAlarm() { - mainViewModel.getTodayPreorder() - } - override fun onDestroy() { - mainViewModel.cancelAllPreorderAlarm() + AlarmManager.cancelAllAlarm(this) super.onDestroy() } diff --git a/feature/main/src/main/java/org/swm/att/home/MainViewModel.kt b/feature/main/src/main/java/org/swm/att/home/MainViewModel.kt index d28dd39b..74d3687c 100644 --- a/feature/main/src/main/java/org/swm/att/home/MainViewModel.kt +++ b/feature/main/src/main/java/org/swm/att/home/MainViewModel.kt @@ -1,38 +1,22 @@ package org.swm.att.home -import android.content.Context import android.util.Log import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel -import dagger.hilt.android.qualifiers.ApplicationContext -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.launch import org.json.JSONObject import org.swm.att.common_ui.presenter.base.BaseViewModel -import org.swm.att.common_ui.state.UiState -import org.swm.att.common_ui.util.Formatter import org.swm.att.common_ui.util.JWTUtils import org.swm.att.common_ui.util.JWTUtils.unixTimeToDateTime -import org.swm.att.common_ui.util.getUTCDateTime -import org.swm.att.domain.entity.HttpResponseException -import org.swm.att.domain.entity.request.StoreVO -import org.swm.att.domain.entity.response.PreorderVO -import org.swm.att.domain.entity.response.StoreIdVO -import org.swm.att.domain.repository.AttOrderRepository import org.swm.att.domain.repository.AttPosUserRepository import org.swm.att.home.constant.NavDestinationType -import org.swm.att.home.util.alarm.AlarmManager -import java.util.Calendar import javax.inject.Inject @HiltViewModel class MainViewModel @Inject constructor( private val attPosUserRepository: AttPosUserRepository, - private val attOrderRepository: AttOrderRepository, - @ApplicationContext private val context: Context ) : BaseViewModel() { private val _refreshExist = MutableLiveData() val refreshExist: LiveData = _refreshExist @@ -43,14 +27,6 @@ class MainViewModel @Inject constructor( private val _isGlobalAction = MutableLiveData(false) val isGlobalAction: LiveData = _isGlobalAction - private val todayPreorderList = arrayListOf() - private var page = 1 - - private val _storeIdExist = MutableLiveData() - val storeIdExist: LiveData = _storeIdExist - private val _registerStoreState = MutableStateFlow>(UiState.Loading) - val registerStoreState: StateFlow> = _registerStoreState - fun checkRefreshToken() { viewModelScope.launch { val curRefreshToken = attPosUserRepository.getRefreshToken() @@ -67,39 +43,6 @@ class MainViewModel @Inject constructor( } } - fun checkStoreId() { - viewModelScope.launch(attExceptionHandler) { - val storeId = attPosUserRepository.getStoreId() - Log.d("MainViewModel", "checkStoreId: $storeId") - if (storeId == -1) { - // TODO 새로운 가게 등록 화면으로 전환 -> _storeIdExist 활용 - // 임시 token을 활용해 가게 바로 등록 - attPosUserRepository.registerStore( - StoreVO( - name = "temp", - address = "temp", - openingHours = emptyList() - ) - ).collect { result -> - result.onSuccess { - _registerStoreState.value = UiState.Success(it) - }.onFailure { - val errorMsg = if (it is HttpResponseException) it.message else "가게 등록 실패" - _registerStoreState.value = UiState.Error(errorMsg) - } - } - } - - } - } - - fun setStoreId(storeId: Int) { - viewModelScope.launch(attExceptionHandler) { - Log.d("MainViewModel", "setStoreId: $storeId") - attPosUserRepository.saveStoreId(storeId) - } - } - private fun checkRefreshExpire(refreshDecodeStr: String): Boolean { val expStr = JSONObject(refreshDecodeStr).getString("exp") val expDate = unixTimeToDateTime(expStr.toLong()) @@ -144,43 +87,4 @@ class MainViewModel @Inject constructor( fun isDestinationDiff(destination: NavDestinationType): Boolean { return curSelectedScreen.value != destination } - - fun getTodayPreorder() { - viewModelScope.launch(attExceptionHandler) { - val date = - Formatter.getStringByDateTimeBaseFormatter(Calendar.getInstance().time.getUTCDateTime()) - val storeId = attPosUserRepository.getStoreId() - attOrderRepository.getPreOrders(storeId, page, date).collect { result -> - result.onSuccess { - todayPreorderList.addAll(it.preOrders) - page += 1 - if (page < it.lastPage) { - getTodayPreorder() - } else { - setPreorderAlarm() - } - }.onFailure { - val errorMsg = if (it is HttpResponseException) it.message else "예약 내역 불러오기 실패" - Log.e("getTodayPreorder", errorMsg!!) - } - } - } - } - - private fun setPreorderAlarm() { - for (preorderItem in todayPreorderList) { - // 각 아이템에 대한 알람 시간과 기타 설정 가져옴 - AlarmManager.setPreorderAlarm( - context, - preorderItem.orderedFor, - preorderItem.phone, - preorderItem.totalCount, - preorderItem.id - ) - } - } - - fun cancelAllPreorderAlarm() { - AlarmManager.cancelAllAlarm(context) - } } \ No newline at end of file diff --git a/feature/main/src/main/java/org/swm/att/home/home/HomeFragment.kt b/feature/main/src/main/java/org/swm/att/home/home/HomeFragment.kt index 69124e3b..0b1ae2d0 100644 --- a/feature/main/src/main/java/org/swm/att/home/home/HomeFragment.kt +++ b/feature/main/src/main/java/org/swm/att/home/home/HomeFragment.kt @@ -35,14 +35,13 @@ class HomeFragment : BaseFragment(R.layout.fragment_home) { super.onViewCreated(view, savedInstanceState) homeViewModel.clearSelectedMenuList() initRecyclerView() - setSelectedMenuList() setCategoriesObserver() setSelectedMenuObserver() setDataBinding() setOrderBtnListener() setPreorderBtnClickListener() setModifyPreorderBtnClickListener() - setCategories() + checkStoreId() } private fun setSelectedMenuList() { @@ -73,6 +72,37 @@ class HomeFragment : BaseFragment(R.layout.fragment_home) { } private fun setCategoriesObserver() { + homeViewModel.storeIdExist.observe(viewLifecycleOwner) { + if (it != -1) { // storeId가 있는 경우 + setPreorderAlarm() + setSelectedMenuList() + setCategories() + } else { // storeId가 없는 경우 + // TODO 새로운 가게 등록 화면으로 전환 + homeViewModel.registerStore() + } + } + + lifecycleScope.launch { + repeatOnLifecycle(Lifecycle.State.STARTED) { + homeViewModel.registerStoreState.collect { uiState -> + when(uiState) { + is UiState.Success -> { + Toast.makeText(requireContext(), "가게 등록이 완료되었습니다!", Toast.LENGTH_SHORT).show() + uiState.data?.let { + homeViewModel.setStoreId(it.storeId) + setPreorderAlarm() + setSelectedMenuList() + setCategories() + } + } + is UiState.Loading -> {/* nothing */} + is UiState.Error -> { Toast.makeText(requireContext(), uiState.errorMsg, Toast.LENGTH_SHORT).show() } + } + } + } + } + lifecycleScope.launch { repeatOnLifecycle(Lifecycle.State.STARTED) { homeViewModel.getMenuState.collect { uiState -> @@ -145,9 +175,22 @@ class HomeFragment : BaseFragment(R.layout.fragment_home) { } } + private fun checkStoreId() { + if (homeViewModel.storeIdExist.value == null) { + homeViewModel.checkStoreId() + } else { + setSelectedMenuList() + setCategories() + } + } + override fun onDestroy() { // TODO: activityViewModels와 기존 값 clear하는 방법 중 고민해보기 homeViewModel.clearGetMenuState() super.onDestroy() } + + private fun setPreorderAlarm() { + homeViewModel.getTodayPreorder() + } } \ No newline at end of file diff --git a/feature/main/src/main/java/org/swm/att/home/home/HomeViewModel.kt b/feature/main/src/main/java/org/swm/att/home/home/HomeViewModel.kt index 038d6da2..feca6d3c 100644 --- a/feature/main/src/main/java/org/swm/att/home/home/HomeViewModel.kt +++ b/feature/main/src/main/java/org/swm/att/home/home/HomeViewModel.kt @@ -1,32 +1,62 @@ package org.swm.att.home.home +import android.content.Context +import android.util.Log import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel +import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.launch import org.swm.att.common_ui.presenter.base.BaseViewModel import org.swm.att.common_ui.state.UiState +import org.swm.att.common_ui.util.Formatter +import org.swm.att.common_ui.util.getUTCDateTime import org.swm.att.domain.entity.HttpResponseException import org.swm.att.domain.entity.request.OrderedMenuVO import org.swm.att.domain.entity.request.OrderedMenusVO +import org.swm.att.domain.entity.request.StoreVO import org.swm.att.domain.entity.response.CategoriesVO +import org.swm.att.domain.entity.response.PreorderVO +import org.swm.att.domain.entity.response.StoreIdVO import org.swm.att.domain.repository.AttMenuRepository +import org.swm.att.domain.repository.AttOrderRepository import org.swm.att.domain.repository.AttPosUserRepository +import org.swm.att.home.util.alarm.AlarmManager +import java.util.Calendar import javax.inject.Inject @HiltViewModel class HomeViewModel @Inject constructor( private val attMenuRepository: AttMenuRepository, - private val attPosUserRepository: AttPosUserRepository + private val attPosUserRepository: AttPosUserRepository, + private val attOrderRepository: AttOrderRepository, + @ApplicationContext private val context: Context ): BaseViewModel() { private val _selectedMenuMap = MutableLiveData?>() val selectedMenuMap: LiveData?> = _selectedMenuMap private val _getMenuState = MutableStateFlow>(UiState.Loading) val getMenuState: StateFlow> = _getMenuState + private val _storeIdExist = MutableLiveData() + val storeIdExist: LiveData = _storeIdExist + + private val todayPreorderList = arrayListOf() + private var page = 1 + + private val _registerStoreState = MutableStateFlow>(UiState.Loading) + val registerStoreState: StateFlow> = _registerStoreState + + fun checkStoreId() { + viewModelScope.launch(attExceptionHandler) { + val storeId = attPosUserRepository.getStoreId() + _storeIdExist.postValue(storeId) + } + } + + fun setSelectedMenusVO(selectedMenusVO: OrderedMenusVO) { selectedMenusVO.menus?.let { val selectedOrderedMenuMap = mutableMapOf() @@ -106,4 +136,65 @@ class HomeViewModel @Inject constructor( fun clearGetMenuState() { _getMenuState.value = UiState.Loading } + + fun registerStore() { + viewModelScope.launch(attExceptionHandler) { + // 임시 token을 활용해 가게 바로 등록 + attPosUserRepository.registerStore( + StoreVO( + name = "temp", + address = "temp", + openingHours = emptyList() + ) + ).collect { result -> + result.onSuccess { + _registerStoreState.value = UiState.Success(it) + }.onFailure { + val errorMsg = if (it is HttpResponseException) it.message else "가게 등록 실패" + _registerStoreState.value = UiState.Error(errorMsg) + } + } + } + } + + fun getTodayPreorder() { + viewModelScope.launch(attExceptionHandler) { + val date = + Formatter.getStringByDateTimeBaseFormatter(Calendar.getInstance().time.getUTCDateTime()) + val storeId = attPosUserRepository.getStoreId() + attOrderRepository.getPreOrders(storeId, page, date).collect { result -> + result.onSuccess { + todayPreorderList.addAll(it.preOrders) + page += 1 + if (page < it.lastPage) { + getTodayPreorder() + } else { + setPreorderAlarm() + } + }.onFailure { + val errorMsg = if (it is HttpResponseException) it.message else "예약 내역 불러오기 실패" + Log.e("getTodayPreorder", errorMsg!!) + } + } + } + } + + private fun setPreorderAlarm() { + for (preorderItem in todayPreorderList) { + // 각 아이템에 대한 알람 시간과 기타 설정 가져옴 + AlarmManager.setPreorderAlarm( + context, + preorderItem.orderedFor, + preorderItem.phone, + preorderItem.totalCount, + preorderItem.id + ) + } + } + + fun setStoreId(storeId: Int) { + viewModelScope.launch(attExceptionHandler) { + attPosUserRepository.saveStoreId(storeId) + } + } } \ No newline at end of file diff --git a/feature/main/src/main/java/org/swm/att/home/recipe/RecipeFragment.kt b/feature/main/src/main/java/org/swm/att/home/recipe/RecipeFragment.kt index 19acff6d..06bccf57 100644 --- a/feature/main/src/main/java/org/swm/att/home/recipe/RecipeFragment.kt +++ b/feature/main/src/main/java/org/swm/att/home/recipe/RecipeFragment.kt @@ -203,6 +203,7 @@ class RecipeFragment : BaseFragment(R.layout.fragment_rec is UiState.Success -> { uiState.data?.let { Toast.makeText(requireContext(), "메뉴가 추가되었습니다.", Toast.LENGTH_SHORT).show() + recipeViewModel.changeCreateState(false) initData() } } diff --git a/feature/main/src/main/java/org/swm/att/home/recipe/RecipeViewModel.kt b/feature/main/src/main/java/org/swm/att/home/recipe/RecipeViewModel.kt index 335135b9..582c1443 100644 --- a/feature/main/src/main/java/org/swm/att/home/recipe/RecipeViewModel.kt +++ b/feature/main/src/main/java/org/swm/att/home/recipe/RecipeViewModel.kt @@ -70,6 +70,7 @@ class RecipeViewModel @Inject constructor( val currentSelectedCategory = _selectedCategory.value if (!currentSelectedCategory?.menus.isNullOrEmpty()) { currentSelectedCategory!!.menus[0].isFocused = true + getSelectedItem(currentSelectedCategory.menus[0].id) _currentSelectedMenuId.postValue(0) } } @@ -151,7 +152,9 @@ class RecipeViewModel @Inject constructor( fun changeCreateState(state: Boolean) { _isCreate.postValue(state) - _recipeListForNewMenu.postValue(emptyList()) + if (state) { + _recipeListForNewMenu.postValue(emptyList()) + } } fun postCategory(name: String) {