Skip to content
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,17 @@
extension ScreenFactory {

func makeMyPageViewController() -> MyPageViewController {
let authRepository = container.resolve(AuthRepository.self)
let userRepository = container.resolve(UserRepository.self)
let viewModel = MyPageViewModel(
fetchMyUserUseCase: FetchMyUserUseCase(
authRepository: authRepository,
userRepository: userRepository
),
updateMyUserUseCase: UpdateMyUserUseCase(
authRepository: authRepository,
userRepository: userRepository
),
fetchMyAppointmentsUseCase: FetchMyAppointmentsUseCase(
repository: container.resolve(AppointmentRepository.self)
),
Expand All @@ -19,7 +29,7 @@ extension ScreenFactory {
repository: container.resolve(LiveActivityPermissionRepository.self)
),
signOutUseCase: SignOutUseCase(
authRepository: container.resolve(AuthRepository.self),
authRepository: authRepository,
fcmInstallationIDRepository: container.resolve(FCMInstallationIDRepository.self)
)
)
Expand Down
26 changes: 17 additions & 9 deletions WhereAreYou/WhereAreYou/Data/Firebase/DTO/UserDTO.swift
Original file line number Diff line number Diff line change
Expand Up @@ -39,23 +39,31 @@ struct UserDTO {
}
}()

let sharingScope: LocationSharingScope = {
switch locationSharingScope {
case "ALWAYS": return .always
case "NEVER": return .never
default: return .onlyDuringAppointment
}
}()

return User(
id: id,
nickname: nickname,
profileImage: profileImage,
defaultTransportMode: transportMode,
locationSharingScope: sharingScope,
locationSharingScope: Self.locationSharingScope(from: locationSharingScope),
isNotificationEnabled: isNotificationEnabled,
appointmentsNotification: appointmentsNotification
)
}

static func value(from scope: LocationSharingScope) -> String {
switch scope {
case .always: return "ALWAYS"
case .onlyDuringAppointment: return "ONLY_DURING_APPOINTMENT"
case .never: return "NEVER"
}
}

