diff --git a/WhereAreYou/WhereAreYou/Core/DI/Implementation/ScreenFactory/ScreenFactory+MyPage.swift b/WhereAreYou/WhereAreYou/Core/DI/Implementation/ScreenFactory/ScreenFactory+MyPage.swift index 8b7602e..40ccc5b 100644 --- a/WhereAreYou/WhereAreYou/Core/DI/Implementation/ScreenFactory/ScreenFactory+MyPage.swift +++ b/WhereAreYou/WhereAreYou/Core/DI/Implementation/ScreenFactory/ScreenFactory+MyPage.swift @@ -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) ), @@ -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) ) ) diff --git a/WhereAreYou/WhereAreYou/Data/Firebase/DTO/UserDTO.swift b/WhereAreYou/WhereAreYou/Data/Firebase/DTO/UserDTO.swift index f4a3bf2..73e774d 100644 --- a/WhereAreYou/WhereAreYou/Data/Firebase/DTO/UserDTO.swift +++ b/WhereAreYou/WhereAreYou/Data/Firebase/DTO/UserDTO.swift @@ -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 + } + } + } diff --git a/WhereAreYou/WhereAreYou/Data/Firebase/Repository/FirestoreUserRepository.swift b/WhereAreYou/WhereAreYou/Data/Firebase/Repository/FirestoreUserRepository.swift index 121da41..2048ee1 100644 --- a/WhereAreYou/WhereAreYou/Data/Firebase/Repository/FirestoreUserRepository.swift +++ b/WhereAreYou/WhereAreYou/Data/Firebase/Repository/FirestoreUserRepository.swift @@ -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() @@ -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) diff --git a/WhereAreYou/WhereAreYou/Domain/Repository/UserRepository.swift b/WhereAreYou/WhereAreYou/Domain/Repository/UserRepository.swift index b4e9e01..487504e 100644 --- a/WhereAreYou/WhereAreYou/Domain/Repository/UserRepository.swift +++ b/WhereAreYou/WhereAreYou/Domain/Repository/UserRepository.swift @@ -7,7 +7,7 @@ import Foundation -/// 사용자 저장소 — Firestore 유저 문서 생성, 조회 +/// 사용자 저장소 — Firestore 유저 문서 생성, 조회, 수정 protocol UserRepository { func createUserIfNeeded(userID: String, nickname: String) async throws -> User @@ -17,4 +17,13 @@ protocol UserRepository { /// 여러 사용자를 한 번에 조회해 ID별로 돌려준다. 없는 사용자는 결과에서 빠진다 func fetchUsers(userIDs: Set) async throws -> [String: User] + /// nil인 항목은 변경하지 않는다 + func updateUser( + userID: String, + nickname: String?, + profileImage: String?, + locationSharingScope: LocationSharingScope?, + isNotificationEnabled: Bool? + ) async throws -> User + } diff --git a/WhereAreYou/WhereAreYou/Domain/UseCase/User/FetchMyUserUseCase.swift b/WhereAreYou/WhereAreYou/Domain/UseCase/User/FetchMyUserUseCase.swift new file mode 100644 index 0000000..d32e7fb --- /dev/null +++ b/WhereAreYou/WhereAreYou/Domain/UseCase/User/FetchMyUserUseCase.swift @@ -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) + } + +} diff --git a/WhereAreYou/WhereAreYou/Domain/UseCase/User/UpdateMyUserUseCase.swift b/WhereAreYou/WhereAreYou/Domain/UseCase/User/UpdateMyUserUseCase.swift new file mode 100644 index 0000000..72a6c86 --- /dev/null +++ b/WhereAreYou/WhereAreYou/Domain/UseCase/User/UpdateMyUserUseCase.swift @@ -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 + ) + } + +} diff --git a/WhereAreYou/WhereAreYou/Presentation/MyPage/MyPageViewController.swift b/WhereAreYou/WhereAreYou/Presentation/MyPage/MyPageViewController.swift index 6f275cd..af76d81 100644 --- a/WhereAreYou/WhereAreYou/Presentation/MyPage/MyPageViewController.swift +++ b/WhereAreYou/WhereAreYou/Presentation/MyPage/MyPageViewController.swift @@ -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: - 위치 카드 @@ -108,6 +104,7 @@ final class MyPageViewController: UIViewController { super.viewDidLoad() view.backgroundColor = .systemBackground setUpLayout() + setUpStaticContent() setUpActions() bindViewModel() } @@ -115,7 +112,7 @@ final class MyPageViewController: UIViewController { override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(true, animated: animated) - reloadContent() + viewModel.loadProfile() viewModel.loadAppointmentNotifications() } @@ -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) } } @@ -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 @@ -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 ?? [] }, diff --git a/WhereAreYou/WhereAreYou/Presentation/MyPage/MyPageViewModel.swift b/WhereAreYou/WhereAreYou/Presentation/MyPage/MyPageViewModel.swift index 7759b7e..755c250 100644 --- a/WhereAreYou/WhereAreYou/Presentation/MyPage/MyPageViewModel.swift +++ b/WhereAreYou/WhereAreYou/Presentation/MyPage/MyPageViewModel.swift @@ -9,7 +9,8 @@ import Combine import Foundation // MARK: - 마이페이지 화면(탭)의 데이터 -// - profile: 프로필 카드에 표시할 사용자 정보 +// - profile: 프로필 카드·위치 공유·전체 알림에 표시할 내 유저 정보 +// (수정은 화면에 먼저 반영하고, 저장에 실패하면 이전 값으로 되돌린 뒤 profileSaveFailure를 발행) // - appointmentNotifications: 약속별 알림 화면에서 쓸 약속 목록 // - locationPermissionState: 위치 권한 상태를 표시용 타입으로 변환해 발행 // (실제 CoreLocation 접근은 Data 계층이 담당하며, ObserveLocationPermissionUseCase를 통해 전달받음) @@ -18,26 +19,34 @@ import Foundation final class MyPageViewModel { - private(set) var profile: MyPageProfile + @Published private(set) var profile: MyPageProfile? + @Published private(set) var profileSaveFailure: ProfileSaveFailure? @Published private(set) var appointmentNotifications: [AppointmentListItem] = [] @Published private(set) var locationPermissionState: LocationPermissionState @Published private(set) var liveActivityPermissionState: LiveActivityPermissionState @Published private(set) var signOutResult: Result? + private let fetchMyUserUseCase: FetchMyUserUseCase + private let updateMyUserUseCase: UpdateMyUserUseCase private let fetchMyAppointmentsUseCase: FetchMyAppointmentsUseCase private let observeLocationPermissionUseCase: ObserveLocationPermissionUseCase private let observeLiveActivityPermissionUseCase: ObserveLiveActivityPermissionUseCase private let signOutUseCase: SignOutUseCase + /// 저장 요청마다 올라가는 번호 — 늦게 도착한 이전 요청의 결과가 최신 값을 덮어쓰지 않게 한다 + private var latestProfileSaveID = 0 + init( - profile: MyPageProfile? = nil, + fetchMyUserUseCase: FetchMyUserUseCase, + updateMyUserUseCase: UpdateMyUserUseCase, fetchMyAppointmentsUseCase: FetchMyAppointmentsUseCase, observeLocationPermissionUseCase: ObserveLocationPermissionUseCase, observeLiveActivityPermissionUseCase: ObserveLiveActivityPermissionUseCase, signOutUseCase: SignOutUseCase ) { - self.profile = profile ?? Self.makeDummyProfile() + self.fetchMyUserUseCase = fetchMyUserUseCase + self.updateMyUserUseCase = updateMyUserUseCase self.fetchMyAppointmentsUseCase = fetchMyAppointmentsUseCase self.observeLocationPermissionUseCase = observeLocationPermissionUseCase self.observeLiveActivityPermissionUseCase = observeLiveActivityPermissionUseCase @@ -66,42 +75,116 @@ final class MyPageViewModel { extension MyPageViewModel { - func setProfile(nickname: String, profileImageName: String) { - profile = MyPageProfile( - nickname: nickname, - profileImageName: profileImageName, - locationSharingOption: profile.locationSharingOption, - isNotificationEnabled: profile.isNotificationEnabled - ) + /// 실패해도 알럿 없이 이전 값을 유지한다 + func loadProfile() { + Task { @MainActor in + guard let user = try? await fetchMyUserUseCase.execute() else { return } + profile = MyPageProfile(user: user) + } } - func setNotificationEnabled(_ isEnabled: Bool) { - profile = MyPageProfile( - nickname: profile.nickname, - profileImageName: profile.profileImageName, - locationSharingOption: profile.locationSharingOption, - isNotificationEnabled: isEnabled - ) + func saveProfile(nickname: String, profileImageName: String) { + guard let current = profile, + nickname != current.nickname || profileImageName != current.profileImageName + else { return } + + save( + MyPageProfile( + nickname: nickname, + profileImageName: profileImageName, + locationSharingOption: current.locationSharingOption, + isNotificationEnabled: current.isNotificationEnabled + ), + item: .profile, + retry: { [weak self] in self?.saveProfile(nickname: nickname, profileImageName: profileImageName) } + ) { + try await self.updateMyUserUseCase.execute(nickname: nickname, profileImage: profileImageName) + } } - func setLocationSharingOption(_ option: LocationSharingOption) { - profile = MyPageProfile( - nickname: profile.nickname, - profileImageName: profile.profileImageName, - locationSharingOption: option, - isNotificationEnabled: profile.isNotificationEnabled - ) + func saveNotificationEnabled(_ isEnabled: Bool) { + guard let current = profile, isEnabled != current.isNotificationEnabled else { return } + + save( + MyPageProfile( + nickname: current.nickname, + profileImageName: current.profileImageName, + locationSharingOption: current.locationSharingOption, + isNotificationEnabled: isEnabled + ), + item: .notification, + retry: { [weak self] in self?.saveNotificationEnabled(isEnabled) } + ) { + try await self.updateMyUserUseCase.execute(isNotificationEnabled: isEnabled) + } } - private static func makeDummyProfile() -> MyPageProfile { - MyPageProfile( - nickname: "성훈", - profileImageName: "shark", - locationSharingOption: .onlyDuringAppointment, - isNotificationEnabled: true - ) + func saveLocationSharingOption(_ option: LocationSharingOption) { + guard let current = profile, option != current.locationSharingOption else { return } + + save( + MyPageProfile( + nickname: current.nickname, + profileImageName: current.profileImageName, + locationSharingOption: option, + isNotificationEnabled: current.isNotificationEnabled + ), + item: .locationSharing, + retry: { [weak self] in self?.saveLocationSharingOption(option) } + ) { + try await self.updateMyUserUseCase.execute(locationSharingScope: option.scope) + } } + /// 바뀐 값을 먼저 화면에 반영하고 저장한다. 성공하면 저장된 값으로, 실패하면 이전 값으로 맞춘다 + private func save( + _ newProfile: MyPageProfile, + item: ProfileSaveFailure.Item, + retry: @escaping () -> Void, + update: @escaping () async throws -> User + ) { + guard let previous = profile else { return } + + latestProfileSaveID += 1 + let saveID = latestProfileSaveID + profile = newProfile + + Task { @MainActor in + do { + let user = try await update() + guard saveID == latestProfileSaveID else { return } + profile = MyPageProfile(user: user) + } catch { + guard saveID == latestProfileSaveID else { return } + profile = previous + let isNetworkError: Bool + if case AppError.network = error { + isNetworkError = true + } else { + isNetworkError = false + } + profileSaveFailure = ProfileSaveFailure(item: item, isNetworkError: isNetworkError, retry: retry) + } + } + } + +} + +// MARK: - 저장 실패 + +/// 저장에 실패한 항목과 원인, 같은 값으로 다시 저장하는 동작 — 화면이 알럿 문구와 다시 시도 버튼을 만드는 데 쓴다 +struct ProfileSaveFailure { + + enum Item { + case profile + case locationSharing + case notification + } + + let item: Item + let isNetworkError: Bool + let retry: () -> Void + } // MARK: - 약속별 알림 diff --git a/WhereAreYou/WhereAreYou/Presentation/PresentationModel/LocationSharingOption.swift b/WhereAreYou/WhereAreYou/Presentation/PresentationModel/LocationSharingOption.swift index 59a363c..65085b1 100644 --- a/WhereAreYou/WhereAreYou/Presentation/PresentationModel/LocationSharingOption.swift +++ b/WhereAreYou/WhereAreYou/Presentation/PresentationModel/LocationSharingOption.swift @@ -23,4 +23,12 @@ enum LocationSharingOption: CaseIterable { } } + var scope: LocationSharingScope { + switch self { + case .always: return .always + case .onlyDuringAppointment: return .onlyDuringAppointment + case .never: return .never + } + } + } diff --git a/WhereAreYou/WhereAreYou/Presentation/PresentationModel/MyPageProfile.swift b/WhereAreYou/WhereAreYou/Presentation/PresentationModel/MyPageProfile.swift index af7476a..e085639 100644 --- a/WhereAreYou/WhereAreYou/Presentation/PresentationModel/MyPageProfile.swift +++ b/WhereAreYou/WhereAreYou/Presentation/PresentationModel/MyPageProfile.swift @@ -13,3 +13,14 @@ struct MyPageProfile { let locationSharingOption: LocationSharingOption let isNotificationEnabled: Bool } + +extension MyPageProfile { + + init(user: User) { + nickname = user.nickname + profileImageName = user.profileImage + locationSharingOption = LocationSharingOption(scope: user.locationSharingScope) + isNotificationEnabled = user.isNotificationEnabled + } + +}