SPB Git

Repository Public

AccountFlow.swift 35.4 KB 753 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Lou-Ka iOS9// File             : LouKa/Features/Account/AccountFlow.swift10// Description      : feuille du compte quand on n'est pas connecté — connexion,11//                    création d'un compte, code à six chiffres reçu par12//                    courriel, mot de passe oublié. Le compte est facultatif :13//                    la feuille se ferme à tout moment et rien dans l'app n'en14//                    dépend.15// Module           : LouKa16// Repository       : https://git.spboucher.ai/lou-ka-ios-v317// Project Website  : https://www.lou-ka.com18// Created          : 2026-11-3019// Last Modified    : 2026-11-3020//21// =============================================================================22// AUTHOR & PROFESSIONAL AFFILIATION23// =============================================================================24//25// Author           : Simon-Pierre Boucher26// Position         : Professor of Finance27// Institution      : Université du Québec en Outaouais (UQO)28// Department       : Département des sciences administratives29// Organization     : SP Boucher30//31// Website          : https://spboucher.ai32// Git              : https://git.spboucher.ai33//34// =============================================================================35// OFFICIAL CONTACT DIRECTORY36// =============================================================================37//38// General          : info@spboucher.ai39// Professional     : contact@spboucher.ai40// Direct           : simon@spboucher.ai41// Research         : research@spboucher.ai42// Development      : dev@spboucher.ai43// Support          : support@spboucher.ai44// Security/Admin   : admin@spboucher.ai45// Notifications    : notifications@spboucher.ai46//47// Preferred Contact: support@spboucher.ai48//49// =============================================================================50// COPYRIGHT & INTELLECTUAL PROPERTY51// =============================================================================52//53// Copyright (c) 202654// Simon-Pierre Boucher55//56// All rights reserved where applicable.57//58// This file is governed by the applicable project license,59// copyright notices, institutional agreements and relevant law.60//61// Unless expressly authorized by the applicable license or62// rights holder, copying, redistribution, sublicensing,63// publication and commercial exploitation are not permitted.64//65// Existing third-party rights and notices remain unaffected.66//67// =============================================================================68// CONFIDENTIALITY & SECURITY69// =============================================================================70//71// Classification   : Public72// Distribution     : Public repository; use is governed by the project license73// Security Contact : admin@spboucher.ai74//75// Access to this source does not independently grant permission76// to redistribute or disclose confidential materials.77//78// Do not embed credentials, private keys, access tokens,79// certificates or confidential personal information.80//81// =============================================================================82// LICENSE & MAINTENANCE83// =============================================================================84//85// License          : None specified (no license file in this repository)86// Maintainer       : Simon-Pierre Boucher87// Technical Contact: dev@spboucher.ai88//89// =============================================================================90// END OF SP BOUCHER SOURCE HEADER91// =============================================================================9293import SwiftUI94import UIKit9596// MARK: - Composants de formulaire9798/// Types de contenu des champs (trousseau iCloud, mots de passe robustes, code reçu par courriel).99/// `-LKNoAutoFill YES` (Debug) les retire : les feuilles du système (« Utiliser un mot de passe robuste ? »)100/// avalent sinon la frappe des tests d'interface.101enum AutoFill {102    static func type(_ t: UITextContentType) -> UITextContentType? {103        #if DEBUG104        if UserDefaults.standard.bool(forKey: "LKNoAutoFill") { return nil }105        #endif106        return t107    }108}109110/// Champ de formulaire : libellé au-dessus, contour de contrôle, message d'erreur dessous.111struct AccountField<Content: View>: View {112    let label: String113    var hint: String?114    var error: String?115    @ViewBuilder var content: () -> Content116117    var body: some View {118        VStack(alignment: .leading, spacing: 6) {119            Text(label).font(.subheadline.weight(.medium)).foregroundStyle(Theme.ink2)120            content()121                .font(.body)122                .foregroundStyle(Theme.ink)123                .padding(.horizontal, 14)124                .frame(minHeight: 50)125                .background(Theme.surface, in: RoundedRectangle(cornerRadius: Theme.radiusSmall, style: .continuous))126                .overlay(RoundedRectangle(cornerRadius: Theme.radiusSmall, style: .continuous)127                    .strokeBorder(error == nil ? Theme.lineControl : Theme.bad, lineWidth: error == nil ? 1 : 1.5))128            if let error {129                Label(error, systemImage: "exclamationmark.circle").font(.footnote).foregroundStyle(Theme.bad)130                    .fixedSize(horizontal: false, vertical: true)131            } else if let hint {132                Text(hint).font(.footnote).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true)133            }134        }135    }136}137138/// Mot de passe avec bouton afficher / masquer.139struct PasswordInput: View {140    let label: String141    @Binding var text: String142    var contentType: UITextContentType = .password143    var hint: String?144    var error: String?145    var identifier = "account.password"146    var onSubmit: () -> Void = {}147    @State private var visible = false148    @FocusState private var focus: Mode?149    private enum Mode { case hidden, shown }150151    var body: some View {152        AccountField(label: label, hint: hint, error: error) {153            HStack(spacing: 8) {154                // les deux champs coexistent : basculer l'affichage garde le curseur et le clavier en place155                ZStack {156                    SecureField("", text: $text)157                        .focused($focus, equals: .hidden)158                        .opacity(visible ? 0 : 1).disabled(visible).accessibilityHidden(visible)159                    TextField("", text: $text)160                        .focused($focus, equals: .shown)161                        .opacity(visible ? 1 : 0).disabled(!visible).accessibilityHidden(!visible)162                }163                .textContentType(AutoFill.type(contentType))164                .textInputAutocapitalization(.never)165                .autocorrectionDisabled()166                .submitLabel(.go)167                .onSubmit(onSubmit)168                .accessibilityLabel(label)169                .accessibilityIdentifier(identifier)170                Button {171                    let editing = focus != nil172                    visible.toggle()173                    // au tour suivant : le champ qui apparaît doit être actif avant de recevoir le curseur174                    if editing { Task { @MainActor in focus = visible ? .shown : .hidden } }175                } label: {176                    Image(systemName: visible ? "eye.slash" : "eye").foregroundStyle(Theme.ink3).frame(width: 44, height: 44)177                }178                .buttonStyle(.plain)179                .accessibilityLabel(visible ? "Masquer le mot de passe" : "Afficher le mot de passe")180                .accessibilityIdentifier(identifier + ".toggle")181                .padding(.trailing, -10)182            }183        }184    }185}186187/// Message d'erreur du serveur ou du réseau, lu par VoiceOver à son apparition.188struct AccountBanner: View {189    let text: String190    var tone: Tone = .error191    enum Tone { case error, info }192    var body: some View {193        Label(text, systemImage: tone == .error ? "exclamationmark.triangle" : "envelope")194            .font(.subheadline)195            .foregroundStyle(tone == .error ? Theme.bad : Theme.ink2)196            .fixedSize(horizontal: false, vertical: true)197            .padding(12)198            .frame(maxWidth: .infinity, alignment: .leading)199            .background(tone == .error ? Theme.badSoft : Theme.surface2, in: RoundedRectangle(cornerRadius: Theme.radiusSmall, style: .continuous))200            .accessibilityIdentifier(tone == .error ? "account.error" : "account.info")201            .onAppear { if tone == .error { UIAccessibility.post(notification: .announcement, argument: text) } }202    }203}204205/// Bouton principal pleine largeur, avec attente.206struct AccountSubmit: View {207    let title: String208    var busy = false209    var enabled = true210    var destructive = false211    var identifier = "account.submit"212    let action: () -> Void213    var body: some View {214        Button(action: action) {215            HStack(spacing: 10) {216                if busy { ProgressView().tint(Theme.brandInk) }217                Text(title)218            }219            .frame(maxWidth: .infinity)220        }221        .buttonStyle(PrimaryButtonStyle(tint: destructive ? Theme.bad : Theme.brand, foreground: destructive ? Theme.bg : Theme.brandInk))222        .opacity(enabled && !busy ? 1 : 0.55)223        .disabled(!enabled || busy)224        .accessibilityIdentifier(identifier)225    }226}227228/// Page d'une étape : porte, titre éditorial, phrase, contenu.229private struct AccountPage<Content: View>: View {230    let title: String231    let lead: String232    var navTitle = ""233    @ViewBuilder var content: () -> Content234    var body: some View {235        ScrollView {236            VStack(alignment: .leading, spacing: 22) {237                VStack(alignment: .leading, spacing: 10) {238                    DoorMark(angle: DoorGeometry.ajarAngle).frame(height: 40).accessibilityHidden(true)239                    Text(title).font(.editorial(28)).tracking(-0.2).foregroundStyle(Theme.ink)240                        .fixedSize(horizontal: false, vertical: true).accessibilityAddTraits(.isHeader)241                    Text(lead).font(.subheadline).foregroundStyle(Theme.ink2).lineSpacing(2).fixedSize(horizontal: false, vertical: true)242                }243                content()244            }245            .padding(.horizontal, 24).padding(.top, 8).padding(.bottom, 32)246            .frame(maxWidth: 480, alignment: .leading)247            .frame(maxWidth: .infinity)248        }249        .scrollDismissesKeyboard(.interactively)250        .background(Theme.bg)251        .navigationTitle(navTitle)252        .navigationBarTitleDisplayMode(.inline)253    }254}255256/// Erreur prête à afficher : celle d'un champ (`param`) ou générale.257struct AccountFailure: Equatable {258    var message: String259    var param: String?260    var code: String?261    init(_ error: Error) {262        let e = error as? AccountError263        message = e?.errorDescription ?? "Une erreur est survenue. Réessayez dans un instant."264        param = e?.param265        code = e?.code266    }267    init(message: String, param: String? = nil) { self.message = message; self.param = param }268    func on(_ field: String) -> String? { param == field ? message : nil }269    /// Message général : tout ce qui ne vise pas un des champs affichés.270    func general(fields: [String]) -> String? { param.map(fields.contains) == true ? nil : message }271}272273// MARK: - Courriel ou cellulaire274275/// Choix « Courriel » / « Cellulaire » (contrôle segmenté du Design System).276struct IdentifierModePicker: View {277    @Binding var mode: AccountIdentifier.Mode278    var body: some View {279        SlidingSegmented(selection: $mode, options: [(AccountIdentifier.Mode.email, "Courriel"), (AccountIdentifier.Mode.phone, "Cellulaire")],280                         label: "Identifiant du compte")281            .accessibilityIdentifier("account.mode")282    }283}284285/// Champ de l'identifiant : adresse courriel, ou numéro de cellulaire mis en forme pendant la frappe.286struct IdentifierInput: View {287    let mode: AccountIdentifier.Mode288    @Binding var email: String289    @Binding var phone: String290    /// `.username` à la connexion (le trousseau associe numéro et mot de passe), `.telephoneNumber` à l'inscription.291    var phoneContentType: UITextContentType = .telephoneNumber292    var emailHint: String?293    var phoneHint: String? = "Canada et États-Unis."294    var error: String?295    var submitLabel: SubmitLabel = .next296    var onSubmit: () -> Void = {}297298    var body: some View {299        if mode == .phone {300            AccountField(label: "Numéro de cellulaire", hint: phoneHint, error: error) {301                TextField("", text: $phone, prompt: Text(verbatim: "418 555-0123").foregroundStyle(Theme.ink3))302                    .textContentType(AutoFill.type(phoneContentType))303                    .keyboardType(.phonePad)304                    .autocorrectionDisabled()305                    .accessibilityLabel("Numéro de cellulaire, Canada et États-Unis")306                    .accessibilityIdentifier("account.phone")307                    .onChange(of: phone) { _, v in308                        let f = PhoneNumber.formatTyping(v)309                        if f != v { phone = f }310                    }311            }312        } else {313            AccountField(label: "Courriel", hint: emailHint, error: error) {314                TextField("", text: $email, prompt: Text(verbatim: "vous@exemple.com").foregroundStyle(Theme.ink3))315                    .textContentType(AutoFill.type(.username))316                    .keyboardType(.emailAddress)317                    .textInputAutocapitalization(.never)318                    .autocorrectionDisabled()319                    .submitLabel(submitLabel)320                    .onSubmit(onSubmit)321                    .accessibilityLabel("Courriel")322                    .accessibilityIdentifier("account.email")323            }324        }325    }326}327328private func identifier(_ mode: AccountIdentifier.Mode, email: String, phone: String) -> AccountIdentifier {329    mode == .phone ? .phone(phone) : .email(email)330}331332private func invalidIdentifier(_ id: AccountIdentifier) -> AccountFailure {333    id.mode == .phone ? AccountFailure(message: "Entrez un numéro de cellulaire à dix chiffres, du Canada ou des États-Unis.", param: "phone")334                      : AccountFailure(message: "Entrez une adresse courriel valide.", param: "email")335}336337// MARK: - Flux338339struct AccountFlow: View {340    enum Step: Hashable {341        case signUp342        /// `display` : l'adresse, ou le numéro mis en forme rendu par le serveur (« 418 555-0123 »)343        case code(AccountIdentifier, display: String)344        case forgot(AccountIdentifier.Mode, prefill: String)345        case reset(AccountIdentifier, display: String)346    }347348    @Environment(\.dismiss) private var dismiss349    @Environment(AppModel.self) private var app350    @Environment(Account.self) private var account351    @State private var path: [Step] = []352    /// Mode du formulaire de création ; « Utiliser plutôt une adresse courriel » le ramène au courriel.353    @State private var signUpMode: AccountIdentifier.Mode = .email354    /// Message montré sur le formulaire de création après une bascule vers le courriel.355    @State private var signUpNotice: String?356    var initial: [Step] = []357358    var body: some View {359        NavigationStack(path: $path) {360            SignInScreen(path: $path, done: finish)361                .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Fermer") { dismiss() }.accessibilityIdentifier("account.close") } }362                .navigationDestination(for: Step.self) { step in363                    switch step {364                    case .signUp: SignUpScreen(path: $path, mode: $signUpMode, notice: $signUpNotice)365                    case .code(let id, let display): CodeScreen(id: id, display: display, useEmail: useEmail, done: finish)366                    case .forgot(let mode, let prefill): ForgotScreen(mode: mode, prefill: prefill, path: $path)367                    case .reset(let id, let display): ResetScreen(id: id, display: display, done: finish)368                    }369                }370        }371        .tint(Theme.brand)372        .onAppear { if path.isEmpty, !initial.isEmpty { path = initial } }373        // le cellulaire n'est offert que si le serveur le dit ; sans réponse, courriel seulement374        .task { await account.loadOptions() }375    }376377    /// « Utiliser plutôt une adresse courriel » : retour au formulaire de création, en mode courriel ; le nom378    /// déjà saisi y est resté.379    private func useEmail(_ notice: String?) {380        signUpMode = .email381        signUpNotice = notice382        path = [.signUp]383    }384385    private func finish(_ message: String) {386        Haptics.success()387        dismiss()388        app.showToast(message)389    }390}391392// MARK: - Connexion393394private struct SignInScreen: View {395    @Binding var path: [AccountFlow.Step]396    var done: (String) -> Void397    @Environment(Account.self) private var account398    @State private var mode: AccountIdentifier.Mode = .email399    @State private var email = ""400    @State private var phone = ""401    @State private var password = ""402    @State private var busy = false403    @State private var failure: AccountFailure?404    @State private var restored = false405406    private var id: AccountIdentifier { identifier(mode, email: email, phone: phone) }407    private var filled: Bool { !(mode == .phone ? phone : email).isEmpty && !password.isEmpty }408409    var body: some View {410        AccountPage(title: "Connexion", lead: "Retrouvez vos favoris, vos notes et vos recherches sur tous vos appareils. Le compte est facultatif : Lou-Ka fonctionne aussi sans.") {411            // un compte par cellulaire se connecte toujours (aucun texto à la connexion) : le choix est toujours offert412            IdentifierModePicker(mode: $mode)413            if let m = failure?.general(fields: ["email", "phone", "password"]) { AccountBanner(text: m) }414            IdentifierInput(mode: mode, email: $email, phone: $phone, phoneContentType: .username, phoneHint: nil,415                            error: failure?.on("email") ?? failure?.on("phone"))416            PasswordInput(label: "Mot de passe", text: $password, contentType: .password, error: failure?.on("password"), onSubmit: submit)417            AccountSubmit(title: "Se connecter", busy: busy, enabled: filled, action: submit)418            Button("Mot de passe oublié ?") { path.append(.forgot(mode, prefill: mode == .phone ? phone : Account.clean(email))) }419                .font(.subheadline.weight(.medium)).frame(minHeight: 44)420                .accessibilityIdentifier("account.forgot")421            Divider().overlay(Theme.line)422            VStack(alignment: .leading, spacing: 10) {423                Text("Pas encore de compte ?").font(.subheadline).foregroundStyle(Theme.ink2)424                Button { path.append(.signUp) } label: { Text("Créer un compte").frame(maxWidth: .infinity) }425                    .buttonStyle(SoftButtonStyle())426                    .accessibilityIdentifier("account.create")427            }428        }429        .onAppear { if !restored { restored = true; mode = account.lastMode } }   // seul le mode est mémorisé, jamais le numéro430        .onChange(of: mode) { _, _ in failure = nil }431    }432433    private func submit() {434        guard !busy else { return }435        let id = self.id436        guard id.looksValid else { failure = invalidIdentifier(id); return }437        guard !password.isEmpty else { return }438        failure = nil; busy = true439        Task {440            defer { busy = false }441            do {442                try await account.signIn(id, password: password)443                done(account.user?.isManager == true ? "Vous êtes connecté." : "Vous êtes connecté. Vos favoris sont synchronisés.")444            } catch let e as AccountError where e.code == "courriel_non_verifie" || e.code == "telephone_non_verifie" {445                // bon mot de passe, adresse ou numéro pas encore confirmé : un nouveau code vient de partir446                path.append(.code(id, display: id.display))447            } catch {448                failure = AccountFailure(error)449            }450        }451    }452}453454// MARK: - Création455456private struct SignUpScreen: View {457    @Binding var path: [AccountFlow.Step]458    @Binding var mode: AccountIdentifier.Mode459    @Binding var notice: String?460    @Environment(Account.self) private var account461    @State private var name = ""462    @State private var email = ""463    @State private var phone = ""464    @State private var password = ""465    @State private var busy = false466    @State private var failure: AccountFailure?467468    private var id: AccountIdentifier { identifier(mode, email: email, phone: phone) }469    private var phoneOffered: Bool { account.options.phoneSignup }470471    var body: some View {472        AccountPage(title: "Créer un compte", lead: phoneOffered ? "Une adresse courriel ou un numéro de cellulaire, et un mot de passe. Vos favoris actuels seront gardés dans votre compte."473                                                               : "Un courriel et un mot de passe suffisent. Vos favoris actuels seront gardés dans votre compte.") {474            if phoneOffered { IdentifierModePicker(mode: $mode) }475            if let notice { AccountBanner(text: notice, tone: .info) }476            if let m = failure?.general(fields: ["email", "phone", "password", "name"]) { AccountBanner(text: m) }477            AccountField(label: "Nom (facultatif)", error: failure?.on("name")) {478                TextField("", text: $name)479                    .textContentType(AutoFill.type(.name))480                    .textInputAutocapitalization(.words)481                    .submitLabel(.next)482                    .accessibilityLabel("Nom, facultatif")483                    .accessibilityIdentifier("account.name")484            }485            IdentifierInput(mode: mode, email: $email, phone: $phone, emailHint: "Un code de confirmation y sera envoyé.",486                            phoneHint: "Canada et États-Unis. Un code de confirmation vous sera envoyé par texto ; des frais de messagerie de votre opérateur peuvent s'appliquer.",487                            error: failure?.on("email") ?? failure?.on("phone"))488            PasswordInput(label: "Mot de passe", text: $password, contentType: .newPassword,489                          hint: "Au moins \(Account.passwordMin) caractères.", error: failure?.on("password"), onSubmit: submit)490            AccountSubmit(title: mode == .phone ? "Recevoir le code par texto" : "Créer mon compte", busy: busy,491                          enabled: !(mode == .phone ? phone : email).isEmpty && !password.isEmpty, action: submit)492            Text(mode == .phone493                 ? "En créant un compte, vous acceptez que Lou-Ka garde votre numéro de cellulaire, votre nom et les éléments que vous enregistrez (favoris, notes, recherches) pour vous les rendre sur vos appareils. Le numéro sert seulement à confirmer votre compte et à choisir un nouveau mot de passe. Aucun suivi, aucune publicité, aucun texto promotionnel. Vous pouvez supprimer votre compte à tout moment."494                 : "En créant un compte, vous acceptez que Lou-Ka garde votre courriel, votre nom et les éléments que vous enregistrez (favoris, notes, recherches) pour vous les rendre sur vos appareils. Aucun suivi, aucune publicité. Vous pouvez supprimer votre compte à tout moment.")495                .font(.footnote).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true)496        }497        .navigationTitle("Nouveau compte")498        .onChange(of: mode) { _, m in failure = nil; if m == .phone { notice = nil } }499        // le serveur n'offre plus le cellulaire (ou n'a pas répondu) : courriel500        .onChange(of: phoneOffered, initial: true) { _, offered in if !offered { mode = .email } }501    }502503    private func submit() {504        guard !busy else { return }505        let id = self.id506        guard id.looksValid else { failure = invalidIdentifier(id); return }507        guard password.count >= Account.passwordMin else {508            failure = AccountFailure(message: "Le mot de passe doit compter au moins \(Account.passwordMin) caractères.", param: "password"); return509        }510        failure = nil; busy = true511        Task {512            defer { busy = false }513            do {514                let sent = try await account.signUp(id, password: password, name: name)515                notice = nil516                path.append(.code(id, display: id.mode == .phone ? (sent.phoneDisplay ?? id.display) : id.display))517            } catch let e as AccountError where e.code == "sms_indisponible" {518                // la passerelle de textos ne peut pas envoyer : le courriel reste offert, le nom saisi est gardé519                mode = .email520                notice = "\(e.errorDescription ?? "Les textos ne sont pas disponibles pour le moment.") Vous pouvez créer votre compte avec une adresse courriel."521            } catch {522                failure = AccountFailure(error)523            }524        }525    }526}527528// MARK: - Code à six chiffres529530/// Saisie du code : six chiffres, proposés par le clavier quand le courriel ou le texto arrive (`oneTimeCode`).531struct CodeInput: View {532    @Binding var code: String533    var error: String?534    var onComplete: () -> Void = {}535    @FocusState private var focused: Bool536537    var body: some View {538        AccountField(label: "Code à 6 chiffres", error: error) {539            TextField("", text: $code, prompt: Text(verbatim: "000000").foregroundStyle(Theme.ink3.opacity(0.5)))540                .textContentType(AutoFill.type(.oneTimeCode))541                .keyboardType(.numberPad)542                .font(.system(.title2, design: .default).weight(.semibold)).monospacedDigit().tracking(6)543                .focused($focused)544                .accessibilityLabel("Code à 6 chiffres")545                .accessibilityIdentifier("account.code")546                .onChange(of: code) { _, v in547                    let digits = Account.codeDigits(v)548                    if digits != v { code = digits }549                    if digits.count == 6 { onComplete() }550                }551        }552        .onAppear { focused = true }553    }554}555556/// Résultat d'une demande de renvoi : parti, ou refusé (avec l'attente demandée par le serveur sur un 429).557enum ResendOutcome { case sent, failed(retryAfter: Int?) }558559/// Renvoi d'un courriel ou d'un texto, au plus une fois par minute ; sur un 429, le bouton attend le délai du serveur.560struct ResendButton: View {561    let title: String562    var sentText = "Un nouveau courriel vient de partir."563    var action: () async -> ResendOutcome564    @State private var remaining = 60565    @State private var sending = false566    @State private var sent = false567568    var body: some View {569        VStack(alignment: .leading, spacing: 4) {570            Button {571                sending = true572                Task {573                    switch await action() {574                    case .sent: sent = true; remaining = 60575                    case .failed(let wait): sent = false; if let wait, wait > 0 { remaining = min(wait, 3600) }576                    }577                    sending = false578                }579            } label: {580                Text(remaining > 0 ? "\(title) (dans \(AccountError.delay(remaining)))" : title).monospacedDigit()581            }582            .font(.subheadline.weight(.medium))583            .frame(minHeight: 44)584            .disabled(remaining > 0 || sending)585            .accessibilityIdentifier("account.resend")586            .accessibilityLabel(remaining > 0 ? "\(title), possible dans \(AccountError.delay(remaining))" : title)587            if sent { Text(sentText).font(.footnote).foregroundStyle(Theme.ink3) }588        }589        .task(id: remaining > 0) {590            while remaining > 0 {591                try? await Task.sleep(for: .seconds(1))592                if Task.isCancelled { return }593                remaining -= 1594            }595        }596    }597}598599private func resendOutcome(_ error: Error) -> ResendOutcome { .failed(retryAfter: (error as? AccountError)?.retryAfter) }600601private struct CodeScreen: View {602    let id: AccountIdentifier603    let display: String604    /// Retour à la création en mode courriel, avec un message éventuel.605    var useEmail: (String?) -> Void606    var done: (String) -> Void607    @Environment(Account.self) private var account608    @State private var code = ""609    @State private var busy = false610    @State private var failure: AccountFailure?611612    private var sms: Bool { id.mode == .phone }613614    var body: some View {615        AccountPage(title: sms ? "Vérifiez vos textos" : "Vérifiez votre courriel",616                    lead: sms ? "Nous avons envoyé un code par texto au \(display). Il est valide 10 minutes."617                              : "Nous avons envoyé un code à 6 chiffres à \(display). Il est valide 60 minutes. Pensez à regarder dans les indésirables.") {618            if let m = failure?.general(fields: ["code"]) { AccountBanner(text: m) }619            CodeInput(code: $code, error: failure?.on("code"), onComplete: submit)620            AccountSubmit(title: "Confirmer", busy: busy, enabled: code.count == 6, action: submit)621            ResendButton(title: sms ? "Renvoyer le texto" : "Renvoyer le courriel", sentText: sms ? "Un nouveau texto vient de partir." : "Un nouveau courriel vient de partir.") {622                do { try await account.resendCode(id); failure = nil; return .sent } catch {623                    failure = AccountFailure(error)   // message du serveur ; sur un 429, le bouton attend le délai624                    return resendOutcome(error)625                }626            }627            if sms {628                Button("Utiliser plutôt une adresse courriel") { useEmail(nil) }629                    .font(.subheadline.weight(.medium)).frame(minHeight: 44)630                    .accessibilityIdentifier("account.useEmail")631            }632        }633        .navigationTitle("Confirmation")634    }635636    private func submit() {637        guard !busy, code.count == 6 else { return }638        failure = nil; busy = true639        Task {640            defer { busy = false }641            do {642                try await account.verify(id, code: code)643                done(account.user?.isManager == true ? "Adresse confirmée. Votre demande d'accès est en attente de validation." : "Compte confirmé. Vos favoris sont synchronisés.")644            } catch {645                failure = AccountFailure(error)646                if failure?.code == "code_invalide" { code = "" }647            }648        }649    }650}651652// MARK: - Mot de passe oublié653654private struct ForgotScreen: View {655    @State var mode: AccountIdentifier.Mode656    let prefill: String657    @Binding var path: [AccountFlow.Step]658    @Environment(Account.self) private var account659    @State private var email = ""660    @State private var phone = ""661    @State private var filledIn = false662    @State private var busy = false663    @State private var failure: AccountFailure?664665    private var id: AccountIdentifier { identifier(mode, email: email, phone: phone) }666    /// Par cellulaire seulement si le serveur envoie des textos (ou si l'on arrive déjà en mode cellulaire).667    private var phoneOffered: Bool { account.options.phoneSignup }668669    var body: some View {670        AccountPage(title: "Mot de passe oublié",671                    lead: mode == .phone ? "Indiquez le numéro de cellulaire de votre compte. Si un compte existe à ce numéro, vous recevrez un code par texto pour choisir un nouveau mot de passe ; des frais de messagerie de votre opérateur peuvent s'appliquer."672                                         : "Indiquez le courriel de votre compte. Si un compte existe à cette adresse, vous recevrez un code pour choisir un nouveau mot de passe.") {673            if phoneOffered || mode == .phone { IdentifierModePicker(mode: $mode) }674            if let m = failure?.general(fields: ["email", "phone"]) { AccountBanner(text: m) }675            IdentifierInput(mode: mode, email: $email, phone: $phone, phoneContentType: .username,676                            error: failure?.on("email") ?? failure?.on("phone"), submitLabel: .go, onSubmit: submit)677            AccountSubmit(title: mode == .phone ? "Recevoir le code par texto" : "Envoyer le code", busy: busy,678                          enabled: !(mode == .phone ? phone : email).isEmpty, action: submit)679        }680        .navigationTitle("Mot de passe")681        .onAppear {682            guard !filledIn else { return }683            filledIn = true684            if mode == .phone { phone = prefill } else { email = prefill }685        }686        .onChange(of: mode) { _, _ in failure = nil }687    }688689    private func submit() {690        guard !busy else { return }691        let id = self.id692        guard id.looksValid else { failure = invalidIdentifier(id); return }693        failure = nil; busy = true694        Task {695            defer { busy = false }696            do {697                try await account.forgotPassword(id)698                path.append(.reset(id, display: id.display))699            } catch let e as AccountError where e.code == "sms_indisponible" {700                failure = AccountFailure(message: "\(e.errorDescription ?? "Les textos ne sont pas disponibles pour le moment.") Si votre compte a une adresse courriel, utilisez-la.")701            } catch {702                failure = AccountFailure(error)703            }704        }705    }706}707708private struct ResetScreen: View {709    let id: AccountIdentifier710    let display: String711    var done: (String) -> Void712    @Environment(Account.self) private var account713    @State private var code = ""714    @State private var password = ""715    @State private var busy = false716    @State private var failure: AccountFailure?717718    private var sms: Bool { id.mode == .phone }719720    var body: some View {721        AccountPage(title: "Nouveau mot de passe",722                    lead: sms ? "Entrez le code reçu par texto au \(display) (valide 10 minutes), puis choisissez un nouveau mot de passe. Vos autres appareils seront déconnectés."723                              : "Entrez le code envoyé à \(display) (valide 30 minutes), puis choisissez un nouveau mot de passe. Vos autres appareils seront déconnectés.") {724            if let m = failure?.general(fields: ["code", "password"]) { AccountBanner(text: m) }725            CodeInput(code: $code, error: failure?.on("code"))726            PasswordInput(label: "Nouveau mot de passe", text: $password, contentType: .newPassword,727                          hint: "Au moins \(Account.passwordMin) caractères.", error: failure?.on("password"), identifier: "account.newPassword", onSubmit: submit)728            AccountSubmit(title: "Changer le mot de passe", busy: busy, enabled: code.count == 6 && !password.isEmpty, action: submit)729            ResendButton(title: sms ? "Renvoyer le texto" : "Renvoyer le courriel", sentText: sms ? "Un nouveau texto vient de partir." : "Un nouveau courriel vient de partir.") {730                do { try await account.forgotPassword(id); failure = nil; return .sent } catch { failure = AccountFailure(error); return resendOutcome(error) }731            }732        }733        .navigationTitle("Mot de passe")734    }735736    private func submit() {737        guard !busy, code.count == 6 else { return }738        guard password.count >= Account.passwordMin else {739            failure = AccountFailure(message: "Le mot de passe doit compter au moins \(Account.passwordMin) caractères.", param: "password"); return740        }741        failure = nil; busy = true742        Task {743            defer { busy = false }744            do {745                try await account.resetPassword(id, code: code, password: password)746                done("Mot de passe changé. Vous êtes connecté.")747            } catch {748                failure = AccountFailure(error)749            }750        }751    }752}753
Files main
Menu

Theme