private static func locationSharingScope(from value: String?) -> LocationSharingScope {
switch value {
case "ALWAYS": return .always
case "NEVER": return .never
default: return .onlyDuringAppointment
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ final class FirestoreUserRepository: UserRepository {
"nickname": nickname,
"profileImage": "basic",
"defaultTransportMode": "TRANSIT",
"locationSharingScope": "ONLY_DURING_APPOINTMENT",
"locationSharingScope": UserDTO.value(from: .onlyDuringAppointment),
"isNotificationEnabled": true,
"appointmentsNotification": [String: Bool](),
"createdAt": FieldValue.serverTimestamp()
Expand Down Expand Up @@ -106,6 +106,37 @@ final class FirestoreUserRepository: UserRepository {
}
}

func updateUser(
userID: String,
nickname: String?,
profileImage: String?,
locationSharingScope: LocationSharingScope?,
isNotificationEnabled: Bool?
) async throws -> User {
var fields: [String: Any] = [:]
if let nickname {
fields["nickname"] = nickname
}
if let profileImage {
fields["profileImage"] = profileImage
}
if let locationSharingScope {
fields["locationSharingScope"] = UserDTO.value(from: locationSharingScope)
}
if let isNotificationEnabled {
fields["isNotificationEnabled"] = isNotificationEnabled
}

if !fields.isEmpty {
do {
try await db.collection("users").document(userID).updateData(fields)
} catch {
throw FirebaseErrorMapper.map(error)
}
}
return try await fetchUser(userID: userID)
}

private func fetchUsers(chunk: [String]) async throws -> [String: User] {
let snapshot = try await db.collection("users")
.whereField(FieldPath.documentID(), in: chunk)
Expand Down
11 changes: 10 additions & 1 deletion WhereAreYou/WhereAreYou/Domain/Repository/UserRepository.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

import Foundation

/// 사용자 저장소 — Firestore 유저 문서 생성, 조회
/// 사용자 저장소 — Firestore 유저 문서 생성, 조회, 수정
protocol UserRepository {

func createUserIfNeeded(userID: String, nickname: String) async throws -> User
Expand All @@ -17,4 +17,13 @@ protocol UserRepository {
/// 여러 사용자를 한 번에 조회해 ID별로 돌려준다. 없는 사용자는 결과에서 빠진다
func fetchUsers(userIDs: Set<String>) async throws -> [String: User]

/// nil인 항목은 변경하지 않는다
func updateUser(
userID: String,
nickname: String?,
profileImage: String?,
locationSharingScope: LocationSharingScope?,
isNotificationEnabled: Bool?
) async throws -> User

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
//
// FetchMyUserUseCase.swift
// WhereAreYou
//
// Created by 이상유 on 2026-11-15.
//

import Foundation

/// 로그인한 내 유저 정보를 조회한다 — 로그인 상태가 아니면 AppError.notAuthenticated
final class FetchMyUserUseCase {

private let authRepository: AuthRepository
private let userRepository: UserRepository

init(authRepository: AuthRepository, userRepository: UserRepository) {
self.authRepository = authRepository
self.userRepository = userRepository
}

func execute() async throws -> User {
guard let userID = authRepository.currentUserID else {
throw AppError.notAuthenticated
}
return try await userRepository.fetchUser(userID: userID)
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
//
// UpdateMyUserUseCase.swift
// WhereAreYou
//
// Created by 이상유 on 2026-11-15.
//

import Foundation

/// 내 유저 정보(프로필·위치 공유 범위·전체 알림)를 수정하고 저장된 값을 돌려준다 — nil인 항목은 변경하지 않는다
final class UpdateMyUserUseCase {

private let authRepository: AuthRepository
private let userRepository: UserRepository

init(authRepository: AuthRepository, userRepository: UserRepository) {
self.authRepository = authRepository
self.userRepository = userRepository
}

func execute(
nickname: String? = nil,
profileImage: String? = nil,
locationSharingScope: LocationSharingScope? = nil,
isNotificationEnabled: Bool? = nil
) async throws -> User {
guard let userID = authRepository.currentUserID else {
throw AppError.notAuthenticated
}
return try await userRepository.updateUser(
userID: userID,
nickname: nickname,
profileImage: profileImage,
locationSharingScope: locationSharingScope,
isNotificationEnabled: isNotificationEnabled
)
}

}
115 changes: 85 additions & 30 deletions WhereAreYou/WhereAreYou/Presentation/MyPage/MyPageViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -58,16 +58,12 @@ final class MyPageViewController: UIViewController {
imageView.widthAnchor.constraint(equalToConstant: 16).isActive = true
return imageView
}()
private lazy var profileRow: MyPageRow = {
let row = MyPageRow(
icon: nil,
title: "닉네임",
isCircularImage: true,
accessoryView: profileEditIcon
)
row.setProfileIcon(viewModel.profile.profileImageName)
return row
}()
private lazy var profileRow = MyPageRow(
icon: nil,
title: "닉네임",
isCircularImage: true,
accessoryView: profileEditIcon
)

// MARK: - 위치 카드

Expand Down Expand Up @@ -108,14 +104,15 @@ final class MyPageViewController: UIViewController {
super.viewDidLoad()
view.backgroundColor = .systemBackground
setUpLayout()
setUpStaticContent()
setUpActions()
bindViewModel()
}

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: animated)
reloadContent()
viewModel.loadProfile()
viewModel.loadAppointmentNotifications()
}

Expand Down Expand Up @@ -208,46 +205,48 @@ final class MyPageViewController: UIViewController {

notificationSwitch.addAction(UIAction { [weak self] _ in
guard let self else { return }
viewModel.setNotificationEnabled(notificationSwitch.isOn)
viewModel.saveNotificationEnabled(notificationSwitch.isOn)
}, for: .valueChanged)
}

private func reloadContent() {
let profile = viewModel.profile

profileRow.value = profile.nickname
profileRow.setProfileIcon(profile.profileImageName)
locationSharingRow.value = profile.locationSharingOption.title
notificationSwitch.isOn = profile.isNotificationEnabled
notificationRow.value = profile.isNotificationEnabled ? "전체 알림 켜짐" : "전체 알림 꺼짐"

updateAppointmentNotificationRow(items: viewModel.appointmentNotifications)

private func setUpStaticContent() {
appInfoRow.value = "버전 정보"
signOutRow.value = "현재 계정에서 나가기"
}

/// 내 정보를 아직 불러오지 못했으면 값을 비우고 스위치를 끈다
private func updateProfileRows(_ profile: MyPageProfile?) {
profileRow.value = profile?.nickname
if let profile {
profileRow.setProfileIcon(profile.profileImageName)
}
locationSharingRow.value = profile?.locationSharingOption.title
notificationSwitch.isEnabled = profile != nil
notificationSwitch.setOn(profile?.isNotificationEnabled ?? false, animated: true)
notificationRow.value = profile.map { $0.isNotificationEnabled ? "전체 알림 켜짐" : "전체 알림 꺼짐" }
}

private func updateAppointmentNotificationRow(items: [AppointmentListItem]) {
let enabledCount = items.filter { $0.isNotificationEnabled }.count
appointmentNotificationRow.value = "\(enabledCount)개의 약속 알림 켜짐"
}

private func presentProfileEdit() {
guard let profile = viewModel.profile else { return }
coordinator?.showProfileEdit(
nickname: viewModel.profile.nickname,
profileImageName: viewModel.profile.profileImageName
nickname: profile.nickname,
profileImageName: profile.profileImageName
) { [weak self] nickname, profileImageName in
self?.viewModel.setProfile(nickname: nickname, profileImageName: profileImageName)
self?.reloadContent()
self?.viewModel.saveProfile(nickname: nickname, profileImageName: profileImageName)
}
}

private func presentLocationSharingSelection() {
guard let profile = viewModel.profile else { return }
coordinator?.showLocationSharingSelection(
selectedOption: viewModel.profile.locationSharingOption
selectedOption: profile.locationSharingOption
) { [weak self] option in
self?.viewModel.setLocationSharingOption(option)
self?.locationSharingRow.value = option.title
self?.viewModel.saveLocationSharingOption(option)
}
}

Expand All @@ -256,6 +255,21 @@ final class MyPageViewController: UIViewController {
}

private func bindViewModel() {
viewModel.$profile
.receive(on: DispatchQueue.main)
.sink { [weak self] profile in
self?.updateProfileRows(profile)
}
.store(in: &cancellables)

viewModel.$profileSaveFailure
.compactMap { $0 }
.receive(on: DispatchQueue.main)
.sink { [weak self] failure in
self?.handleProfileSaveFailure(failure)
}
.store(in: &cancellables)

viewModel.$appointmentNotifications
.receive(on: DispatchQueue.main)
.sink { [weak self] items in
Expand Down Expand Up @@ -310,6 +324,47 @@ final class MyPageViewController: UIViewController {
present(alert, animated: true)
}

/// 위치 공유 설정 화면에 있는 동안 실패하면 되돌아간 값을 볼 수 있게 마이페이지로 돌아온 뒤 알럿을 띄운다
private func handleProfileSaveFailure(_ failure: ProfileSaveFailure) {
guard let navigationController,
failure.item == .locationSharing,
navigationController.topViewController is LocationSharingSelectionViewController
else {
showProfileSaveFailureAlert(failure)
return
}

navigationController.popToViewController(self, animated: true)
if let transitionCoordinator = navigationController.transitionCoordinator {
transitionCoordinator.animate(alongsideTransition: nil) { [weak self] _ in
self?.showProfileSaveFailureAlert(failure)
}
} else {
showProfileSaveFailureAlert(failure)
}
}

private func showProfileSaveFailureAlert(_ failure: ProfileSaveFailure) {
let title: String
switch failure.item {
case .profile: title = "프로필이 바뀌지 않았어요"
case .locationSharing: title = "위치 공유 설정이 바뀌지 않았어요"
case .notification: title = "알림 설정이 바뀌지 않았어요"
}
let message = failure.isNetworkError
? "네트워크 연결을 확인한 뒤 다시 시도해 주세요."
: "잠시 후 다시 시도해 주세요."

let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "취소", style: .cancel))
let retryAction = UIAlertAction(title: "다시 시도", style: .default) { _ in
failure.retry()
}
alert.addAction(retryAction)
alert.preferredAction = retryAction
(navigationController ?? self).present(alert, animated: true)
}

private func presentAppointmentNotificationList() {
coordinator?.showAppointmentNotificationList(
fetchItems: { [weak self] in self?.viewModel.appointmentNotifications ?? [] },
Expand Down
Loading
Loading