Repository Public
1// SP Notes Core2// File: Sources/SPNotesFeatures/Knowledge/DailyBriefScreen.swift3// Description: The brief of the day: recent notes, active projects, tasks due, unfiled captures, link suggestions (AI,4// marked), pages to revisit. Computed by the server without a model; the AI summary is requested only by an5// explicit tap (one paid call) and shown under the AI badge.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import Foundation10import Observation11import SPNotesAPI12import SPNotesDesign13import SPNotesSync14import SwiftUI1516/// A suggested page ↔ page link of the brief (decoded leniently: the brief carries the edge keys and titles).17public struct BriefLinkSuggestion: Decodable, Sendable, Equatable, Identifiable {18 public var id: String19 public var fromId: String?20 public var toId: String?21 public var fromTitle: String?22 public var toTitle: String?23 public var rationale: String?24 public var confidence: Double?25 public var model: String?26}2728/// A connected page nobody opened for a while.29public struct BriefRevisit: Decodable, Sendable, Equatable, Identifiable {30 public var id: String31 public var title: String?32 public var icon: String?33 public var updatedAt: Date?34 public var degree: Int?35}3637@Observable @MainActor38public final class DailyBriefModel {39 public private(set) var brief: DailyBrief?40 public private(set) var phase: LoadPhase = .idle41 public private(set) var freshness: Freshness?42 /// The AI summary: the last one the server kept, or the one just requested. Never requested automatically.43 public private(set) var summary: BriefSummary?44 public private(set) var isSummarizing = false45 public var actionFailure: FeatureFailure?4647 private let repository: KnowledgeRepository48 private weak var router: (any FeatureRouter)?49 private let timeZone: TimeZone5051 public init(repositories: NotesRepositories, router: (any FeatureRouter)? = nil, timeZone: TimeZone = .current, now: @escaping @Sendable () -> Date = { Date() }) {52 repository = repositories.knowledge53 self.router = router54 self.timeZone = timeZone55 }5657 public func load() async {58 phase = .loading59 do {60 let cached = try await repository.brief(timeZone: timeZone)61 brief = cached.value62 if let stored = cached.value.aiSummary { summary = stored }63 freshness = Freshness(cached)64 phase = .loaded65 } catch {66 phase = .failed(FeatureFailure(error))67 }68 }6970 /// One paid model call — only from the explicit button.71 @discardableResult72 public func requestSummary() async -> Bool {73 guard !isSummarizing else { return false }74 isSummarizing = true75 actionFailure = nil76 defer { isSummarizing = false }77 do {78 summary = try await repository.summarizeBrief(timeZone: timeZone)79 return true80 } catch {81 actionFailure = FeatureFailure(error)82 return false83 }84 }8586 public var linkSuggestions: [BriefLinkSuggestion] { (brief?.linkSuggestions.items ?? []).compactMap { try? $0.decode(BriefLinkSuggestion.self) } }87 public var toRevisit: [BriefRevisit] { (brief?.toRevisit ?? []).compactMap { try? $0.decode(BriefRevisit.self) } }8889 public var taskCount: Int {90 guard let tasks = brief?.tasks else { return 0 }91 return tasks.overdue.count + tasks.dueToday.count + tasks.dueSoon.count92 }9394 /// Nothing at all to show (a brand-new workspace).95 public var isEmpty: Bool {96 guard let brief else { return true }97 return brief.recentNotes.isEmpty && brief.activeProjects.isEmpty && taskCount == 0 && brief.unfiledCaptures.count == 0 && brief.linkSuggestions.count == 0 && brief.toRevisit.isEmpty98 }99100 /// The brief's day (`date` is a calendar day in the brief's time zone), formatted long.101 public var dayTitle: String {102 guard let brief else { return "" }103 let parser = DateFormatter()104 parser.calendar = Calendar(identifier: .gregorian)105 parser.locale = Locale(identifier: "en_US_POSIX")106 parser.timeZone = TimeZone(identifier: "UTC")107 parser.dateFormat = "yyyy-MM-dd"108 guard let date = parser.date(from: brief.date) else { return brief.date }109 var style = Date.FormatStyle(date: .complete, time: .omitted)110 style.timeZone = TimeZone(identifier: "UTC") ?? .current111 style.locale = FeatureStrings.locale112 return date.formatted(style)113 }114115 public func open(note: BriefNote) {116 if note.type == "database" { router?.openDatabase(id: note.id) } else if note.type == "canvas" { router?.openCanvas(pageId: note.id) } else { router?.openPage(id: note.id, blockId: nil) }117 }118119 public func open(task: BriefTask) {120 guard let pageId = task.pageId else { return }121 router?.openPage(id: pageId, blockId: task.blockId)122 }123124 public func open(pageId: String) { router?.openPage(id: pageId, blockId: nil) }125126 /// A bare due day is noon UTC on the server: show the UTC calendar day.127 public nonisolated static func due(_ task: BriefTask) -> String? {128 task.dueAt.map { FeatureFormat.day($0, timeZone: TimeZone(identifier: "UTC") ?? .current) }129 }130}131132public struct DailyBriefScreen: View {133 @State private var model: DailyBriefModel134135 public init(repositories: NotesRepositories, router: (any FeatureRouter)? = nil) {136 _model = State(initialValue: DailyBriefModel(repositories: repositories, router: router))137 }138139 public init(model: DailyBriefModel) { _model = State(initialValue: model) }140141 public var body: some View {142 FeatureScaffold(title: L("Brief du jour"), subtitle: model.dayTitle.isEmpty ? nil : model.dayTitle, phase: model.phase, freshness: model.freshness,143 retry: { Task { await model.load() } },144 actions: { FeatureIconButton("arrow.clockwise", label: L("Actualiser")) { Task { await model.load() } } }) { sizeClass in145 FeaturePhaseView(phase: model.phase, hasData: model.brief != nil, retry: { Task { await model.load() } }) {146 EmptyView()147 } content: {148 if let brief = model.brief {149 ScrollView {150 VStack(alignment: .leading, spacing: NVSpace.lg) {151 summaryCard152 if model.isEmpty {153 NVEmptyState(systemImage: "sun.max", title: L("Rien de particulier aujourd'hui"), message: L("Vos notes récentes, vos tâches et vos captures à classer apparaîtront ici."))154 .frame(maxWidth: .infinity).padding(.vertical, NVSpace.xxl)155 } else if sizeClass.isCompact {156 tasks(brief); captures(brief); notes(brief); projects(brief); suggestions; revisit157 } else {158 HStack(alignment: .top, spacing: NVSpace.lg) {159 VStack(spacing: NVSpace.lg) { tasks(brief); captures(brief); suggestions }160 VStack(spacing: NVSpace.lg) { notes(brief); projects(brief); revisit }161 }162 }163 }164 .padding(.horizontal, sizeClass.isCompact ? NVSpace.lg : NVSpace.xl)165 .padding(.bottom, NVSpace.xl)166 }167 }168 }169 }170 .task { if model.phase == .idle { await model.load() } }171 }172173 @ViewBuilder174 private var summaryCard: some View {175 if let summary = model.summary {176 FeatureAICard(model: summary.model, title: L("Résumé du jour")) {177 Text(summary.text).nvFont(.reading).foregroundStyle(NVColor.fg).fixedSize(horizontal: false, vertical: true)178 if let at = summary.at { Text(LF("Demandé le %@", FeatureFormat.dayTime(at))).nvFont(.micro).foregroundStyle(NVColor.fgMuted) }179 if model.isSummarizing { NVProgressDots(tone: .ai) } else { FeatureButton(L("Régénérer (payant)"), systemImage: "arrow.clockwise", kind: .ai) { Task { await model.requestSummary() } } }180 }181 } else {182 VStack(alignment: .leading, spacing: NVSpace.sm) {183 HStack(spacing: NVSpace.sm) { NVAIBadge(style: .compact); Text(L("Résumé par l'IA")).nvFont(.uiStrong).foregroundStyle(NVColor.fg) }184 Text(L("Le brief ci-dessous est calculé sans modèle. Un résumé rédigé par l'IA n'est demandé que si vous le voulez : un appel payant.")).nvFont(.ui).foregroundStyle(NVColor.fgMuted)185 if model.isSummarizing { NVProgressDots(tone: .ai) } else { FeatureButton(L("Résumer avec l'IA (payant)"), systemImage: "sparkles", kind: .ai) { Task { await model.requestSummary() } } }186 }187 .padding(NVSpace.lg)188 .frame(maxWidth: .infinity, alignment: .leading)189 .nvCard()190 }191 if let failure = model.actionFailure { FeatureStatusBanner(failure: failure, freshness: nil) }192 }193194 @ViewBuilder195 private func tasks(_ brief: DailyBrief) -> some View {196 KnowledgeSection(title: L("Tâches"), count: model.taskCount, tone: brief.tasks.overdue.isEmpty ? .accent : .danger) {197 if model.taskCount == 0 { Label(L("Rien à faire dans les sept prochains jours."), systemImage: "checkmark.circle").nvFont(.ui).foregroundStyle(NVColor.fgMuted) }198 taskGroup(L("En retard"), brief.tasks.overdue, tint: NVColor.danger, symbol: "exclamationmark.circle")199 taskGroup(L("Aujourd'hui"), brief.tasks.dueToday, tint: NVColor.accent, symbol: "circle")200 taskGroup(L("Bientôt"), brief.tasks.dueSoon, tint: NVColor.fgMuted, symbol: "circle")201 }202 }203204 @ViewBuilder205 private func taskGroup(_ title: String, _ tasks: [BriefTask], tint: Color, symbol: String) -> some View {206 if !tasks.isEmpty {207 Text(title).nvFont(.micro).foregroundStyle(NVColor.fgMuted).padding(.top, NVSpace.xs)208 ForEach(tasks) { task in209 KnowledgeRow(symbol: symbol, tint: tint, title: task.title,210 detail: [DailyBriefModel.due(task), task.pageTitle.map { KnowledgeVocabulary.title($0) }, KnowledgeVocabulary.priorityTitle(task.priority)].compactMap { $0 }.joined(separator: " · "),211 action: task.pageId == nil ? nil : { model.open(task: task) })212 }213 }214 }215216 @ViewBuilder217 private func captures(_ brief: DailyBrief) -> some View {218 if brief.unfiledCaptures.count > 0 {219 KnowledgeSection(title: L("Captures à classer"), count: brief.unfiledCaptures.count, tone: .accent) {220 ForEach(brief.unfiledCaptures.items) { capture in221 KnowledgeRow(symbol: "tray", icon: capture.icon, title: KnowledgeVocabulary.title(capture.title), detail: capture.inboxAt.map { FeatureFormat.dayTime($0) },222 action: { model.open(pageId: capture.id) })223 }224 }225 }226 }227228 @ViewBuilder229 private func notes(_ brief: DailyBrief) -> some View {230 if !brief.recentNotes.isEmpty {231 KnowledgeSection(title: L("Notes récentes"), count: brief.recentNotes.count) {232 ForEach(brief.recentNotes) { note in233 KnowledgeRow(symbol: note.type == "database" ? "tablecells" : (note.type == "canvas" ? "rectangle.3.group" : "doc.text"), icon: note.icon, tint: NVColor.accent,234 title: KnowledgeVocabulary.title(note.title),235 detail: [note.updatedAt.map { FeatureFormat.dayTime($0) }, note.wordCount.flatMap { $0 > 0 ? LF("%lld mots", $0) : nil }].compactMap { $0 }.joined(separator: " · "),236 action: { model.open(note: note) })237 }238 }239 }240 }241242 @ViewBuilder243 private func projects(_ brief: DailyBrief) -> some View {244 if !brief.activeProjects.isEmpty {245 KnowledgeSection(title: L("Projets actifs"), count: brief.activeProjects.count) {246 ForEach(brief.activeProjects) { project in247 KnowledgeRow(symbol: "folder", icon: project.icon, tint: NVColor.accent, title: KnowledgeVocabulary.title(project.title),248 detail: [project.pages.map { LF("%lld pages", $0) }, project.openTasks.map { LF("%lld tâche(s) ouverte(s)", $0) }].compactMap { $0 }.joined(separator: " · "),249 action: { model.open(pageId: project.id) })250 }251 }252 }253 }254255 @ViewBuilder256 private var suggestions: some View {257 let list = model.linkSuggestions258 if !list.isEmpty {259 FeatureAICard(title: L("Liens suggérés")) {260 Text(L("Des suggestions à décider dans le graphe : rien n'est relié sans votre accord.")).nvFont(.ui).foregroundStyle(NVColor.fgMuted)261 ForEach(list) { suggestion in262 KnowledgeRow(symbol: "link", tint: NVColor.ai, title: KnowledgeVocabulary.title(suggestion.fromTitle) + " ↔ " + KnowledgeVocabulary.title(suggestion.toTitle),263 detail: suggestion.rationale, action: suggestion.fromId.map { id in { model.open(pageId: id) } })264 }265 }266 }267 }268269 @ViewBuilder270 private var revisit: some View {271 let list = model.toRevisit272 if !list.isEmpty {273 KnowledgeSection(title: L("À revoir"), subtitle: L("Pages reliées que vous n'avez pas ouvertes depuis 30 jours"), count: list.count) {274 ForEach(list) { page in275 KnowledgeRow(symbol: "arrow.uturn.backward.circle", icon: page.icon, title: KnowledgeVocabulary.title(page.title),276 detail: page.updatedAt.map { LF("Modifiée le %@", FeatureFormat.day($0)) }, action: { model.open(pageId: page.id) })277 }278 }279 }280 }281}282