Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : Immo-Ka Admin iOS9// File : ImmoKaAdmin/Features/AccountView.swift10// Description : compte de l'administrateur — ses clés d'accès (retirer,11// sauf la dernière), ajouter une clé sur un autre appareil,12// administrateurs, journal des actions, déconnexion.13// Module : ImmoKaAdmin14// Repository : https://git.spboucher.ai/immo-ka-admin-ios15// Project Website : https://www.immo-ka.com16// Created : 2026-11-3017// Last Modified : 2026-11-3018//19// =============================================================================20// AUTHOR & PROFESSIONAL AFFILIATION21// =============================================================================22//23// Author : Simon-Pierre Boucher24// Position : Professor of Finance25// Institution : Université du Québec en Outaouais (UQO)26// Department : Département des sciences administratives27// Organization : SP Boucher28//29// Website : https://spboucher.ai30// Git : https://git.spboucher.ai31//32// =============================================================================33// OFFICIAL CONTACT DIRECTORY34// =============================================================================35//36// General : info@spboucher.ai37// Professional : contact@spboucher.ai38// Direct : simon@spboucher.ai39// Research : research@spboucher.ai40// Development : dev@spboucher.ai41// Support : support@spboucher.ai42// Security/Admin : admin@spboucher.ai43// Notifications : notifications@spboucher.ai44//45// Preferred Contact: support@spboucher.ai46//47// =============================================================================48// COPYRIGHT & INTELLECTUAL PROPERTY49// =============================================================================50//51// Copyright (c) 202652// Simon-Pierre Boucher53//54// All rights reserved where applicable.55//56// This file is governed by the applicable project license,57// copyright notices, institutional agreements and relevant law.58//59// Unless expressly authorized by the applicable license or60// rights holder, copying, redistribution, sublicensing,61// publication and commercial exploitation are not permitted.62//63// Existing third-party rights and notices remain unaffected.64//65// =============================================================================66// CONFIDENTIALITY & SECURITY67// =============================================================================68//69// Classification : Public70// Distribution : Public repository; use is governed by the project license71// Security Contact : admin@spboucher.ai72//73// Access to this source does not independently grant permission74// to redistribute or disclose confidential materials.75//76// Do not embed credentials, private keys, access tokens,77// certificates or confidential personal information.78//79// =============================================================================80// LICENSE & MAINTENANCE81// =============================================================================82//83// License : None specified (no license file in this repository)84// Maintainer : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import SwiftUI9293struct AccountView: View {94 @Environment(AdminSession.self) private var session95 @Environment(Navigator.self) private var nav96 @State private var admins: [AdminAccount]?97 @State private var invitation: KeyInvitation?98 @State private var failure: String?99 @State private var busy = false100 @State private var toDelete: AccessKey?101 @State private var confirmSignOut = false102103 var body: some View {104 Form {105 if let failure { Section { ErrorBanner(text: failure).listRowInsets(EdgeInsets()) } }106 if let me = session.me {107 Section("Administrateur") {108 InfoRow(label: "Nom", value: me.admin.name)109 InfoRow(label: "Courriel", value: me.admin.email)110 if !me.admin.mailboxes.isEmpty { InfoRow(label: "Boîtes", value: me.admin.mailboxes.joined(separator: "\n")) }111 }112 Section {113 ForEach(me.keys) { key in114 HStack(spacing: 12) {115 Image(systemName: "key").foregroundStyle(Theme.ink2).frame(width: 24).accessibilityHidden(true)116 VStack(alignment: .leading, spacing: 2) {117 Text(verbatim: key.name).font(.subheadline.weight(.medium)).foregroundStyle(Theme.ink)118 Text(verbatim: "créée le \(Fmt.dateTime(key.createdAt)) · utilisée \(Fmt.relative(key.usedAt))").font(.caption).foregroundStyle(Theme.ink3)119 }120 Spacer()121 if me.keys.count > 1 {122 Button("Retirer", role: .destructive) { toDelete = key }.font(.subheadline).buttonStyle(.borderless).disabled(busy)123 .accessibilityLabel("Retirer la clé \(key.name)")124 }125 }126 .accessibilityElement(children: .combine)127 }128 Button { invite() } label: { Label("Ajouter une clé sur un autre appareil", systemImage: "plus") }129 .disabled(busy)130 .accessibilityIdentifier("account.invite")131 } header: {132 Text("Mes clés d'accès")133 } footer: {134 Text(me.keys.count > 1 ? "Retirer une clé empêche de se connecter avec elle. La dernière clé ne peut pas être retirée."135 : "C'est votre seule clé : elle ne peut pas être retirée. Ajoutez-en une sur un autre appareil pour ne pas dépendre d'un seul.")136 }137 }138 Section("Administrateurs") {139 if let admins {140 ForEach(admins) { a in141 VStack(alignment: .leading, spacing: 2) {142 HStack {143 Text(verbatim: a.name).font(.subheadline.weight(.medium)).foregroundStyle(Theme.ink)144 if !a.active { StatusTag(label: "Inactif", symbol: "pause.circle", tone: .warn) }145 }146 Text(verbatim: "\(a.email) · \(Fmt.plural(a.keys, "clé", "clés"))").font(.caption).foregroundStyle(Theme.ink3)147 }148 .accessibilityElement(children: .combine)149 }150 } else {151 ProgressView()152 }153 }154 Section {155 NavigationLink { JournalView() } label: { Label("Journal des actions", systemImage: "list.bullet.rectangle") }156 .accessibilityIdentifier("account.journal")157 }158 Section {159 Button("Se déconnecter") { confirmSignOut = true }.accessibilityIdentifier("account.signOut")160 } footer: {161 Text(verbatim: "Immo-Ka Admin \(Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "") (\(Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? "")) · \(AdminSession.baseURL().host ?? "")")162 }163 }164 .navigationTitle("Compte")165 .navigationBarTitleDisplayMode(.inline)166 .refreshable { await load() }167 .task { await load() }168 .sheet(item: $invitation) { InvitationSheet(invitation: $0) }169 .alert("Retirer cette clé d'accès ?", isPresented: Binding(get: { toDelete != nil }, set: { if !$0 { toDelete = nil } }), presenting: toDelete) { key in170 Button("Retirer la clé", role: .destructive) { remove(key) }171 Button("Annuler", role: .cancel) {}172 } message: { key in173 Text(verbatim: "« \(key.name) » ne pourra plus servir à se connecter à l'administration.")174 }175 .alert("Se déconnecter ?", isPresented: $confirmSignOut) {176 Button("Se déconnecter") { Task { await session.signOut() } }.accessibilityIdentifier("account.signOut.confirm")177 Button("Annuler", role: .cancel) {}178 } message: {179 Text("Il faudra votre clé d'accès pour revenir.")180 }181 }182183 private func load() async {184 do {185 try await session.load()186 admins = try await session.call { try await $0.admins() }187 failure = nil188 } catch {189 if session.isSignedIn { failure = AdminError.message(error) }190 }191 }192193 private func invite() {194 busy = true; failure = nil195 Task {196 defer { busy = false }197 do { invitation = try await session.call { try await $0.keyInvitation() } } catch { failure = AdminError.message(error) }198 }199 }200201 private func remove(_ key: AccessKey) {202 busy = true; failure = nil203 Task {204 defer { busy = false }205 do {206 try await session.call { try await $0.deleteKey(key.id) }207 nav.show("Clé retirée")208 await load()209 } catch { failure = AdminError.message(error) }210 }211 }212}213214extension KeyInvitation: Identifiable { var id: String { url } }215216/// Adresse à ouvrir sur l'autre appareil pour y créer une clé.217private struct InvitationSheet: View {218 let invitation: KeyInvitation219 @Environment(\.dismiss) private var dismiss220 var body: some View {221 NavigationStack {222 Form {223 Section {224 Text(verbatim: invitation.url).font(.footnote.monospaced()).foregroundStyle(Theme.ink).textSelection(.enabled)225 .accessibilityIdentifier("invitation.url")226 if let u = URL(string: invitation.url) {227 ShareLink(item: u) { Label("Partager l'adresse", systemImage: "square.and.arrow.up") }.accessibilityIdentifier("invitation.share")228 }229 } header: {230 Text("Adresse d'activation")231 } footer: {232 Text("Ouvrez cette adresse sur l'appareil à ajouter : dans son navigateur, ou collée dans Immo-Ka Admin (« J'ai une adresse d'activation »). Elle ne sert qu'une fois et expire dans \(Fmt.plural(invitation.expiresInDays ?? 1, "jour", "jours")). Ne la transmettez à personne d'autre : elle donne accès à votre compte d'administration.")233 }234 }235 .navigationTitle("Ajouter une clé")236 .navigationBarTitleDisplayMode(.inline)237 .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Terminé") { dismiss() } } }238 }239 .presentationDetents([.medium, .large])240 }241}242243struct JournalView: View {244 @Environment(AdminSession.self) private var session245 @State private var entries: [JournalEntry]?246 @State private var failure: String?247248 var body: some View {249 Loadable(value: entries, failure: failure, retry: { Task { await load() } }) { entries in250 List {251 if entries.isEmpty { EmptyState(symbol: "list.bullet.rectangle", title: "Aucune action consignée").listRowBackground(Color.clear) }252 ForEach(entries) { e in253 VStack(alignment: .leading, spacing: 3) {254 HStack(alignment: .firstTextBaseline) {255 Text(verbatim: e.actionLabel).font(.subheadline.weight(.medium)).foregroundStyle(Theme.ink)256 Spacer(minLength: 8)257 Text(verbatim: Fmt.dateTime(e.at)).font(.caption).monospacedDigit().foregroundStyle(Theme.ink3)258 }259 Text(verbatim: [e.admin, e.target, e.detail].filter { !$0.isEmpty }.joined(separator: " · ")).font(.caption).foregroundStyle(Theme.ink2)260 }261 .accessibilityElement(children: .combine)262 }263 }264 .listStyle(.plain)265 .refreshable { await load() }266 }267 .background(Theme.bg)268 .navigationTitle("Journal")269 .navigationBarTitleDisplayMode(.inline)270 .task { await load() }271 .accessibilityIdentifier("journal")272 }273274 private func load() async {275 do { entries = try await session.call { try await $0.journal() }; failure = nil } catch { if entries == nil { failure = AdminError.message(error) } }276 }277}278