Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : SP ID & Card Vault7// File : SPVault/Core/Storage/Models.swift8// Module : SPVault9// Repository : https://git.spboucher.ai/sp-id-card-vault10// Project Website : Not specified11// Created : 2026-12-0212// Last Modified : 2026-12-0213//14// Author : Simon-Pierre Boucher15// Position : Professor of Finance16// Institution : Université du Québec en Outaouais (UQO)17// Organization : SP Boucher18// Website : https://spboucher.ai19// Git : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development : dev@spboucher.ai23// Support : support@spboucher.ai24// Security/Admin : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import Foundation4243/// sRGB colour stored with a card (dominant colour of the photograph).44struct RGB: Codable, Hashable, Sendable {45 var r: Double46 var g: Double47 var b: Double4849 static let titanium = RGB(r: 0.56, g: 0.58, b: 0.62)50 static let electric = RGB(r: 0.16, g: 0.47, b: 1.0)5152 var luminance: Double { 0.2126 * r + 0.7152 * g + 0.0722 * b }53}5455/// Physical format of a card. Rendering always keeps this aspect ratio.56enum CardFormat: Codable, Hashable, Sendable {57 /// ISO/IEC 7810 ID-1: 85.60 × 53.98 mm (bank cards, licences, health cards).58 case id159 /// ISO/IEC 7810 ID-3: 125 × 88 mm (passport data page).60 case id361 /// Any other document: width / height as photographed.62 case custom(aspect: Double)6364 /// Width divided by height.65 var aspectRatio: Double {66 switch self {67 case .id1: 85.60 / 53.9868 case .id3: 125.0 / 88.069 case .custom(let aspect): min(max(aspect, 0.4), 2.6)70 }71 }7273 /// Corner radius as a fraction of the width (ID-1: 3.18 mm of 85.60 mm).74 var cornerRadiusFraction: Double {75 switch self {76 case .id1: 3.18 / 85.6077 case .id3: 2.6 / 125.078 case .custom: 0.0379 }80 }8182 var label: String {83 switch self {84 case .id1: "ID-1 · 85.60 × 53.98 mm"85 case .id3: "ID-3 · 125 × 88 mm"86 case .custom: "Custom format"87 }88 }8990 /// Closest standard format for a measured aspect ratio, within 4 %.91 static func matching(aspect: Double) -> CardFormat {92 for format in [CardFormat.id1, .id3] where abs(format.aspectRatio - aspect) / format.aspectRatio < 0.04 {93 return format94 }95 return .custom(aspect: aspect)96 }97}9899enum CardKind: String, Codable, CaseIterable, Sendable {100 case driverLicense, healthCard, passport, citizenshipCard, residenceCard, otherIdentity101 case creditCard, debitCard, internationalBankCard, prepaidCard102 case autoInsurance, homeInsurance, medicalInsurance, travelInsurance103 case businessCard, universityCard, employeeCard, accessCard104 case loyaltyCard, subscription, membershipCard, customCard105106 var title: String {107 switch self {108 case .driverLicense: "Driver's Licence"109 case .healthCard: "Health Insurance Card"110 case .passport: "Passport"111 case .citizenshipCard: "Citizenship Card"112 case .residenceCard: "Residence Card"113 case .otherIdentity: "Other Identity Document"114 case .creditCard: "Credit Card"115 case .debitCard: "Debit Card"116 case .internationalBankCard: "International Bank Card"117 case .prepaidCard: "Prepaid Card"118 case .autoInsurance: "Auto Insurance"119 case .homeInsurance: "Home Insurance"120 case .medicalInsurance: "Medical Insurance"121 case .travelInsurance: "Travel Insurance"122 case .businessCard: "Business Card"123 case .universityCard: "University Card"124 case .employeeCard: "Employee Card"125 case .accessCard: "Access Card"126 case .loyaltyCard: "Loyalty Card"127 case .subscription: "Subscription"128 case .membershipCard: "Membership Card"129 case .customCard: "Custom Card"130 }131 }132133 var symbol: String {134 switch self {135 case .driverLicense: "car.fill"136 case .healthCard: "cross.case.fill"137 case .passport: "globe.americas.fill"138 case .citizenshipCard: "flag.fill"139 case .residenceCard: "house.lodge.fill"140 case .otherIdentity: "person.text.rectangle.fill"141 case .creditCard, .debitCard, .internationalBankCard, .prepaidCard: "creditcard.fill"142 case .autoInsurance: "car.side.fill"143 case .homeInsurance: "house.fill"144 case .medicalInsurance: "stethoscope"145 case .travelInsurance: "airplane"146 case .businessCard: "briefcase.fill"147 case .universityCard: "graduationcap.fill"148 case .employeeCard: "person.badge.shield.checkmark.fill"149 case .accessCard: "key.card.fill"150 case .loyaltyCard: "star.circle.fill"151 case .subscription: "arrow.triangle.2.circlepath"152 case .membershipCard: "person.2.fill"153 case .customCard: "rectangle.on.rectangle.angled"154 }155 }156157 var categoryID: String {158 switch self {159 case .driverLicense, .healthCard, .passport, .citizenshipCard, .residenceCard, .otherIdentity:160 CardCategory.identity.id161 case .creditCard, .debitCard, .internationalBankCard, .prepaidCard: CardCategory.banking.id162 case .autoInsurance, .homeInsurance, .medicalInsurance, .travelInsurance: CardCategory.insurance.id163 case .businessCard, .universityCard, .employeeCard, .accessCard: CardCategory.professional.id164 case .loyaltyCard, .subscription, .membershipCard, .customCard: CardCategory.other.id165 }166 }167168 /// Bank cards get the payment-card rules: masked number, last four digits in169 /// previews, CVV redaction on the back.170 var isBanking: Bool { categoryID == CardCategory.banking.id }171172 var defaultFormat: CardFormat { self == .passport ? .id3 : .id1 }173174 var numberLabel: String {175 switch self {176 case _ where isBanking: "Card number"177 case .passport: "Passport number"178 case .driverLicense: "Licence number"179 case .healthCard: "Health insurance number"180 case .autoInsurance, .homeInsurance, .medicalInsurance, .travelInsurance: "Policy number"181 case .loyaltyCard, .membershipCard, .subscription: "Member number"182 default: "Document number"183 }184 }185186 static func kinds(inCategory id: String) -> [CardKind] { allCases.filter { $0.categoryID == id } }187}188189struct CardCategory: Codable, Hashable, Identifiable, Sendable {190 var id: String191 var name: String192 var symbol: String193 var tint: RGB194 var isBuiltIn: Bool195196 static let identity = CardCategory(id: "identity", name: "My Identity", symbol: "person.text.rectangle.fill",197 tint: RGB(r: 0.16, g: 0.47, b: 1.0), isBuiltIn: true)198 static let banking = CardCategory(id: "banking", name: "My Banking", symbol: "creditcard.fill",199 tint: RGB(r: 0.72, g: 0.75, b: 0.80), isBuiltIn: true)200 static let insurance = CardCategory(id: "insurance", name: "My Insurance", symbol: "shield.lefthalf.filled",201 tint: RGB(r: 0.22, g: 0.70, b: 0.62), isBuiltIn: true)202 static let professional = CardCategory(id: "professional", name: "My Professional Cards",203 symbol: "briefcase.fill", tint: RGB(r: 0.55, g: 0.50, b: 0.95),204 isBuiltIn: true)205 static let other = CardCategory(id: "other", name: "My Other Cards", symbol: "rectangle.stack.fill",206 tint: RGB(r: 0.85, g: 0.62, b: 0.30), isBuiltIn: true)207208 static let builtIn: [CardCategory] = [identity, banking, insurance, professional, other]209}210211/// A free-form labelled value on a card ("Class", "Group number"…).212struct CardField: Codable, Hashable, Identifiable, Sendable {213 var id = UUID()214 var label: String215 var value: String216 /// Hidden in Privacy Mode and until a fresh authentication reveals it.217 var isSensitive: Bool = false218}219220enum CardSide: String, Codable, Sendable { case front, back }221222/// Everything known about one card except its photographs. The whole record is223/// encrypted at rest; nothing here is stored in clear. By design there is no field224/// for a CVV/CVC, a PIN or magnetic-stripe data.225struct Card: Codable, Identifiable, Hashable, Sendable {226 static let currentSchema = 2227228 var schemaVersion: Int = Card.currentSchema229 var id = UUID()230 var name: String231 var kind: CardKind232 var categoryID: String233 var issuer: String = ""234 var holderName: String = ""235 /// Full card or document number. Sensitive: masked by default.236 var number: String = ""237 var expiry: Date?238 var notes: String = ""239 var fields: [CardField] = []240 var dominantColor: RGB = .titanium241 var format: CardFormat = .id1242 var isFavorite: Bool = false243 var hasBack: Bool = false244 /// Days before expiry at which a local reminder fires (0 = the day itself).245 var reminderOffsets: [Int] = [30, 7, 0]246 var createdAt = Date()247 var modifiedAt = Date()248249 init(name: String, kind: CardKind, categoryID: String? = nil) {250 self.name = name251 self.kind = kind252 self.categoryID = categoryID ?? kind.categoryID253 self.format = kind.defaultFormat254 }255256 var digitsOfNumber: String { number.filter(\.isNumber) }257258 /// Last four characters of the number, the only part shown in previews.259 var last4: String {260 let compact = number.filter { $0.isNumber || $0.isLetter }261 return compact.count >= 4 ? String(compact.suffix(4)) : ""262 }263264 /// `•••• 4242` for bank cards, `••••4242` style for documents.265 var maskedNumber: String {266 guard !number.isEmpty else { return "" }267 let tail = last4268 if kind.isBanking { return "•••• •••• •••• " + (tail.isEmpty ? "••••" : tail) }269 return String(repeating: "•", count: max(4, min(8, number.count - tail.count))) + tail270 }271272 var formattedNumber: String {273 guard kind.isBanking else { return number }274 let digits = digitsOfNumber275 if digits.count == 15 { // 4-6-5 grouping276 let a = digits.prefix(4), b = digits.dropFirst(4).prefix(6), c = digits.dropFirst(10)277 return "\(a) \(b) \(c)"278 }279 return stride(from: 0, to: digits.count, by: 4).map { i -> String in280 let start = digits.index(digits.startIndex, offsetBy: i)281 let end = digits.index(start, offsetBy: 4, limitedBy: digits.endIndex) ?? digits.endIndex282 return String(digits[start..<end])283 }.joined(separator: " ")284 }285}286287enum ExpiryStatus: String, Sendable, CaseIterable {288 case valid, expiringSoon, expired, noExpiry289290 var title: String {291 switch self {292 case .valid: "Valid"293 case .expiringSoon: "Expiring soon"294 case .expired: "Expired"295 case .noExpiry: "No expiry"296 }297 }298}299300extension Card {301 /// Days until the end of the expiry day (negative once expired).302 func daysUntilExpiry(now: Date = Date(), calendar: Calendar = .current) -> Int? {303 guard let expiry else { return nil }304 let from = calendar.startOfDay(for: now), to = calendar.startOfDay(for: expiry)305 return calendar.dateComponents([.day], from: from, to: to).day306 }307308 func expiryStatus(now: Date = Date(), soonWithinDays: Int = 90) -> ExpiryStatus {309 guard let days = daysUntilExpiry(now: now) else { return .noExpiry }310 if days < 0 { return .expired }311 return days <= soonWithinDays ? .expiringSoon : .valid312 }313}314315/// Vault-wide encrypted state that is not a card: ordering, custom categories,316/// backup bookkeeping.317struct VaultManifest: Codable, Equatable, Sendable {318 static let currentSchema = 1319 var schemaVersion = VaultManifest.currentSchema320 var order: [UUID] = []321 var customCategories: [CardCategory] = []322 var lastBackupAt: Date?323 var lastRestoreAt: Date?324}325