diff --git a/EATSSU/App/Resources/en.lproj/Localizable.strings b/EATSSU/App/Resources/en.lproj/Localizable.strings index 3de7d273..90a2bb9e 100644 --- a/EATSSU/App/Resources/en.lproj/Localizable.strings +++ b/EATSSU/App/Resources/en.lproj/Localizable.strings @@ -467,6 +467,25 @@ /// 다시 시도해주세요. "notification_error_unknown_description" = "Please try again."; +// MARK: - Notification Inbox (알림함) + +/// "알림" +"notification.inboxTitle" = "Notifications"; +/// "모두 읽음" +"notification.readAll" = "Mark all as read"; +/// "새로운 알림이 없어요." +"notification.emptyTitle" = "No new notifications."; +/// "찜한 메뉴가 나오면 알림으로 알려드릴게요!" +"notification.emptySubtitle" = "We'll notify you when a saved menu is served!"; +/// "7일 전 알림까지 확인할 수 있어요" +"notification.retentionNotice" = "Notifications from the last 7 days are shown"; +/// "방금 전" +"notification.justNow" = "Just now"; +/// "%d시간 전" +"notification.hoursAgo" = "%dh ago"; +/// "알림을 불러오지 못했어요." +"notification.loadFailed" = "Couldn't load notifications."; + // MARK: - Restaurant diff --git a/EATSSU/App/Resources/ja.lproj/Localizable.strings b/EATSSU/App/Resources/ja.lproj/Localizable.strings index a4534df1..48289079 100644 --- a/EATSSU/App/Resources/ja.lproj/Localizable.strings +++ b/EATSSU/App/Resources/ja.lproj/Localizable.strings @@ -468,6 +468,25 @@ /// 다시 시도해주세요. "notification_error_unknown_description" = "もう一度お試しください。"; +// MARK: - Notification Inbox (알림함) + +/// "알림" +"notification.inboxTitle" = "通知"; +/// "모두 읽음" +"notification.readAll" = "すべて既読"; +/// "새로운 알림이 없어요." +"notification.emptyTitle" = "新しい通知はありません。"; +/// "찜한 메뉴가 나오면 알림으로 알려드릴게요!" +"notification.emptySubtitle" = "お気に入りのメニューが出たらお知らせします!"; +/// "7일 전 알림까지 확인할 수 있어요" +"notification.retentionNotice" = "7日前までの通知を確認できます"; +/// "방금 전" +"notification.justNow" = "たった今"; +/// "%d시간 전" +"notification.hoursAgo" = "%d時間前"; +/// "알림을 불러오지 못했어요." +"notification.loadFailed" = "通知を読み込めませんでした。"; + // MARK: - Restaurant diff --git a/EATSSU/App/Resources/ko.lproj/Localizable.strings b/EATSSU/App/Resources/ko.lproj/Localizable.strings index 4093111e..0b8b3e14 100644 --- a/EATSSU/App/Resources/ko.lproj/Localizable.strings +++ b/EATSSU/App/Resources/ko.lproj/Localizable.strings @@ -468,6 +468,25 @@ /// 다시 시도해주세요. "notification_error_unknown_description" = "다시 시도해주세요."; +// MARK: - Notification Inbox (알림함) + +/// "알림" +"notification.inboxTitle" = "알림"; +/// "모두 읽음" +"notification.readAll" = "모두 읽음"; +/// "새로운 알림이 없어요." +"notification.emptyTitle" = "새로운 알림이 없어요."; +/// "찜한 메뉴가 나오면 알림으로 알려드릴게요!" +"notification.emptySubtitle" = "찜한 메뉴가 나오면 알림으로 알려드릴게요!"; +/// "7일 전 알림까지 확인할 수 있어요" +"notification.retentionNotice" = "7일 전 알림까지 확인할 수 있어요"; +/// "방금 전" +"notification.justNow" = "방금 전"; +/// "%d시간 전" +"notification.hoursAgo" = "%d시간 전"; +/// "알림을 불러오지 못했어요." +"notification.loadFailed" = "알림을 불러오지 못했어요."; + // MARK: - Restaurant diff --git a/EATSSU/App/Resources/vi.lproj/Localizable.strings b/EATSSU/App/Resources/vi.lproj/Localizable.strings index b62e4618..afffdbfa 100644 --- a/EATSSU/App/Resources/vi.lproj/Localizable.strings +++ b/EATSSU/App/Resources/vi.lproj/Localizable.strings @@ -468,6 +468,25 @@ /// 다시 시도해주세요. "notification_error_unknown_description" = "Vui lòng thử lại."; +// MARK: - Notification Inbox (알림함) + +/// "알림" +"notification.inboxTitle" = "Thông báo"; +/// "모두 읽음" +"notification.readAll" = "Đánh dấu đã đọc tất cả"; +/// "새로운 알림이 없어요." +"notification.emptyTitle" = "Không có thông báo mới."; +/// "찜한 메뉴가 나오면 알림으로 알려드릴게요!" +"notification.emptySubtitle" = "Chúng tôi sẽ báo khi món đã lưu được phục vụ!"; +/// "7일 전 알림까지 확인할 수 있어요" +"notification.retentionNotice" = "Hiển thị thông báo trong 7 ngày gần nhất"; +/// "방금 전" +"notification.justNow" = "Vừa xong"; +/// "%d시간 전" +"notification.hoursAgo" = "%d giờ trước"; +/// "알림을 불러오지 못했어요." +"notification.loadFailed" = "Không thể tải thông báo."; + // MARK: - Restaurant diff --git a/EATSSU/App/Sources/Data/Network/DTO/Notification/NotificationDTO.swift b/EATSSU/App/Sources/Data/Network/DTO/Notification/NotificationDTO.swift new file mode 100644 index 00000000..6a39d4ee --- /dev/null +++ b/EATSSU/App/Sources/Data/Network/DTO/Notification/NotificationDTO.swift @@ -0,0 +1,30 @@ +// +// NotificationDTO.swift +// EATSSU +// +// Created by 황상환 on 11/7/26. +// + +import Foundation + +/// 알림함 항목 (`GET /notifications`) +struct NotificationItemDTO: Codable, Equatable { + let notificationId: Int + /// 알림 종류. 현재는 `MENU_FAVORITE`만 온다 + let type: String + /// 제목·본문은 조회 시점의 사용자 언어로 만들어진다 + let title: String + let body: String + /// 알림을 누르면 이동할 식단 날짜 (yyyyMMdd) + let date: String + /// 이동할 시간대 (MORNING / LUNCH / DINNER) + let timePart: String? + let isRead: Bool + /// 알림 생성 시각. 서버(한국) 시간이며 타임존 표기가 없다 (예: `2026-11-02T11:00:00`) + let createdAt: String +} + +/// `GET /notifications/unread` +struct UnreadNotificationDTO: Codable { + let hasUnread: Bool +} diff --git a/EATSSU/App/Sources/Data/Network/Router/NotificationRouter.swift b/EATSSU/App/Sources/Data/Network/Router/NotificationRouter.swift new file mode 100644 index 00000000..11759c52 --- /dev/null +++ b/EATSSU/App/Sources/Data/Network/Router/NotificationRouter.swift @@ -0,0 +1,62 @@ +// +// NotificationRouter.swift +// EATSSU +// +// Created by 황상환 on 11/7/26. +// + +import Foundation + +import Moya + +/// 알림함 API (로그인 필요). 서버는 최근 7일(식단 날짜 기준) 찜 메뉴 알림만 보관한다 +enum NotificationRouter { + /// 알림 목록 (최신순). 제목·본문은 조회 시점의 사용자 언어로 내려온다 + case getNotifications + /// 안 읽은 알림이 있는지 (학식 탭 알림 아이콘의 점 표시) + case hasUnread + /// 알림 하나 읽음 처리. 이미 읽었어도 성공 + case read(notificationId: Int) + /// 내 알림 모두 읽음 처리 + case readAll +} + +extension NotificationRouter: TargetType { + var baseURL: URL { + URL(string: Config.baseURL)! + } + + var path: String { + switch self { + case .getNotifications: + "/notifications" + case .hasUnread: + "/notifications/unread" + case let .read(notificationId): + "/notifications/\(notificationId)/read" + case .readAll: + "/notifications/read-all" + } + } + + var method: Moya.Method { + switch self { + case .getNotifications, .hasUnread: + .get + case .read, .readAll: + .patch + } + } + + var task: Moya.Task { + .requestPlain + } + + var headers: [String: String]? { + ["Content-Type": "application/json"] + } + + var validationType: ValidationType { + .successCodes + } +} diff --git a/EATSSU/App/Sources/Data/Notification/NotificationInboxService.swift b/EATSSU/App/Sources/Data/Notification/NotificationInboxService.swift new file mode 100644 index 00000000..465d5ad4 --- /dev/null +++ b/EATSSU/App/Sources/Data/Notification/NotificationInboxService.swift @@ -0,0 +1,58 @@ +// +// NotificationInboxService.swift +// EATSSU +// +// Created by 황상환 on 11/7/26. +// + +import Foundation + +/// 알림함 API 호출 모음. 알림함 화면, 학식 탭 알림 아이콘, 푸시 탭 읽음 처리가 함께 쓴다 +enum NotificationInboxService { + + static func fetchNotifications(completion: @escaping (Result<[NotificationItemDTO], Error>) -> Void) { + NetworkService.shared.request( + NotificationRouter.getNotifications, + responseType: [NotificationItemDTO].self, + useAuth: true, + completion: completion + ) + } + + static func fetchHasUnread(completion: @escaping (Result) -> Void) { + NetworkService.shared.request( + NotificationRouter.hasUnread, + responseType: UnreadNotificationDTO.self, + useAuth: true + ) { result in + completion(result.map { $0.hasUnread }) + } + } + + /// 읽음 처리 뒤 `.didUpdateNotificationReadState`를 보내 학식 탭 알림 아이콘이 점을 갱신하게 한다 + static func markRead(notificationId: Int, completion: ((Result) -> Void)? = nil) { + NetworkService.shared.request( + NotificationRouter.read(notificationId: notificationId), + responseType: Bool.self, + useAuth: true + ) { result in + if case .success = result { + NotificationCenter.default.post(name: .didUpdateNotificationReadState, object: nil) + } + completion?(result) + } + } + + static func markAllRead(completion: @escaping (Result) -> Void) { + NetworkService.shared.request( + NotificationRouter.readAll, + responseType: Bool.self, + useAuth: true + ) { result in + if case .success = result { + NotificationCenter.default.post(name: .didUpdateNotificationReadState, object: nil) + } + completion(result) + } + } +} diff --git a/EATSSU/App/Sources/Notification/PushRoute.swift b/EATSSU/App/Sources/Notification/PushRoute.swift index 694d4a34..a41d83ec 100644 --- a/EATSSU/App/Sources/Notification/PushRoute.swift +++ b/EATSSU/App/Sources/Notification/PushRoute.swift @@ -27,8 +27,10 @@ struct PushRoute { let date: Date /// 찜 알림에만 있다. 없으면(일반 학식 알림) 현재 시각 기준 시간대를 그대로 쓴다 let mealTime: MealTime? + /// 알림함 항목 id. 있으면 알림을 누른 시점에 읽음 처리한다 (서버가 알림함을 지원하기 전 푸시에는 없다) + let notificationId: Int? - /// 서버 푸시 data: `type`(MENU_FAVORITE / DAILY_MENU), `date`(yyyyMMdd), `timePart`(찜 알림만) + /// 서버 푸시 data: `type`(MENU_FAVORITE / DAILY_MENU), `date`(yyyyMMdd), `timePart`(찜 알림만), `notificationId`(문자열) init?(userInfo: [AnyHashable: Any]) { guard let type = userInfo["type"] as? String, Self.supportedTypes.contains(type), @@ -36,6 +38,7 @@ struct PushRoute { let date = Self.dateFormatter.date(from: dateString) else { return nil } self.date = date self.mealTime = (userInfo["timePart"] as? String).flatMap(MealTime.init(rawValue:)) + self.notificationId = (userInfo["notificationId"] as? String).flatMap(Int.init) } private static let supportedTypes: Set = ["MENU_FAVORITE", "DAILY_MENU"] @@ -90,6 +93,10 @@ final class PushRouter { guard let tabBarController = Self.currentTabBarController() else { return } self.pendingRoute = nil tabBarController.showHomeMenu(on: pending.route.date, mealTime: pending.route.mealTime) + // 푸시를 눌러 들어왔으면 알림함에서도 읽은 것으로 표시한다 + if let notificationId = pending.route.notificationId { + NotificationInboxService.markRead(notificationId: notificationId) + } } } diff --git a/EATSSU/App/Sources/Presentation/Home/ViewController/HomeViewController.swift b/EATSSU/App/Sources/Presentation/Home/ViewController/HomeViewController.swift index 77a63b42..d3728163 100644 --- a/EATSSU/App/Sources/Presentation/Home/ViewController/HomeViewController.swift +++ b/EATSSU/App/Sources/Presentation/Home/ViewController/HomeViewController.swift @@ -33,9 +33,22 @@ final class HomeViewController: BaseViewController { return imageView }() + /// 알림함 진입 버튼. 안 읽은 알림이 있으면 점이 있는 아이콘을 보여준다 + /// 디자인: 24×24 아이콘, 우측 24, 로고와 세로 중앙 정렬. 터치 영역은 44 + private let notificationButton: UIButton = { + let button = UIButton(type: .custom) + button.setImage(EATSSUDesignAsset.Images.icBell.image, for: .normal) + button.accessibilityLabel = TextLiteral.Notification.inboxTitle + button.accessibilityIdentifier = "home.notificationButton" + return button + }() + private let tabmanController = CustomTimeTabController() private let homeCalendarView = HomeCalendarView() + /// 안 읽은 알림 조회 요청마다 증가. 연달아 보낸 요청의 응답 순서가 뒤바뀌어도 마지막 요청만 배지에 반영한다 + private var unreadBadgeRequestID = 0 + // MARK: - Life Cycle override func viewDidLoad() { @@ -45,6 +58,7 @@ final class HomeViewController: BaseViewController { configureUI() setLayout() registerTabman() + addUnreadBadgeObservers() } override func viewDidAppear(_ animated: Bool) { @@ -62,6 +76,9 @@ final class HomeViewController: BaseViewController { addNewDayObserver() self.tabBarController?.tabBar.isHidden = false + // 알림함은 로그인한 사용자만 쓸 수 있어 비로그인이면 아이콘을 숨긴다 + notificationButton.isHidden = !TokenStore.hasAccessToken + refreshUnreadBadge() } override func viewWillDisappear(_ animated: Bool) { @@ -88,6 +105,7 @@ final class HomeViewController: BaseViewController { override func configureUI() { view.addSubview(logoImageView) + view.addSubview(notificationButton) view.addSubview(homeCalendarView) } @@ -98,6 +116,13 @@ final class HomeViewController: BaseViewController { make.height.equalTo(28) } + notificationButton.snp.makeConstraints { make in + make.centerY.equalTo(logoImageView) + // 44 터치 영역 안에 24 아이콘이 가운데 오므로 우측 여백 24 = 14 + 10 + make.trailing.equalToSuperview().inset(14) + make.size.equalTo(44) + } + homeCalendarView.snp.makeConstraints { make in make.top.equalTo(logoImageView.snp.bottom).offset(13) make.leading.trailing.equalToSuperview() @@ -105,6 +130,44 @@ final class HomeViewController: BaseViewController { } } + override func setButtonEvent() { + notificationButton.addTarget(self, action: #selector(didTapNotificationButton), for: .touchUpInside) + } + + // MARK: - Notification Inbox + + @objc private func didTapNotificationButton() { + navigationController?.pushViewController(NotificationInboxViewController(), animated: true) + } + + /// 안 읽은 알림 여부를 다시 확인하는 시점: 화면 진입, 앱 활성화, 사용 중 푸시 도착, 알림 읽음 처리 + private func addUnreadBadgeObservers() { + let names: [Notification.Name] = [ + UIApplication.didBecomeActiveNotification, + .didReceivePushNotification, + .didUpdateNotificationReadState + ] + names.forEach { + NotificationCenter.default.addObserver(self, selector: #selector(refreshUnreadBadge), name: $0, object: nil) + } + } + + @objc private func refreshUnreadBadge() { + // 푸시 도착(`willPresent`) 알림은 메인 큐 호출이 보장되지 않아 메인으로 옮긴다 + guard Thread.isMainThread else { + DispatchQueue.main.async { self.refreshUnreadBadge() } + return + } + guard TokenStore.hasAccessToken else { return } + unreadBadgeRequestID += 1 + let requestID = unreadBadgeRequestID + NotificationInboxService.fetchHasUnread { [weak self] result in + guard let self, requestID == self.unreadBadgeRequestID, case .success(let hasUnread) = result else { return } + let image = hasUnread ? EATSSUDesignAsset.Images.icBellUnread.image : EATSSUDesignAsset.Images.icBell.image + self.notificationButton.setImage(image, for: .normal) + } + } + // MARK: - Tabman Setup private func registerTabman() { diff --git a/EATSSU/App/Sources/Presentation/Notification/NotificationTimeDisplay.swift b/EATSSU/App/Sources/Presentation/Notification/NotificationTimeDisplay.swift new file mode 100644 index 00000000..b311500d --- /dev/null +++ b/EATSSU/App/Sources/Presentation/Notification/NotificationTimeDisplay.swift @@ -0,0 +1,57 @@ +// +// NotificationTimeDisplay.swift +// EATSSU +// +// Created by 황상환 on 11/7/26. +// + +import Foundation + +/// 알림 생성 시각 표시 규칙. 하루가 안 지난 알림은 "n시간 전", 하루가 지난 알림은 "n월 n일" +enum NotificationTimeDisplay: Equatable { + /// 1시간 미만 + case justNow + /// 1시간 이상 24시간 미만 + case hoursAgo(Int) + /// 24시간 이상. 앱 언어로 "7월 26일" 형태 + case date(String) + + /// - Parameters: + /// - createdAt: 서버 `createdAt` (`yyyy-MM-dd'T'HH:mm:ss`, 한국 시간, 타임존 표기 없음) + /// - now: 비교 기준 시각 + /// - locale: 날짜 표기 언어 + /// - Returns: 파싱에 실패하면 nil + static func make(createdAt: String, now: Date = Date(), locale: Locale) -> NotificationTimeDisplay? { + guard let created = Self.parse(createdAt) else { return nil } + let elapsed = now.timeIntervalSince(created) + if elapsed < 3600 { + return .justNow + } + if elapsed < 24 * 3600 { + return .hoursAgo(Int(elapsed / 3600)) + } + let formatter = DateFormatter() + formatter.locale = locale + formatter.timeZone = Self.serverTimeZone + formatter.setLocalizedDateFormatFromTemplate("MMMd") + return .date(formatter.string(from: created)) + } + + /// 서버는 한국 시간을 타임존 없이 내려주므로 한국 시간으로 해석한다 + private static let serverTimeZone = TimeZone(identifier: "Asia/Seoul") ?? .current + + private static let parser: DateFormatter = { + let formatter = DateFormatter() + formatter.calendar = Calendar(identifier: .gregorian) + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.timeZone = serverTimeZone + formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss" + return formatter + }() + + private static func parse(_ string: String) -> Date? { + // 소수점 초(`11:00:00.123`)가 붙어 와도 읽을 수 있게 잘라낸다 + let trimmed = string.split(separator: ".", maxSplits: 1).first.map(String.init) ?? string + return parser.date(from: trimmed) + } +} diff --git a/EATSSU/App/Sources/Presentation/Notification/View/NotificationCell.swift b/EATSSU/App/Sources/Presentation/Notification/View/NotificationCell.swift new file mode 100644 index 00000000..986494a0 --- /dev/null +++ b/EATSSU/App/Sources/Presentation/Notification/View/NotificationCell.swift @@ -0,0 +1,120 @@ +// +// NotificationCell.swift +// EATSSU +// +// Created by 황상환 on 11/7/26. +// + +import UIKit + +import SnapKit + +import EATSSUDesign + +/// 알림함 한 줄: 확성기 아이콘 · 제목 · 시각 · 본문. 안 읽은 알림은 민트 배경 +/// +/// 디자인(390 기준): 행 높이 84(본문 한 줄), 아이콘 원 35 좌측 24, 글 시작 76, 제목 Bold 14, 본문·시각 12, 우측 24 +/// 제목·본문은 길어도 말줄임 없이 다음 줄로 넘긴다 +final class NotificationCell: UITableViewCell { + + // MARK: - Constants + + static let identifier = "NotificationCell" + + private enum Layout { + static let horizontalInset: CGFloat = 24 + static let verticalInset: CGFloat = 20 + static let iconSize: CGFloat = 35 + static let iconImageSize = CGSize(width: 20, height: 16) + static let textLeading: CGFloat = 76 + static let titleBodySpacing: CGFloat = 13 + static let titleTimeSpacing: CGFloat = 8 + } + + // MARK: - UI Components + + private let iconContainerView = UIView() + private let iconImageView = UIImageView(image: EATSSUDesignAsset.Images.icMegaphone.image) + private let titleLabel = UILabel() + private let timeLabel = UILabel() + private let bodyLabel = UILabel() + + // MARK: - Init + + override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { + super.init(style: style, reuseIdentifier: reuseIdentifier) + configureUI() + setLayout() + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + // MARK: - View Setup + + private func configureUI() { + selectionStyle = .none + + iconContainerView.backgroundColor = .white + iconContainerView.layer.cornerRadius = Layout.iconSize / 2 + iconContainerView.layer.borderWidth = 1 + iconContainerView.layer.borderColor = UIColor.primary.cgColor + iconContainerView.clipsToBounds = true + iconImageView.contentMode = .scaleAspectFit + + titleLabel.font = EATSSUDesignFontFamily.Pretendard.bold.font(size: 14) + titleLabel.textColor = .gray700 + titleLabel.numberOfLines = 0 + + timeLabel.font = .caption2 + timeLabel.textColor = .gray600 + timeLabel.setContentCompressionResistancePriority(.required, for: .horizontal) + timeLabel.setContentHuggingPriority(.required, for: .horizontal) + + bodyLabel.font = .caption2 + bodyLabel.textColor = .gray600 + bodyLabel.numberOfLines = 0 + + iconContainerView.addSubview(iconImageView) + contentView.addSubviews(iconContainerView, titleLabel, timeLabel, bodyLabel) + } + + private func setLayout() { + iconContainerView.snp.makeConstraints { + $0.leading.equalToSuperview().inset(Layout.horizontalInset) + $0.centerY.equalToSuperview() + $0.size.equalTo(Layout.iconSize) + } + iconImageView.snp.makeConstraints { + $0.center.equalToSuperview() + $0.size.equalTo(Layout.iconImageSize) + } + titleLabel.snp.makeConstraints { + $0.top.equalToSuperview().inset(Layout.verticalInset) + $0.leading.equalToSuperview().inset(Layout.textLeading) + $0.trailing.lessThanOrEqualTo(timeLabel.snp.leading).offset(-Layout.titleTimeSpacing) + } + timeLabel.snp.makeConstraints { + $0.firstBaseline.equalTo(titleLabel.snp.firstBaseline) + $0.trailing.equalToSuperview().inset(Layout.horizontalInset) + } + bodyLabel.snp.makeConstraints { + $0.top.equalTo(titleLabel.snp.bottom).offset(Layout.titleBodySpacing) + $0.leading.equalTo(titleLabel) + $0.trailing.equalToSuperview().inset(Layout.horizontalInset) + $0.bottom.equalToSuperview().inset(Layout.verticalInset) + } + } + + // MARK: - Configuration + + func configure(title: String, body: String, time: String?, isRead: Bool) { + titleLabel.text = title + bodyLabel.text = body + timeLabel.text = time + contentView.backgroundColor = isRead ? .white : .secondary + backgroundColor = contentView.backgroundColor + } +} diff --git a/EATSSU/App/Sources/Presentation/Notification/ViewController/NotificationInboxViewController.swift b/EATSSU/App/Sources/Presentation/Notification/ViewController/NotificationInboxViewController.swift new file mode 100644 index 00000000..9983bb1a --- /dev/null +++ b/EATSSU/App/Sources/Presentation/Notification/ViewController/NotificationInboxViewController.swift @@ -0,0 +1,234 @@ +// +// NotificationInboxViewController.swift +// EATSSU +// +// Created by 황상환 on 11/7/26. +// + +import UIKit + +import SnapKit + +import EATSSUDesign + +/// 알림함: 최근 7일 찜 메뉴 알림 목록 · 모두 읽음 · 알림을 누르면 해당 날짜·시간대의 학식 화면으로 이동 +/// +/// 삭제는 없고 7일이 지나면 서버가 지운다. 이미 읽은 알림을 눌러도 이동한다 +final class NotificationInboxViewController: BaseViewController { + + // MARK: - Constants + + /// 디자인: 상단 "모두 읽음" 영역 높이 40, 좌우 24, 하단 안내 문구는 안전 영역 위 22 + private enum Layout { + static let headerHeight: CGFloat = 40 + static let horizontalInset: CGFloat = 24 + static let noticeBottomInset: CGFloat = 22 + static let estimatedRowHeight: CGFloat = 84 + } + + override var shouldHideTabBar: Bool { true } + + // MARK: - Properties + + private var notifications: [NotificationItemDTO] = [] + private var hasLoaded = false + + private var hasUnread: Bool { + notifications.contains { !$0.isRead } + } + + // MARK: - UI Components + + private let readAllButton = UIButton(type: .system) + private let tableView = UITableView(frame: .zero, style: .plain) + private let emptyView = EmptyStateView() + private let noticeLabel = UILabel() + + // MARK: - Life Cycle + + override func viewDidLoad() { + super.viewDidLoad() + loadNotifications() + } + + // MARK: - View Setup + + override func configureUI() { + view.backgroundColor = .white + + readAllButton.setTitle(TextLiteral.Notification.readAll, for: .normal) + readAllButton.titleLabel?.font = .body2 + readAllButton.setTitleColor(.gray600, for: .normal) + readAllButton.setTitleColor(.gray300, for: .disabled) + readAllButton.isEnabled = false + + tableView.register(NotificationCell.self, forCellReuseIdentifier: NotificationCell.identifier) + tableView.dataSource = self + tableView.delegate = self + tableView.separatorStyle = .none + tableView.rowHeight = UITableView.automaticDimension + tableView.estimatedRowHeight = Layout.estimatedRowHeight + tableView.tableFooterView = UIView() + tableView.showsVerticalScrollIndicator = false + + emptyView.configure(title: TextLiteral.Notification.emptyTitle, subtitle: TextLiteral.Notification.emptySubtitle) + emptyView.isHidden = true + + noticeLabel.text = TextLiteral.Notification.retentionNotice + noticeLabel.font = .caption2 + noticeLabel.textColor = .gray500 + noticeLabel.textAlignment = .center + noticeLabel.isHidden = true + + view.addSubviews(readAllButton, tableView, emptyView, noticeLabel) + } + + override func setLayout() { + readAllButton.snp.makeConstraints { + $0.top.equalTo(view.safeAreaLayoutGuide) + $0.trailing.equalToSuperview().inset(Layout.horizontalInset) + $0.height.equalTo(Layout.headerHeight) + } + tableView.snp.makeConstraints { + $0.top.equalTo(readAllButton.snp.bottom) + $0.leading.trailing.bottom.equalToSuperview() + } + emptyView.snp.makeConstraints { + $0.edges.equalTo(tableView) + } + noticeLabel.snp.makeConstraints { + $0.centerX.equalToSuperview() + $0.leading.trailing.equalToSuperview().inset(Layout.horizontalInset) + $0.bottom.equalTo(view.safeAreaLayoutGuide).inset(Layout.noticeBottomInset) + } + } + + override func setButtonEvent() { + readAllButton.addTarget(self, action: #selector(didTapReadAll), for: .touchUpInside) + } + + override func setCustomNavigationBar() { + super.setCustomNavigationBar() + navigationItem.title = TextLiteral.Notification.inboxTitle + } + + // MARK: - Data + + private func loadNotifications() { + NotificationInboxService.fetchNotifications { [weak self] result in + guard let self else { return } + switch result { + case .success(let notifications): + self.notifications = notifications + self.hasLoaded = true + case .failure(let error): + print("알림 목록 조회 실패: \(error.localizedDescription)") + self.showToast(message: TextLiteral.Notification.loadFailed, type: .danger) + } + self.render() + } + } + + private func render() { + let isEmpty = hasLoaded && notifications.isEmpty + emptyView.isHidden = !isEmpty + tableView.isHidden = isEmpty + noticeLabel.isHidden = notifications.isEmpty + // 디자인: 알림이 없으면 "모두 읽음"도 보이지 않는다 + readAllButton.isHidden = notifications.isEmpty + readAllButton.isEnabled = hasUnread + // 마지막 행이 하단 안내 문구에 가리지 않게 한다 + let noticeHeight = noticeLabel.intrinsicContentSize.height + Layout.noticeBottomInset * 2 + tableView.contentInset.bottom = notifications.isEmpty ? 0 : noticeHeight + tableView.reloadData() + } + + // MARK: - Actions + + @objc private func didTapReadAll() { + notifications = notifications.map { Self.marked($0, isRead: true) } + render() + NotificationInboxService.markAllRead { [weak self] result in + guard let self, case .failure(let error) = result else { return } + print("알림 모두 읽음 실패: \(error.localizedDescription)") + // 요청 중에 개별 읽음 처리가 끼어들 수 있어, 이전 화면 상태로 되돌리는 대신 서버 상태를 다시 받는다 + self.loadNotifications() + } + } + + /// 알림을 누르면 읽음 처리하고 학식 탭의 해당 날짜·시간대로 이동한다. 읽음 처리 실패는 이동을 막지 않는다 + private func open(_ notification: NotificationItemDTO, at indexPath: IndexPath) { + if !notification.isRead { + notifications[indexPath.row] = Self.marked(notification, isRead: true) + render() + NotificationInboxService.markRead(notificationId: notification.notificationId) + } + // 푸시 data와 같은 형태로 만들어 푸시 탭과 같은 이동 규칙을 쓴다 + var userInfo: [AnyHashable: Any] = ["type": notification.type, "date": notification.date] + if let timePart = notification.timePart { + userInfo["timePart"] = timePart + } + guard let route = PushRoute(userInfo: userInfo), + let tabBarController = tabBarController as? CustomTabBarContainerController else { return } + tabBarController.showHomeMenu(on: route.date, mealTime: route.mealTime) + } + + private static func marked(_ notification: NotificationItemDTO, isRead: Bool) -> NotificationItemDTO { + NotificationItemDTO( + notificationId: notification.notificationId, + type: notification.type, + title: notification.title, + body: notification.body, + date: notification.date, + timePart: notification.timePart, + isRead: isRead, + createdAt: notification.createdAt + ) + } + + private func timeText(for notification: NotificationItemDTO) -> String? { + let locale = Locale(identifier: AppLanguageManager.shared.currentLanguage.rawValue) + switch NotificationTimeDisplay.make(createdAt: notification.createdAt, locale: locale) { + case .justNow: + return TextLiteral.Notification.justNow + case .hoursAgo(let hours): + return TextLiteral.Notification.hoursAgo(hours) + case .date(let text): + return text + case nil: + return nil + } + } +} + +// MARK: - UITableViewDataSource + +extension NotificationInboxViewController: UITableViewDataSource { + + func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + notifications.count + } + + func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { + guard let cell = tableView.dequeueReusableCell(withIdentifier: NotificationCell.identifier, for: indexPath) as? NotificationCell else { + return UITableViewCell() + } + let notification = notifications[indexPath.row] + cell.configure( + title: notification.title, + body: notification.body, + time: timeText(for: notification), + isRead: notification.isRead + ) + return cell + } +} + +// MARK: - UITableViewDelegate + +extension NotificationInboxViewController: UITableViewDelegate { + + func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { + open(notifications[indexPath.row], at: indexPath) + } +} diff --git a/EATSSU/App/Sources/Utility/Application/AppDelegate.swift b/EATSSU/App/Sources/Utility/Application/AppDelegate.swift index 57344a38..f3fabb42 100644 --- a/EATSSU/App/Sources/Utility/Application/AppDelegate.swift +++ b/EATSSU/App/Sources/Utility/Application/AppDelegate.swift @@ -228,6 +228,8 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD extension AppDelegate { // Foreground에서도 알림이 보이도록 설정 func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { + // 앱 사용 중에 알림이 오면 학식 탭 알림 아이콘에 점을 띄운다 + NotificationCenter.default.post(name: .didReceivePushNotification, object: nil) completionHandler([.banner, .sound, .badge]) } } diff --git a/EATSSU/App/Sources/Utility/Extension/Notification+.swift b/EATSSU/App/Sources/Utility/Extension/Notification+.swift index 2aa13918..38d79de0 100644 --- a/EATSSU/App/Sources/Utility/Extension/Notification+.swift +++ b/EATSSU/App/Sources/Utility/Extension/Notification+.swift @@ -9,5 +9,9 @@ import Foundation extension Notification.Name { static let didEnterNewDay = Notification.Name("didEnterNewDay") + /// 앱 사용 중(포그라운드)에 푸시가 도착함. 학식 탭 알림 아이콘이 안 읽은 알림 여부를 다시 확인한다 + static let didReceivePushNotification = Notification.Name("didReceivePushNotification") + /// 알림을 읽음 처리함 (알림함·모두 읽음·푸시 탭). 학식 탭 알림 아이콘이 점을 갱신한다 + static let didUpdateNotificationReadState = Notification.Name("didUpdateNotificationReadState") // 추가 알림 이름도 여기 모아서 관리 } diff --git a/EATSSU/App/Sources/Utility/Literal/TextLiteral.swift b/EATSSU/App/Sources/Utility/Literal/TextLiteral.swift index 9e93ad85..2b7c5357 100644 --- a/EATSSU/App/Sources/Utility/Literal/TextLiteral.swift +++ b/EATSSU/App/Sources/Utility/Literal/TextLiteral.swift @@ -1233,6 +1233,48 @@ enum TextLiteral { fallback: "다시 시도해주세요." ) } + + // MARK: 알림함 + + /// "알림" + static var inboxTitle: String { + Localization.localized("notification.inboxTitle", fallback: "알림") + } + + /// "모두 읽음" + static var readAll: String { + Localization.localized("notification.readAll", fallback: "모두 읽음") + } + + /// "새로운 알림이 없어요." + static var emptyTitle: String { + Localization.localized("notification.emptyTitle", fallback: "새로운 알림이 없어요.") + } + + /// "찜한 메뉴가 나오면 알림으로 알려드릴게요!" + static var emptySubtitle: String { + Localization.localized("notification.emptySubtitle", fallback: "찜한 메뉴가 나오면 알림으로 알려드릴게요!") + } + + /// "7일 전 알림까지 확인할 수 있어요" + static var retentionNotice: String { + Localization.localized("notification.retentionNotice", fallback: "7일 전 알림까지 확인할 수 있어요") + } + + /// "방금 전" (1시간 미만) + static var justNow: String { + Localization.localized("notification.justNow", fallback: "방금 전") + } + + /// "%d시간 전" (하루 미만) + static func hoursAgo(_ hours: Int) -> String { + Localization.formatted("notification.hoursAgo", fallback: "%d시간 전", hours) + } + + /// "알림을 불러오지 못했어요." + static var loadFailed: String { + Localization.localized("notification.loadFailed", fallback: "알림을 불러오지 못했어요.") + } } // MARK: - Restaurant diff --git a/EATSSU/Tests/UnitTests/NotificationTimeDisplayTests.swift b/EATSSU/Tests/UnitTests/NotificationTimeDisplayTests.swift new file mode 100644 index 00000000..7008d819 --- /dev/null +++ b/EATSSU/Tests/UnitTests/NotificationTimeDisplayTests.swift @@ -0,0 +1,45 @@ +// +// NotificationTimeDisplayTests.swift +// EATSSUUnitTests +// +// Created by 황상환 on 11/7/26. +// + +import XCTest + +@testable import EATSSU_DEV + +/// 알림함 시각 표시 규칙: 하루 미만 "n시간 전", 하루 이상 "n월 n일" +final class NotificationTimeDisplayTests: XCTestCase { + + private let korean = Locale(identifier: "ko") + + /// 한국 시간 2026-07-27 12:00 + private let now: Date = { + var components = DateComponents() + components.calendar = Calendar(identifier: .gregorian) + components.timeZone = TimeZone(identifier: "Asia/Seoul") + components.year = 2026; components.month = 7; components.day = 27; components.hour = 12 + return components.date! + }() + + func test_한_시간_미만은_방금_전() { + XCTAssertEqual(NotificationTimeDisplay.make(createdAt: "2026-07-27T11:30:00", now: now, locale: korean), .justNow) + } + + func test_하루_미만은_시간_단위로_내림() { + XCTAssertEqual(NotificationTimeDisplay.make(createdAt: "2026-07-27T11:00:00", now: now, locale: korean), .hoursAgo(1)) + XCTAssertEqual(NotificationTimeDisplay.make(createdAt: "2026-07-26T12:30:00", now: now, locale: korean), .hoursAgo(23)) + } + + func test_하루_이상은_앱_언어의_월일로_표시() { + XCTAssertEqual(NotificationTimeDisplay.make(createdAt: "2026-07-26T11:00:00", now: now, locale: korean), .date("7월 26일")) + XCTAssertEqual(NotificationTimeDisplay.make(createdAt: "2026-07-22T11:00:00", now: now, locale: Locale(identifier: "en")), .date("Jul 22")) + XCTAssertEqual(NotificationTimeDisplay.make(createdAt: "2026-07-22T11:00:00", now: now, locale: Locale(identifier: "ja")), .date("7月22日")) + } + + func test_소수점_초가_붙어도_읽고_형식이_다르면_nil() { + XCTAssertEqual(NotificationTimeDisplay.make(createdAt: "2026-07-27T11:30:00.123456", now: now, locale: korean), .justNow) + XCTAssertNil(NotificationTimeDisplay.make(createdAt: "2026-07-27 11:30", now: now, locale: korean)) + } +} diff --git a/EATSSU/Tests/UnitTests/PushRouteTests.swift b/EATSSU/Tests/UnitTests/PushRouteTests.swift index 8183bedc..d7a4de23 100644 --- a/EATSSU/Tests/UnitTests/PushRouteTests.swift +++ b/EATSSU/Tests/UnitTests/PushRouteTests.swift @@ -40,4 +40,15 @@ final class PushRouteTests: XCTestCase { let route = try XCTUnwrap(PushRoute(userInfo: ["type": "MENU_FAVORITE", "date": "20261005", "timePart": "BRUNCH"])) XCTAssertNil(route.mealTime) } + + func test_알림함_id는_문자열로_오며_없거나_이상하면_비운다() throws { + let withId = try XCTUnwrap(PushRoute(userInfo: ["type": "MENU_FAVORITE", "date": "20261005", "timePart": "LUNCH", "notificationId": "42"])) + XCTAssertEqual(withId.notificationId, 42) + + let withoutId = try XCTUnwrap(PushRoute(userInfo: ["type": "MENU_FAVORITE", "date": "20261005"])) + XCTAssertNil(withoutId.notificationId) + + let invalidId = try XCTUnwrap(PushRoute(userInfo: ["type": "MENU_FAVORITE", "date": "20261005", "notificationId": "abc"])) + XCTAssertNil(invalidId.notificationId) + } } diff --git a/EATSSUDesign/EATSSUDesign/Resources/Images.xcassets/ic_bell.imageset/Contents.json b/EATSSUDesign/EATSSUDesign/Resources/Images.xcassets/ic_bell.imageset/Contents.json new file mode 100644 index 00000000..baf63caf --- /dev/null +++ b/EATSSUDesign/EATSSUDesign/Resources/Images.xcassets/ic_bell.imageset/Contents.json @@ -0,0 +1,15 @@ +{ + "images" : [ + { + "filename" : "ic_bell.svg", + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + }, + "properties" : { + "preserves-vector-representation" : true + } +} diff --git a/EATSSUDesign/EATSSUDesign/Resources/Images.xcassets/ic_bell.imageset/ic_bell.svg b/EATSSUDesign/EATSSUDesign/Resources/Images.xcassets/ic_bell.imageset/ic_bell.svg new file mode 100644 index 00000000..d9518925 --- /dev/null +++ b/EATSSUDesign/EATSSUDesign/Resources/Images.xcassets/ic_bell.imageset/ic_bell.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/EATSSUDesign/EATSSUDesign/Resources/Images.xcassets/ic_bell_unread.imageset/Contents.json b/EATSSUDesign/EATSSUDesign/Resources/Images.xcassets/ic_bell_unread.imageset/Contents.json new file mode 100644 index 00000000..bcc29205 --- /dev/null +++ b/EATSSUDesign/EATSSUDesign/Resources/Images.xcassets/ic_bell_unread.imageset/Contents.json @@ -0,0 +1,15 @@ +{ + "images" : [ + { + "filename" : "ic_bell_unread.svg", + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + }, + "properties" : { + "preserves-vector-representation" : true + } +} diff --git a/EATSSUDesign/EATSSUDesign/Resources/Images.xcassets/ic_bell_unread.imageset/ic_bell_unread.svg b/EATSSUDesign/EATSSUDesign/Resources/Images.xcassets/ic_bell_unread.imageset/ic_bell_unread.svg new file mode 100644 index 00000000..2bd6d765 --- /dev/null +++ b/EATSSUDesign/EATSSUDesign/Resources/Images.xcassets/ic_bell_unread.imageset/ic_bell_unread.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/EATSSUDesign/EATSSUDesign/Resources/Images.xcassets/ic_megaphone.imageset/Contents.json b/EATSSUDesign/EATSSUDesign/Resources/Images.xcassets/ic_megaphone.imageset/Contents.json new file mode 100644 index 00000000..b7d06b0d --- /dev/null +++ b/EATSSUDesign/EATSSUDesign/Resources/Images.xcassets/ic_megaphone.imageset/Contents.json @@ -0,0 +1,15 @@ +{ + "images" : [ + { + "filename" : "ic_megaphone.svg", + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + }, + "properties" : { + "preserves-vector-representation" : true + } +} diff --git a/EATSSUDesign/EATSSUDesign/Resources/Images.xcassets/ic_megaphone.imageset/ic_megaphone.svg b/EATSSUDesign/EATSSUDesign/Resources/Images.xcassets/ic_megaphone.imageset/ic_megaphone.svg new file mode 100644 index 00000000..414b5627 --- /dev/null +++ b/EATSSUDesign/EATSSUDesign/Resources/Images.xcassets/ic_megaphone.imageset/ic_megaphone.svg @@ -0,0 +1,5 @@ + + + + +