Skip to content

Commit

Permalink
feat: move checking storeId logic(mainActivity -> homeFragment)
Browse files Browse the repository at this point in the history
  • Loading branch information
915dbfl committed Oct 16, 2023
1 parent 159506d commit e6afd06
Show file tree
Hide file tree
Showing 6 changed files with 154 additions and 145 deletions.
57 changes: 12 additions & 45 deletions feature/main/src/main/java/org/swm/att/home/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -27,23 +22,16 @@ class MainActivity: BaseActivity<ActivityMainBinding>(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
Expand All @@ -58,14 +46,14 @@ class MainActivity: BaseActivity<ActivityMainBinding>(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 {
Expand All @@ -75,28 +63,11 @@ class MainActivity: BaseActivity<ActivityMainBinding>(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() {
Expand All @@ -108,12 +79,8 @@ class MainActivity: BaseActivity<ActivityMainBinding>(R.layout.activity_main) {
}
}

private fun setPreorderAlarm() {
mainViewModel.getTodayPreorder()
}

override fun onDestroy() {
mainViewModel.cancelAllPreorderAlarm()
AlarmManager.cancelAllAlarm(this)
super.onDestroy()
}

Expand Down
96 changes: 0 additions & 96 deletions feature/main/src/main/java/org/swm/att/home/MainViewModel.kt
Original file line number Diff line number Diff line change
@@ -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<Boolean>()
val refreshExist: LiveData<Boolean> = _refreshExist
Expand All @@ -43,14 +27,6 @@ class MainViewModel @Inject constructor(
private val _isGlobalAction = MutableLiveData(false)
val isGlobalAction: LiveData<Boolean> = _isGlobalAction

private val todayPreorderList = arrayListOf<PreorderVO>()
private var page = 1

private val _storeIdExist = MutableLiveData<Int>()
val storeIdExist: LiveData<Int> = _storeIdExist
private val _registerStoreState = MutableStateFlow<UiState<StoreIdVO>>(UiState.Loading)
val registerStoreState: StateFlow<UiState<StoreIdVO>> = _registerStoreState

fun checkRefreshToken() {
viewModelScope.launch {
val curRefreshToken = attPosUserRepository.getRefreshToken()
Expand All @@ -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())
Expand Down Expand Up @@ -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)
}
}
47 changes: 45 additions & 2 deletions feature/main/src/main/java/org/swm/att/home/home/HomeFragment.kt
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,13 @@ class HomeFragment : BaseFragment<FragmentHomeBinding>(R.layout.fragment_home) {
super.onViewCreated(view, savedInstanceState)
homeViewModel.clearSelectedMenuList()
initRecyclerView()
setSelectedMenuList()
setCategoriesObserver()
setSelectedMenuObserver()
setDataBinding()
setOrderBtnListener()
setPreorderBtnClickListener()
setModifyPreorderBtnClickListener()
setCategories()
checkStoreId()
}

private fun setSelectedMenuList() {
Expand Down Expand Up @@ -73,6 +72,37 @@ class HomeFragment : BaseFragment<FragmentHomeBinding>(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 ->
Expand Down Expand Up @@ -145,9 +175,22 @@ class HomeFragment : BaseFragment<FragmentHomeBinding>(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()
}
}
Loading

0 comments on commit e6afd06

Please sign in to comment.