Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feat] #170 월 계산로직 수정 및 에러 핸들링 #176

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions SOPT-iOS/Projects/Core/Sources/Extension/Foundation+/Date+.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
//
// Date+.swift
// Core
//
// Created by sejin on 2023/04/17.
// Copyright © 2023 SOPT-iOS. All rights reserved.
//

import Foundation

public extension Date {
/// Create a date from specified parameters
///
/// - Parameters:
/// - year: The desired year
/// - month: The desired month
/// - day: The desired day
/// - Returns: A `Date` object
static func from(year: Int, month: Int, day: Int) -> Date? {
let calendar = Calendar(identifier: .gregorian)
var dateComponents = DateComponents()
dateComponents.timeZone = TimeZone.current
dateComponents.year = year
dateComponents.month = month
dateComponents.day = day
return calendar.date(from: dateComponents) ?? nil
}
}
15 changes: 11 additions & 4 deletions SOPT-iOS/Projects/Domain/Sources/Model/UserMainInfoModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,15 @@
import Foundation

public struct UserMainInfoModel {
public let status, name, profileImage: String
public let status, name: String
public let profileImage: String?
public let historyList: [Int]
public let attendanceScore: Float
public let announcement: String
public let attendanceScore: Float?
public let announcement: String?
public let responseMessage: String?
public var withError: Bool = false

public init(status: String, name: String, profileImage: String, historyList: [Int], attendanceScore: Float, announcement: String, responseMessage: String?) {
public init(status: String, name: String, profileImage: String?, historyList: [Int], attendanceScore: Float?, announcement: String?, responseMessage: String?) {
self.status = status
self.name = name
self.profileImage = profileImage
Expand All @@ -24,4 +26,9 @@ public struct UserMainInfoModel {
self.announcement = announcement
self.responseMessage = responseMessage
}

public init(withError: Bool) {
self.init(status: "", name: "", profileImage: nil, historyList: [], attendanceScore: nil, announcement: nil, responseMessage: nil)
self.withError = withError
}
}
1 change: 1 addition & 0 deletions SOPT-iOS/Projects/Domain/Sources/UseCase/MainUseCase.swift
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ public class DefaultMainUseCase {
extension DefaultMainUseCase: MainUseCase {
public func getUserMainInfo() {
repository.getUserMainInfo()
.replaceError(with: UserMainInfoModel.init(withError: true))
.sink { event in
print("MainUseCase: \(event)")
} receiveValue: { [weak self] userMainInfoModel in
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import SnapKit
import Then

import AuthFeatureInterface
import BaseFeatureDependency
import MainFeatureInterface
import StampFeatureInterface
import SettingFeatureInterface
Expand All @@ -30,15 +31,16 @@ public class MainVC: UIViewController, MainViewControllable {
& SettingFeatureViewBuildable
& AppMyPageFeatureViewBuildable
& AttendanceFeatureViewBuildable
& AlertViewBuildable

// MARK: - Properties

public var viewModel: MainViewModel!
public var factory: factoryType!
private var cancelBag = CancelBag()

private var userMainInfo: UserMainInfoModel?
private var requestUserInfo = CurrentValueSubject<Void, Never>(())

// MARK: - UI Components

private let naviBar = MainNavigationBar()
Expand Down Expand Up @@ -96,16 +98,20 @@ extension MainVC {

extension MainVC {
private func bindViewModels() {
let input = MainViewModel.Input(viewDidLoad: Driver.just(()))
let input = MainViewModel.Input(requestUserInfo: self.requestUserInfo)
let output = self.viewModel.transform(from: input, cancelBag: self.cancelBag)

output.getUserMainInfoDidComplete
.sink { [weak self] _ in
guard let userMainInfo = self?.viewModel.userMainInfo, userMainInfo.withError == false else {
self?.presentNetworkAlertVC()
return
}
self?.collectionView.reloadData()
}.store(in: self.cancelBag)

output.isServiceAvailable
.sink { [weak self] isServiceAvailable in
.sink { isServiceAvailable in
print("현재 앱 서비스 사용 가능(심사 X)?: \(isServiceAvailable)")
}.store(in: self.cancelBag)
}
Expand All @@ -117,12 +123,6 @@ extension MainVC {
.sink { owner, _ in
let viewController = owner.factory.makeAppMyPageVC(userType: owner.viewModel.userType).viewController
owner.navigationController?.pushViewController(viewController, animated: true)

// if owner.viewModel.userType == .visitor {
// owner.setRootViewToSignIn()
// return
// }
// owner.pushSettingFeature()
}.store(in: self.cancelBag)
}

Expand Down Expand Up @@ -160,6 +160,20 @@ extension MainVC {
let navigation = UINavigationController(rootViewController: factory.makeSignInVC().viewController)
ViewControllerUtils.setRootViewController(window: self.view.window!, viewController: navigation, withAnimation: true)
}

private func presentNetworkAlertVC() {
let networkAlertVC = factory.makeAlertVC(
type: .titleDescription,
theme: .main,
title: I18N.Default.networkError,
description: I18N.Default.networkErrorDescription,
customButtonTitle: I18N.Default.ok,
customAction:{ [weak self] in
self?.requestUserInfo.send()
}).viewController

self.present(networkAlertVC, animated: false)
}
}

// MARK: - UICollectionViewDelegate
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public class MainViewModel: ViewModelType {
// MARK: - Inputs

public struct Input {
let viewDidLoad: Driver<Void>
let requestUserInfo: CurrentValueSubject<Void, Never>
}

// MARK: - Outputs
Expand All @@ -54,7 +54,7 @@ extension MainViewModel {
let output = Output()
self.bindOutput(output: output, cancelBag: cancelBag)

input.viewDidLoad
input.requestUserInfo
.sink { [weak self] _ in
guard let self = self else { return }
if self.userType != .visitor {
Expand All @@ -74,7 +74,7 @@ extension MainViewModel {
}.store(in: self.cancelBag)

useCase.serviceState.asDriver()
.sink { [weak self] serviceState in
.sink { serviceState in
output.isServiceAvailable.send(serviceState.isAvailable)
}.store(in: self.cancelBag)
}
Expand All @@ -94,37 +94,31 @@ extension MainViewModel {
}
}

/// 최초 솝트 가입일로부터 몇달이 지났는지 계산
func calculateMonths() -> String? {
guard let userMainInfo = userMainInfo else { return nil }
if userMainInfo.status == "ACTIVE" && userMainInfo.historyList.count > 0 {
guard var currentMonth = getCurrentMonth() else {
return String(userMainInfo.historyList.count * 5)
}

// 짝수 기수 -> 상반기
if let recent = userMainInfo.historyList.first {
var currentGenerationTime = 0
if recent % 2 == 0 {
// 기수 시작 3월 기준으로 계산
currentGenerationTime = currentMonth - 3 + 1
} else {
// 현재 1월 일 때
if currentMonth < 3 {
currentMonth += 12
}
currentGenerationTime = currentMonth - 9 + 1
}
return String((userMainInfo.historyList.count-1)*5 + currentGenerationTime)
}
}
return String(userMainInfo.historyList.count * 5)
guard let userMainInfo = userMainInfo, let firstHistory = userMainInfo.historyList.last else { return nil }
guard let joinDate = calculateJoinDateWithFirstHistory(history: firstHistory), let monthDifference = calculateMonthDifference(since: joinDate) else { return nil }

return String(monthDifference)
}

private func getCurrentMonth() -> Int? {
let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "M"
let monthString = dateFormatter.string(from: date)
return Int(monthString)
// 파라미터로 넣은 기수의 시작 날짜를 리턴
private func calculateJoinDateWithFirstHistory(history: Int) -> Date? {
let yearDifference = history / 2
let month = (history % 2 == 0) ? 3 : 9 // 짝수 기수는 3월, 홀수 기수는 9월 시작
// 1기를 2007년으로 계산
return Date.from(year: yearDifference + 2007, month: month, day: 1)
Copy link
Member

@devxsby devxsby Apr 17, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

개월수를 서버에서 뿌려주는게 아니였군요.. !!!!
솝트 홈피에는 창립이 2008로 나오긴 하는디 ... 따로 기획한테 안물어보고 작업해도 될가요옹?
특이사항만 있는지 한번만 체크해봐도 좋을거같아여

스크린샷 2023-04-17 22 14 29

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

2008년으로 알고 있기는 했는데 그렇게 하면 기수 계산이 밀려서 2007년으로 두고 했어요!
image
여기에 있는 기수, 날짜를 토대로 식을 세우다 보니 2007년으로 했는데 이 부분은 나중에 서버에서 계산해서 내려주는 걸로 바뀔 것 같아요~!

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

굿 !! 👍🏻

}

// 파라미터로 넣은 날짜로 부터 현재 몇달이 지났는지 계산
private func calculateMonthDifference(since startDate: Date) -> Int? {
let calendar = Calendar.current

let components = calendar.dateComponents([.month], from: startDate, to: .now)
guard let month = components.month else {
return nil
}

return month >= 0 ? month + 1 : nil
}
}