Files
InvestmentTrackerApp/PortfolioJournal/Utilities/SharedQuickUpdate.swift
T
alexandrev-tibco 386f4ff265 Actualización sin cambiar de app: Share Extension "Quick Update" + clipboard auto-advance
El dolor: para actualizar cada source hay que saltar a la app del banco, copiar/
memorizar el valor y volver. iOS no permite ventanas flotantes editables (PiP es
solo vídeo), así que se resuelve con las dos vías sancionadas:

Share Extension (target nuevo PortfolioJournalQuickUpdate):
- Al compartir texto desde CUALQUIER app aparece "Portfolio Journal": mini-form
  sobre la app anfitriona con el importe pre-parseado del texto compartido y la
  siguiente source pendiente del mes preseleccionada. Guardar → sigues en el banco.
- Sin Core Data en la extensión: la app publica un espejo de sources activas en el
  App Group (SharedQuickUpdateSync.refreshMirror) y la extensión encola
  PendingQuickUpdate; la app los convierte en Snapshots reales al activarse
  (ingestPending). ExtSharedBridge duplica el contrato (keep-in-sync comentado).
- Parser de importes tolerante a locales (12.345,67 € / $1,234.56 / 1234,5).
- UI localizada en los 7 idiomas (lproj propios de la extensión).
- pbxproj: target app-extension completo (sync group, embed, dependency, configs)
  replicando el patrón del widget. Entitlements solo con App Group.

Clipboard auto-advance en Quick Update:
- Al volver a la app con un importe copiado: banner de un tap "Pegar X en <source>"
  que rellena la siguiente source vacía y avanza el foco a la siguiente.
- Badge NEXT en la fila activa; no repite sugerencias del mismo clipboard.

Script de upload: -allowProvisioningUpdates + API key también en el archive para
que el bundle id nuevo de la extensión se registre automáticamente.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015qUZrBusG82T37R7PeokqJ
2026-07-03 23:21:55 +02:00

143 lines
5.1 KiB
Swift

import Foundation
import CoreData
// MARK: - App Group bridge for the Quick Update share extension
//
// The share extension can't open the CloudKit-backed Core Data store, so the app
// maintains a lightweight mirror of active sources in the App Group defaults and
// the extension appends "pending updates" to a queue there. The app ingests the
// queue on every activation, creating real snapshots.
/// Snapshot of an active source, enough for the extension's picker.
struct SharedSourceInfo: Codable, Identifiable {
let id: UUID
let name: String
let latestValue: Double
let currencyCode: String
/// True when a value was already recorded this month (by app or extension).
var updatedThisMonth: Bool
}
/// A value captured from the share extension, waiting to become a Snapshot.
struct PendingQuickUpdate: Codable {
let sourceId: UUID
let amount: Double
let capturedAt: Date
}
enum SharedQuickUpdateStore {
private static let mirrorKey = "sharedSourceMirror"
private static let queueKey = "pendingQuickUpdates"
static var defaults: UserDefaults? {
UserDefaults(suiteName: AppConstants.appGroupIdentifier)
}
// MARK: Mirror (app writes, extension reads)
static func writeMirror(_ sources: [SharedSourceInfo]) {
guard let data = try? JSONEncoder().encode(sources) else { return }
defaults?.set(data, forKey: mirrorKey)
}
static func readMirror() -> [SharedSourceInfo] {
guard let data = defaults?.data(forKey: mirrorKey),
let decoded = try? JSONDecoder().decode([SharedSourceInfo].self, from: data) else { return [] }
return decoded
}
// MARK: Pending queue (extension writes, app drains)
static func appendPending(_ update: PendingQuickUpdate) {
var queue = readPending()
queue.append(update)
if let data = try? JSONEncoder().encode(queue) {
defaults?.set(data, forKey: queueKey)
}
// Optimistically mark the source as updated in the mirror so the extension
// suggests the next pending source on the following invocation.
var mirror = readMirror()
if let idx = mirror.firstIndex(where: { $0.id == update.sourceId }) {
mirror[idx].updatedThisMonth = true
writeMirror(mirror)
}
}
static func readPending() -> [PendingQuickUpdate] {
guard let data = defaults?.data(forKey: queueKey),
let decoded = try? JSONDecoder().decode([PendingQuickUpdate].self, from: data) else { return [] }
return decoded
}
static func clearPending() {
defaults?.removeObject(forKey: queueKey)
}
}
// MARK: - App-side sync & ingestion
enum SharedQuickUpdateSync {
/// Refreshes the source mirror for the extension. Call on app activation and
/// after snapshot saves.
@MainActor
static func refreshMirror() {
let context = CoreDataStack.shared.viewContext
let request = InvestmentSource.fetchRequest()
request.predicate = NSPredicate(format: "isActive == YES")
request.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]
guard let sources = try? context.fetch(request) else { return }
let settings = AppSettings.getOrCreate(in: context)
let calendar = Calendar.current
let monthStart = calendar.date(from: calendar.dateComponents([.year, .month], from: Date())) ?? Date()
let mirror = sources.map { source in
SharedSourceInfo(
id: source.id,
name: source.name,
latestValue: NSDecimalNumber(decimal: source.latestValue).doubleValue,
currencyCode: source.account?.currency ?? settings.currency,
updatedThisMonth: (source.latestSnapshot?.date ?? .distantPast) >= monthStart
)
}
SharedQuickUpdateStore.writeMirror(mirror)
}
/// Drains the extension's pending queue into real snapshots. Returns how many
/// snapshots were created. Call on app activation.
@MainActor
@discardableResult
static func ingestPending() -> Int {
let pending = SharedQuickUpdateStore.readPending()
guard !pending.isEmpty else { return 0 }
let context = CoreDataStack.shared.viewContext
let request = InvestmentSource.fetchRequest()
guard let sources = try? context.fetch(request) else { return 0 }
let byId = Dictionary(uniqueKeysWithValues: sources.map { ($0.id, $0) })
var created = 0
for update in pending {
guard let source = byId[update.sourceId] else { continue }
let snapshot = Snapshot(context: context)
snapshot.id = UUID()
snapshot.value = NSDecimalNumber(value: update.amount)
snapshot.date = update.capturedAt
snapshot.source = source
created += 1
}
if context.hasChanges {
do {
try context.save()
} catch {
print("Failed to ingest pending quick updates: \(error)")
return 0
}
}
SharedQuickUpdateStore.clearPending()
refreshMirror()
return created
}
}